server-list-and-volume-updates-20040730
[openafs.git] / src / WINNT / afsd / cm_conn.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afs/param.h>
11 #include <afs/stds.h>
12
13 #ifndef DJGPP
14 #include <windows.h>
15 #endif /* !DJGPP */
16 #include <string.h>
17 #include <malloc.h>
18 #include <osi.h>
19 #include <rx/rx.h>
20 #ifndef DJGPP
21 #include <rx/rxkad.h>
22 #else
23 #include <rx/rxkad.h>
24 #endif
25
26 #include "afsd.h"
27
28 osi_rwlock_t cm_connLock;
29
30 long RDRtimeout = CM_CONN_DEFAULTRDRTIMEOUT;
31 long ConnDeadtimeout = CM_CONN_CONNDEADTIME;
32 long HardDeadtimeout = CM_CONN_HARDDEADTIME;
33
34 #define LANMAN_WKS_PARAM_KEY "SYSTEM\\CurrentControlSet\\Services\\lanmanworkstation\\parameters"
35 #define LANMAN_WKS_SESSION_TIMEOUT "SessTimeout"
36
37 afs_int32 cryptall = 0;
38
39 void cm_PutConn(cm_conn_t *connp)
40 {
41         lock_ObtainWrite(&cm_connLock);
42         osi_assert(connp->refCount-- > 0);
43         lock_ReleaseWrite(&cm_connLock);
44 }
45
46 void cm_InitConn(void)
47 {
48         static osi_once_t once;
49         long code;
50         DWORD sessTimeout;
51         HKEY parmKey;
52         
53     if (osi_Once(&once)) {
54                 lock_InitializeRWLock(&cm_connLock, "connection global lock");
55
56         /* keisa - read timeout value for lanmanworkstation  service.
57          * jaltman - as per 
58          *   http://support.microsoft.com:80/support/kb/articles/Q102/0/67.asp&NoWebContent=1
59          * the SessTimeout is a minimum timeout not a maximum timeout.  Therefore, 
60          * I believe that the default should not be short.  Instead, we should wait until
61          * RX times out before reporting a timeout to the SMB client.
62          */
63                 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, LANMAN_WKS_PARAM_KEY,
64                             0, KEY_QUERY_VALUE, &parmKey);
65                 if (code == ERROR_SUCCESS)
66         {
67                     DWORD dummyLen = sizeof(sessTimeout);
68                     code = RegQueryValueEx(parmKey, LANMAN_WKS_SESSION_TIMEOUT, NULL, NULL, 
69                                    (BYTE *) &sessTimeout, &dummyLen);
70                     if (code == ERROR_SUCCESS)
71             {
72                 afsi_log("lanmanworkstation : SessTimeout %d", sessTimeout);
73                 RDRtimeout = sessTimeout;
74                 if ( ConnDeadtimeout < RDRtimeout + 15 ) {
75                     ConnDeadtimeout = RDRtimeout + 15;
76                     afsi_log("ConnDeadTimeout increased to %d", ConnDeadtimeout);
77                 }
78                 if ( HardDeadtimeout < 2 * ConnDeadtimeout ) {
79                     HardDeadtimeout = 2 * ConnDeadtimeout;
80                     afsi_log("HardDeadTimeout increased to %d", HardDeadtimeout);
81                 }
82             }
83         }
84
85         osi_EndOnce(&once);
86     }
87 }
88
89 void cm_InitReq(cm_req_t *reqp)
90 {
91         memset((char *)reqp, 0, sizeof(cm_req_t));
92 #ifndef DJGPP
93         reqp->startTime = GetCurrentTime();
94 #else
95         gettimeofday(&reqp->startTime, NULL);
96 #endif
97  
98 }
99
100 long cm_GetServerList(struct cm_fid *fidp, struct cm_user *userp,
101         struct cm_req *reqp, cm_serverRef_t **serverspp)
102 {
103         long code;
104     cm_volume_t *volp = NULL;
105     cm_cell_t *cellp = NULL;
106
107     if (!fidp) {
108                 *serverspp = NULL;
109                 return 0;
110         }
111
112         cellp = cm_FindCellByID(fidp->cell);
113     if (!cellp) return CM_ERROR_NOSUCHCELL;
114
115     code = cm_GetVolumeByID(cellp, fidp->volume, userp, reqp, &volp);
116     if (code) return code;
117     
118     *serverspp = cm_GetVolServers(volp, fidp->volume);
119
120     cm_PutVolume(volp);
121         return 0;
122 }
123
124 /*
125  * Analyze the error return from an RPC.  Determine whether or not to retry,
126  * and if we're going to retry, determine whether failover is appropriate,
127  * and whether timed backoff is appropriate.
128  *
129  * If the error code is from cm_Conn() or friends, it will be a CM_ERROR code.
130  * Otherwise it will be an RPC code.  This may be a UNIX code (e.g. EDQUOT), or
131  * it may be an RX code, or it may be a special code (e.g. VNOVOL), or it may
132  * be a security code (e.g. RXKADEXPIRED).
133  *
134  * If the error code is from cm_Conn() or friends, connp will be NULL.
135  *
136  * For VLDB calls, fidp will be NULL.
137  *
138  * volSyncp and/or cbrp may also be NULL.
139  */
140 int
141 cm_Analyze(cm_conn_t *connp, cm_user_t *userp, cm_req_t *reqp,
142         struct cm_fid *fidp, 
143         AFSVolSync *volSyncp, 
144         cm_serverRef_t * serversp,
145         cm_callbackRequest_t *cbrp, long errorCode)
146 {
147         cm_server_t *serverp;
148         cm_serverRef_t *tsrp;
149         cm_ucell_t *ucellp;
150     int retry = 0;
151     int free_svr_list = 0;
152         int dead_session;
153         
154         osi_Log2(afsd_logp, "cm_Analyze connp 0x%x, code %d",
155                  (long) connp, errorCode);
156
157         /* no locking required, since connp->serverp never changes after
158          * creation */
159         dead_session = (userp->cellInfop == NULL);
160         if (connp)
161                 serverp = connp->serverp;
162
163         /* Update callback pointer */
164     if (cbrp && errorCode == 0) 
165         cbrp->serverp = connp->serverp;
166
167         /* If not allowed to retry, don't */
168         if (reqp->flags & CM_REQ_NORETRY)
169                 goto out;
170
171         /* if timeout - check that it did not exceed the SMB timeout
172            and retry */
173         if (errorCode == CM_ERROR_TIMEDOUT)
174     {
175             long timeUsed, timeLeft;
176             /* timeleft - get if from reqp the same way as cmXonnByMServers does */
177 #ifndef DJGPP
178             timeUsed = (GetCurrentTime() - reqp->startTime) / 1000;
179 #else
180             gettimeofday(&now, NULL);
181             timeUsed = sub_time(now, reqp->startTime) / 1000;
182 #endif
183             
184             /* leave 5 seconds margin for sleep */
185             timeLeft = RDRtimeout - timeUsed;
186             if (timeLeft > 5)
187         {
188             thrd_Sleep(3000);
189             cm_CheckServers(CM_FLAG_CHECKDOWNSERVERS, NULL);
190             retry = 1;
191         } 
192     }
193
194     /* if all servers are offline, mark them non-busy and start over */
195         if (errorCode == CM_ERROR_ALLOFFLINE) {
196             osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_ALLOFFLINE.");
197             thrd_Sleep(5000);
198             /* cm_ForceUpdateVolume marks all servers as non_busy */
199                 /* No it doesn't and it won't do anything if all of the 
200                  * the servers are marked as DOWN.  So clear the DOWN
201                  * flag and reset the busy state as well.
202                  */
203         if (!serversp) {
204             cm_GetServerList(fidp, userp, reqp, &serversp);
205             free_svr_list = 1;
206         }
207         if (serversp) {
208             lock_ObtainWrite(&cm_serverLock);
209             for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
210                 tsrp->server->flags &= ~CM_SERVERFLAG_DOWN;
211                 if (tsrp->status == busy)
212                     tsrp->status = not_busy;
213             }
214             lock_ReleaseWrite(&cm_serverLock);
215             if (free_svr_list)
216                 cm_FreeServerList(&serversp);
217             retry = 1;
218         }
219
220         if (fidp != NULL)   /* Not a VLDB call */
221             cm_ForceUpdateVolume(fidp, userp, reqp);
222         }
223
224         /* if all servers are busy, mark them non-busy and start over */
225         if (errorCode == CM_ERROR_ALLBUSY) {
226         if (!serversp) {
227             cm_GetServerList(fidp, userp, reqp, &serversp);
228             free_svr_list = 1;
229         }
230                 lock_ObtainWrite(&cm_serverLock);
231                 for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
232                         if (tsrp->status == busy)
233                                 tsrp->status = not_busy;
234                 }
235         lock_ReleaseWrite(&cm_serverLock);
236         if (free_svr_list)
237             cm_FreeServerList(&serversp);
238                 thrd_Sleep(5000);
239                 retry = 1;
240         }
241
242         /* special codes:  VBUSY and VRESTARTING */
243         if (errorCode == VBUSY || errorCode == VRESTARTING) {
244         if (!serversp) {
245             cm_GetServerList(fidp, userp, reqp, &serversp);
246             free_svr_list = 1;
247         }
248                 lock_ObtainWrite(&cm_serverLock);
249                 for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
250                         if (tsrp->server == serverp
251                             && tsrp->status == not_busy) {
252                                 tsrp->status = busy;
253                                 break;
254                         }
255                 }
256         lock_ReleaseWrite(&cm_serverLock);
257         if (free_svr_list)
258             cm_FreeServerList(&serversp);
259                 retry = 1;
260         }
261
262         /* special codes:  missing volumes */
263         if (errorCode == VNOVOL || errorCode == VMOVED || errorCode == VOFFLINE
264             || errorCode == VSALVAGE || errorCode == VNOSERVICE) {
265                 /* Log server being offline for this volume */
266                 osi_Log4(afsd_logp, "cm_Analyze found server %d.%d.%d.%d marked offline for a volume",
267                          ((serverp->addr.sin_addr.s_addr & 0xff)),
268                          ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
269                          ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
270                          ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
271                 /* Create Event Log message */ 
272                 {
273                     HANDLE h;
274                     char *ptbuf[1];
275                     char s[100];
276                     h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
277                     sprintf(s, "cm_Analyze: Server %d.%d.%d.%d reported volume %d as missing.",
278                             ((serverp->addr.sin_addr.s_addr & 0xff)),
279                             ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
280                             ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
281                             ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24),
282                             fidp->volume);
283                     ptbuf[0] = s;
284                     ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1009, NULL,
285                                 1, 0, ptbuf, NULL);
286                     DeregisterEventSource(h);
287                 }
288
289                 /* Mark server offline for this volume */
290         if (!serversp) {
291             cm_GetServerList(fidp, userp, reqp, &serversp);
292             free_svr_list = 1;
293         }
294                 for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
295                         if (tsrp->server == serverp)
296                                 tsrp->status = offline;
297                 }
298         if (free_svr_list)
299             cm_FreeServerList(&serversp);
300                 retry = 1;
301         }
302
303         /* RX codes */
304         if (errorCode == RX_CALL_TIMEOUT) {
305                 /* server took longer than hardDeadTime 
306                  * don't mark server as down but don't retry
307                  * this is to prevent the SMB session from timing out
308                  * In addition, we log an event to the event log 
309                  */
310 #ifndef DJGPP
311                 HANDLE h;
312                 char *ptbuf[1];
313                 char s[100];
314                 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
315                 sprintf(s, "cm_Analyze: HardDeadTime exceeded.");
316                 ptbuf[0] = s;
317                 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1009, NULL,
318                         1, 0, ptbuf, NULL);
319                 DeregisterEventSource(h);
320 #endif /* !DJGPP */
321           
322                 retry = 0;
323                 osi_Log0(afsd_logp, "cm_Analyze: hardDeadTime exceeded");
324         }
325         else if (errorCode >= -64 && errorCode < 0) {
326                 /* mark server as down */
327                 lock_ObtainMutex(&serverp->mx);
328         serverp->flags |= CM_SERVERFLAG_DOWN;
329                 lock_ReleaseMutex(&serverp->mx);
330         retry = 1;
331     }
332
333         if (errorCode == RXKADEXPIRED && !dead_session) {
334                 lock_ObtainMutex(&userp->mx);
335                 ucellp = cm_GetUCell(userp, serverp->cellp);
336                 if (ucellp->ticketp) {
337                         free(ucellp->ticketp);
338                         ucellp->ticketp = NULL;
339                 }
340                 ucellp->flags &= ~CM_UCELLFLAG_RXKAD;
341                 ucellp->gen++;
342                 lock_ReleaseMutex(&userp->mx);
343                 retry = 1;
344         }
345
346         if (retry && dead_session)
347                 retry = 0;
348  
349 out:
350         /* drop this on the way out */
351         if (connp)
352                 cm_PutConn(connp);
353
354         /* retry until we fail to find a connection */
355         return retry;
356 }
357
358 long cm_ConnByMServers(cm_serverRef_t *serversp, cm_user_t *usersp,
359         cm_req_t *reqp, cm_conn_t **connpp)
360 {
361         long code;
362         cm_serverRef_t *tsrp;
363     cm_server_t *tsp;
364     long firstError = 0;
365         int someBusy = 0, someOffline = 0, allBusy = 1, allDown = 1;
366         long timeUsed, timeLeft, hardTimeLeft;
367 #ifdef DJGPP
368     struct timeval now;
369 #endif /* DJGPP */        
370
371     *connpp = NULL;
372
373 #ifndef DJGPP
374         timeUsed = (GetCurrentTime() - reqp->startTime) / 1000;
375 #else
376     gettimeofday(&now, NULL);
377     timeUsed = sub_time(now, reqp->startTime) / 1000;
378 #endif
379         
380         /* leave 5 seconds margin of safety */
381         timeLeft =  ConnDeadtimeout - timeUsed - 5;
382         hardTimeLeft = HardDeadtimeout - timeUsed - 5;
383
384         lock_ObtainWrite(&cm_serverLock);
385     for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
386         tsp = tsrp->server;
387         tsp->refCount++;
388         lock_ReleaseWrite(&cm_serverLock);
389         if (!(tsp->flags & CM_SERVERFLAG_DOWN)) {
390             allDown = 0;
391             if (tsrp->status == busy)
392                 someBusy = 1;
393             else if (tsrp->status == offline)
394                 someOffline = 1;
395             else {
396                                 allBusy = 0;
397                 code = cm_ConnByServer(tsp, usersp, connpp);
398                 if (code == 0) {
399                     cm_PutServer(tsp);
400                     /* Set RPC timeout */
401                     if (timeLeft > ConnDeadtimeout)
402                         timeLeft = ConnDeadtimeout;
403
404                     if (hardTimeLeft > HardDeadtimeout) 
405                         hardTimeLeft = HardDeadtimeout;
406
407                     lock_ObtainMutex(&(*connpp)->mx);
408                     rx_SetConnDeadTime((*connpp)->callp,
409                                         timeLeft);
410                     rx_SetConnHardDeadTime((*connpp)->callp, 
411                                             (u_short) hardTimeLeft);
412                     lock_ReleaseMutex(&(*connpp)->mx);
413
414                     return 0;
415                 }
416                 if (firstError == 0) 
417                     firstError = code;
418             }
419                 } 
420         lock_ObtainWrite(&cm_serverLock);
421         osi_assert(tsp->refCount-- > 0);
422     }   
423
424         lock_ReleaseWrite(&cm_serverLock);
425         if (firstError == 0) {
426         if (serversp == NULL)
427                         firstError = CM_ERROR_NOSUCHVOLUME;
428         else if (allDown) 
429                         firstError = CM_ERROR_ALLOFFLINE;
430                 else if (allBusy) 
431                         firstError = CM_ERROR_ALLBUSY;
432                 else
433                         firstError = CM_ERROR_TIMEDOUT;
434         }
435         osi_Log1(afsd_logp, "cm_ConnByMServers returning %x", firstError);
436     return firstError;
437 }
438
439 /* called with a held server to GC all bad connections hanging off of the server */
440 void cm_GCConnections(cm_server_t *serverp)
441 {
442         cm_conn_t *tcp;
443     cm_conn_t **lcpp;
444     cm_user_t *userp;
445
446         lock_ObtainWrite(&cm_connLock);
447         lcpp = &serverp->connsp;
448         for(tcp = *lcpp; tcp; tcp = *lcpp) {
449                 userp = tcp->userp;
450                 if (userp && tcp->refCount == 0 && (userp->vcRefs == 0)) {
451                         /* do the deletion of this guy */
452             cm_ReleaseUser(userp);
453             *lcpp = tcp->nextp;
454                         rx_DestroyConnection(tcp->callp);
455             lock_FinalizeMutex(&tcp->mx);
456             free(tcp);
457         }
458         else {
459                         /* just advance to the next */
460             lcpp = &tcp->nextp;
461         }
462     }
463         lock_ReleaseWrite(&cm_connLock);
464 }
465
466 static void cm_NewRXConnection(cm_conn_t *tcp, cm_ucell_t *ucellp,
467         cm_server_t *serverp)
468 {
469     unsigned short port;
470     int serviceID;
471     int secIndex;
472     struct rx_securityClass *secObjp;
473         afs_int32 level;
474
475         if (serverp->type == CM_SERVER_VLDB) {
476                 port = htons(7003);
477         serviceID = 52;
478     }
479     else {
480                 osi_assert(serverp->type == CM_SERVER_FILE);
481         port = htons(7000);
482         serviceID = 1;
483     }
484         if (ucellp->flags & CM_UCELLFLAG_RXKAD) {
485                 secIndex = 2;
486                 if (cryptall) {
487                         level = rxkad_crypt;
488                         tcp->cryptlevel = rxkad_crypt;
489                 } else {
490                         level = rxkad_clear;
491                 }
492         secObjp = rxkad_NewClientSecurityObject(level,
493                                                 &ucellp->sessionKey, ucellp->kvno,
494                                                 ucellp->ticketLen, ucellp->ticketp);    
495     }
496     else {
497         /* normal auth */
498         secIndex = 0;
499         secObjp = rxnull_NewClientSecurityObject();
500     }
501         osi_assert(secObjp != NULL);
502     tcp->callp = rx_NewConnection(serverp->addr.sin_addr.s_addr,
503                                   port,
504                                   serviceID,
505                                   secObjp,
506                                   secIndex);
507         rx_SetConnDeadTime(tcp->callp, ConnDeadtimeout);
508         rx_SetConnHardDeadTime(tcp->callp, HardDeadtimeout);
509         tcp->ucgen = ucellp->gen;
510     if (secObjp)
511         rxs_Release(secObjp);   /* Decrement the initial refCount */
512 }
513
514 long cm_ConnByServer(cm_server_t *serverp, cm_user_t *userp, cm_conn_t **connpp)
515 {
516         cm_conn_t *tcp;
517     cm_ucell_t *ucellp;
518
519         lock_ObtainMutex(&userp->mx);
520         lock_ObtainWrite(&cm_connLock);
521         for(tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
522                 if (tcp->userp == userp) break;
523     }
524         /* find ucell structure */
525     ucellp = cm_GetUCell(userp, serverp->cellp);
526         if (!tcp) {
527                 tcp = malloc(sizeof(*tcp));
528         memset(tcp, 0, sizeof(*tcp));
529         tcp->nextp = serverp->connsp;
530         serverp->connsp = tcp;
531         cm_HoldUser(userp);
532         tcp->userp = userp;
533         lock_InitializeMutex(&tcp->mx, "cm_conn_t mutex");
534         tcp->serverp = serverp;
535                 tcp->cryptlevel = rxkad_clear;
536                 cm_NewRXConnection(tcp, ucellp, serverp);
537                 tcp->refCount = 1;
538     }
539         else {
540                 if ((tcp->ucgen < ucellp->gen) || (tcp->cryptlevel != cryptall))
541                 {
542                         rx_DestroyConnection(tcp->callp);
543                         cm_NewRXConnection(tcp, ucellp, serverp);
544                 }
545         tcp->refCount++;
546         }
547         lock_ReleaseWrite(&cm_connLock);
548     lock_ReleaseMutex(&userp->mx);
549
550         /* return this pointer to our caller */
551     osi_Log1(afsd_logp, "cm_ConnByServer returning conn 0x%x", (long) tcp);
552         *connpp = tcp;
553
554     return 0;
555 }
556
557 long cm_Conn(struct cm_fid *fidp, struct cm_user *userp, cm_req_t *reqp,
558         cm_conn_t **connpp)
559 {
560         long code;
561
562         cm_serverRef_t *serversp;
563
564         code = cm_GetServerList(fidp, userp, reqp, &serversp);
565         if (code) {
566                 *connpp = NULL;
567                 return code;
568         }
569
570         code = cm_ConnByMServers(serversp, userp, reqp, connpp);
571     cm_FreeServerList(&serversp);
572     return code;
573 }