server-ref-list-20040729
[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_serverRef_t *serversp = NULL;
106     cm_serverRef_t *newServersp = NULL;
107         cm_cell_t *cellp = NULL;
108
109         if (!fidp) {
110                 *serverspp = NULL;
111                 return 0;
112         }
113
114         cellp = cm_FindCellByID(fidp->cell);
115         if (!cellp) return CM_ERROR_NOSUCHCELL;
116
117         code = cm_GetVolumeByID(cellp, fidp->volume, userp, reqp, &volp);
118         if (code) return code;
119         
120     lock_ObtainMutex(&volp->mx);
121         if (fidp->volume == volp->rwID)
122                 serversp = volp->rwServersp;
123         else if (fidp->volume == volp->roID)
124                 serversp = volp->roServersp;
125         else if (fidp->volume == volp->bkID)
126                 serversp = volp->bkServersp;
127         else
128                 serversp = NULL;
129
130     /* make a copy of the server list because by the time the 
131     caller tries to use it, it might have been freed.
132     Preserve server order. */
133     if(serversp) {
134         cm_serverRef_t ** nl;
135         cm_serverRef_t * tref;
136
137         nl = &newServersp;
138
139         lock_ObtainWrite(&cm_serverLock);
140         while(serversp) {
141
142             tref = malloc(sizeof(cm_serverRef_t));
143             tref->next = NULL;
144             tref->server = serversp->server;
145             tref->status = serversp->status;
146
147             tref->server->refCount++;
148
149             *nl = tref;
150             nl = &tref->next;
151
152             serversp = serversp->next;
153         }
154         lock_ReleaseWrite(&cm_serverLock);
155     }
156     lock_ReleaseMutex(&volp->mx);
157
158         cm_PutVolume(volp);
159     *serverspp = newServersp;
160         return 0;
161 }
162
163 /*
164  * Analyze the error return from an RPC.  Determine whether or not to retry,
165  * and if we're going to retry, determine whether failover is appropriate,
166  * and whether timed backoff is appropriate.
167  *
168  * If the error code is from cm_Conn() or friends, it will be a CM_ERROR code.
169  * Otherwise it will be an RPC code.  This may be a UNIX code (e.g. EDQUOT), or
170  * it may be an RX code, or it may be a special code (e.g. VNOVOL), or it may
171  * be a security code (e.g. RXKADEXPIRED).
172  *
173  * If the error code is from cm_Conn() or friends, connp will be NULL.
174  *
175  * For VLDB calls, fidp will be NULL.
176  *
177  * volSyncp and/or cbrp may also be NULL.
178  */
179 int
180 cm_Analyze(cm_conn_t *connp, cm_user_t *userp, cm_req_t *reqp,
181         struct cm_fid *fidp,
182         AFSVolSync *volSyncp, cm_callbackRequest_t *cbrp, long errorCode)
183 {
184         cm_server_t *serverp;
185         cm_serverRef_t *serversp, *tsrp;
186         cm_ucell_t *ucellp;
187         int retry = 0;
188         int dead_session;
189         
190         osi_Log2(afsd_logp, "cm_Analyze connp 0x%x, code %d",
191                  (long) connp, errorCode);
192
193         /* no locking required, since connp->serverp never changes after
194          * creation */
195         dead_session = (userp->cellInfop == NULL);
196         if (connp)
197                 serverp = connp->serverp;
198
199         /* Update callback pointer */
200         if (cbrp && errorCode == 0) cbrp->serverp = connp->serverp;
201
202         /* If not allowed to retry, don't */
203         if (reqp->flags & CM_REQ_NORETRY)
204                 goto out;
205
206         /* if timeout - check that it did not exceed the SMB timeout
207            and retry */
208         if (errorCode == CM_ERROR_TIMEDOUT)
209     {
210             long timeUsed, timeLeft;
211             /* timeleft - get if from reqp the same way as cmXonnByMServers does */
212 #ifndef DJGPP
213             timeUsed = (GetCurrentTime() - reqp->startTime) / 1000;
214 #else
215             gettimeofday(&now, NULL);
216             timeUsed = sub_time(now, reqp->startTime) / 1000;
217 #endif
218             
219             /* leave 5 seconds margin for sleep */
220             timeLeft = RDRtimeout - timeUsed;
221             if (timeLeft > 5)
222         {
223             thrd_Sleep(3000);
224             cm_CheckServers(CM_FLAG_CHECKDOWNSERVERS, NULL);
225             retry = 1;
226         } 
227     }
228
229     /* if all servers are offline, mark them non-busy and start over */
230         if (errorCode == CM_ERROR_ALLOFFLINE) {
231             osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_ALLOFFLINE.");
232             thrd_Sleep(5000);
233             /* cm_ForceUpdateVolume marks all servers as non_busy */
234                 /* No it doesn't and it won't do anything if all of the 
235                  * the servers are marked as DOWN.  So clear the DOWN
236                  * flag and reset the busy state as well.
237                  */
238                 cm_GetServerList(fidp, userp, reqp, &serversp);
239         if (serversp) {
240             lock_ObtainWrite(&cm_serverLock);
241             for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
242                 tsrp->server->flags &= ~CM_SERVERFLAG_DOWN;
243                 if (tsrp->status == busy)
244                     tsrp->status = not_busy;
245             }
246             lock_ReleaseWrite(&cm_serverLock);
247
248             retry = 1;
249         }
250         cm_FreeServerList(&serversp);
251
252         if (fidp != NULL)   /* Not a VLDB call */
253             cm_ForceUpdateVolume(fidp, userp, reqp);
254         }
255
256         /* if all servers are busy, mark them non-busy and start over */
257         if (errorCode == CM_ERROR_ALLBUSY) {
258                 cm_GetServerList(fidp, userp, reqp, &serversp);
259                 lock_ObtainWrite(&cm_serverLock);
260                 for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
261                         if (tsrp->status == busy)
262                                 tsrp->status = not_busy;
263                 }
264         lock_ReleaseWrite(&cm_serverLock);
265         cm_FreeServerList(&serversp);
266                 thrd_Sleep(5000);
267                 retry = 1;
268         }
269
270         /* special codes:  VBUSY and VRESTARTING */
271         if (errorCode == VBUSY || errorCode == VRESTARTING) {
272                 cm_GetServerList(fidp, userp, reqp, &serversp);
273                 lock_ObtainWrite(&cm_serverLock);
274                 for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
275                         if (tsrp->server == serverp
276                             && tsrp->status == not_busy) {
277                                 tsrp->status = busy;
278                                 break;
279                         }
280                 }
281         lock_ReleaseWrite(&cm_serverLock);
282         cm_FreeServerList(&serversp);
283                 retry = 1;
284         }
285
286         /* special codes:  missing volumes */
287         if (errorCode == VNOVOL || errorCode == VMOVED || errorCode == VOFFLINE
288             || errorCode == VSALVAGE || errorCode == VNOSERVICE) {
289                 /* Log server being offline for this volume */
290                 osi_Log4(afsd_logp, "cm_Analyze found server %d.%d.%d.%d marked offline for a volume",
291                          ((serverp->addr.sin_addr.s_addr & 0xff)),
292                          ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
293                          ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
294                          ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
295                 /* Create Event Log message */ 
296                 {
297                     HANDLE h;
298                     char *ptbuf[1];
299                     char s[100];
300                     h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
301                     sprintf(s, "cm_Analyze: Server %d.%d.%d.%d reported volume %d as missing.",
302                             ((serverp->addr.sin_addr.s_addr & 0xff)),
303                             ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
304                             ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
305                             ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24),
306                             fidp->volume);
307                     ptbuf[0] = s;
308                     ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1009, NULL,
309                                 1, 0, ptbuf, NULL);
310                     DeregisterEventSource(h);
311                 }
312
313                 /* Mark server offline for this volume */
314                 cm_GetServerList(fidp, userp, reqp, &serversp);
315                 for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
316                         if (tsrp->server == serverp)
317                                 tsrp->status = offline;
318                 }
319         cm_FreeServerList(&serversp);
320                 retry = 1;
321         }
322
323         /* RX codes */
324         if (errorCode == RX_CALL_TIMEOUT) {
325                 /* server took longer than hardDeadTime 
326                  * don't mark server as down but don't retry
327                  * this is to prevent the SMB session from timing out
328                  * In addition, we log an event to the event log 
329                  */
330 #ifndef DJGPP
331                 HANDLE h;
332                 char *ptbuf[1];
333                 char s[100];
334                 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
335                 sprintf(s, "cm_Analyze: HardDeadTime exceeded.");
336                 ptbuf[0] = s;
337                 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1009, NULL,
338                         1, 0, ptbuf, NULL);
339                 DeregisterEventSource(h);
340 #endif /* !DJGPP */
341           
342                 retry = 0;
343                 osi_Log0(afsd_logp, "cm_Analyze: hardDeadTime exceeded");
344         }
345         else if (errorCode >= -64 && errorCode < 0) {
346                 /* mark server as down */
347                 lock_ObtainMutex(&serverp->mx);
348                 serverp->flags |= CM_SERVERFLAG_DOWN;
349                 lock_ReleaseMutex(&serverp->mx);
350                 retry = 1;
351         }
352
353         if (errorCode == RXKADEXPIRED && !dead_session) {
354                 lock_ObtainMutex(&userp->mx);
355                 ucellp = cm_GetUCell(userp, serverp->cellp);
356                 if (ucellp->ticketp) {
357                         free(ucellp->ticketp);
358                         ucellp->ticketp = NULL;
359                 }
360                 ucellp->flags &= ~CM_UCELLFLAG_RXKAD;
361                 ucellp->gen++;
362                 lock_ReleaseMutex(&userp->mx);
363                 retry = 1;
364         }
365
366         if (retry && dead_session)
367                 retry = 0;
368  
369 out:
370         /* drop this on the way out */
371         if (connp)
372                 cm_PutConn(connp);
373
374         /* retry until we fail to find a connection */
375         return retry;
376 }
377
378 long cm_ConnByMServers(cm_serverRef_t *serversp, cm_user_t *usersp,
379         cm_req_t *reqp, cm_conn_t **connpp)
380 {
381         long code;
382         cm_serverRef_t *tsrp;
383         cm_server_t *tsp;
384         long firstError = 0;
385         int someBusy = 0, someOffline = 0, allBusy = 1, allDown = 1;
386         long timeUsed, timeLeft, hardTimeLeft;
387 #ifdef DJGPP
388         struct timeval now;
389 #endif /* DJGPP */        
390
391         *connpp = NULL;
392
393 #ifndef DJGPP
394         timeUsed = (GetCurrentTime() - reqp->startTime) / 1000;
395 #else
396         gettimeofday(&now, NULL);
397         timeUsed = sub_time(now, reqp->startTime) / 1000;
398 #endif
399         
400         /* leave 5 seconds margin of safety */
401         timeLeft =  ConnDeadtimeout - timeUsed - 5;
402         hardTimeLeft = HardDeadtimeout - timeUsed - 5;
403
404         lock_ObtainWrite(&cm_serverLock);
405
406     for(tsrp = serversp; tsrp; tsrp=tsrp->next) {
407         tsp = tsrp->server;
408         tsp->refCount++;
409         lock_ReleaseWrite(&cm_serverLock);
410         if (!(tsp->flags & CM_SERVERFLAG_DOWN)) {
411             allDown = 0;
412             if (tsrp->status == busy)
413                 someBusy = 1;
414             else if (tsrp->status == offline)
415                 someOffline = 1;
416             else {
417                                 allBusy = 0;
418                 code = cm_ConnByServer(tsp, usersp, connpp);
419                 if (code == 0) {
420                     cm_PutServer(tsp);
421                     /* Set RPC timeout */
422                     if (timeLeft > ConnDeadtimeout)
423                         timeLeft = ConnDeadtimeout;
424
425                     if (hardTimeLeft > HardDeadtimeout) 
426                         hardTimeLeft = HardDeadtimeout;
427
428                     lock_ObtainMutex(&(*connpp)->mx);
429                     rx_SetConnDeadTime((*connpp)->callp,
430                                         timeLeft);
431                     rx_SetConnHardDeadTime((*connpp)->callp, 
432                                             (u_short) hardTimeLeft);
433                     lock_ReleaseMutex(&(*connpp)->mx);
434
435                     return 0;
436                 }
437                 if (firstError == 0) 
438                     firstError = code;
439             }
440                 } 
441         lock_ObtainWrite(&cm_serverLock);
442         osi_assert(tsp->refCount-- > 0);
443     }   
444
445         lock_ReleaseWrite(&cm_serverLock);
446         if (firstError == 0) {
447         if (serversp == NULL)
448                         firstError = CM_ERROR_NOSUCHVOLUME;
449         else if (allDown) 
450                         firstError = CM_ERROR_ALLOFFLINE;
451                 else if (allBusy) 
452                         firstError = CM_ERROR_ALLBUSY;
453                 else
454                         firstError = CM_ERROR_TIMEDOUT;
455         }
456         osi_Log1(afsd_logp, "cm_ConnByMServers returning %x", firstError);
457     return firstError;
458 }
459
460 /* called with a held server to GC all bad connections hanging off of the server */
461 void cm_GCConnections(cm_server_t *serverp)
462 {
463         cm_conn_t *tcp;
464     cm_conn_t **lcpp;
465     cm_user_t *userp;
466
467         lock_ObtainWrite(&cm_connLock);
468         lcpp = &serverp->connsp;
469         for(tcp = *lcpp; tcp; tcp = *lcpp) {
470                 userp = tcp->userp;
471                 if (userp && tcp->refCount == 0 && (userp->vcRefs == 0)) {
472                         /* do the deletion of this guy */
473             cm_ReleaseUser(userp);
474             *lcpp = tcp->nextp;
475                         rx_DestroyConnection(tcp->callp);
476             lock_FinalizeMutex(&tcp->mx);
477             free(tcp);
478         }
479         else {
480                         /* just advance to the next */
481             lcpp = &tcp->nextp;
482         }
483     }
484         lock_ReleaseWrite(&cm_connLock);
485 }
486
487 static void cm_NewRXConnection(cm_conn_t *tcp, cm_ucell_t *ucellp,
488         cm_server_t *serverp)
489 {
490     unsigned short port;
491     int serviceID;
492     int secIndex;
493     struct rx_securityClass *secObjp;
494         afs_int32 level;
495
496         if (serverp->type == CM_SERVER_VLDB) {
497                 port = htons(7003);
498         serviceID = 52;
499     }
500     else {
501                 osi_assert(serverp->type == CM_SERVER_FILE);
502         port = htons(7000);
503         serviceID = 1;
504     }
505         if (ucellp->flags & CM_UCELLFLAG_RXKAD) {
506                 secIndex = 2;
507                 if (cryptall) {
508                         level = rxkad_crypt;
509                         tcp->cryptlevel = rxkad_crypt;
510                 } else {
511                         level = rxkad_clear;
512                 }
513         secObjp = rxkad_NewClientSecurityObject(level,
514                                                 &ucellp->sessionKey, ucellp->kvno,
515                                                 ucellp->ticketLen, ucellp->ticketp);    
516     }
517     else {
518         /* normal auth */
519         secIndex = 0;
520         secObjp = rxnull_NewClientSecurityObject();
521     }
522         osi_assert(secObjp != NULL);
523     tcp->callp = rx_NewConnection(serverp->addr.sin_addr.s_addr,
524                                   port,
525                                   serviceID,
526                                   secObjp,
527                                   secIndex);
528         rx_SetConnDeadTime(tcp->callp, ConnDeadtimeout);
529         rx_SetConnHardDeadTime(tcp->callp, HardDeadtimeout);
530         tcp->ucgen = ucellp->gen;
531     if (secObjp)
532         rxs_Release(secObjp);   /* Decrement the initial refCount */
533 }
534
535 long cm_ConnByServer(cm_server_t *serverp, cm_user_t *userp, cm_conn_t **connpp)
536 {
537         cm_conn_t *tcp;
538     cm_ucell_t *ucellp;
539
540         lock_ObtainMutex(&userp->mx);
541         lock_ObtainWrite(&cm_connLock);
542         for(tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
543                 if (tcp->userp == userp) break;
544     }
545         /* find ucell structure */
546     ucellp = cm_GetUCell(userp, serverp->cellp);
547         if (!tcp) {
548                 tcp = malloc(sizeof(*tcp));
549         memset(tcp, 0, sizeof(*tcp));
550         tcp->nextp = serverp->connsp;
551         serverp->connsp = tcp;
552         cm_HoldUser(userp);
553         tcp->userp = userp;
554         lock_InitializeMutex(&tcp->mx, "cm_conn_t mutex");
555         tcp->serverp = serverp;
556                 tcp->cryptlevel = rxkad_clear;
557                 cm_NewRXConnection(tcp, ucellp, serverp);
558                 tcp->refCount = 1;
559     }
560         else {
561                 if ((tcp->ucgen < ucellp->gen) || (tcp->cryptlevel != cryptall))
562                 {
563                         rx_DestroyConnection(tcp->callp);
564                         cm_NewRXConnection(tcp, ucellp, serverp);
565                 }
566         tcp->refCount++;
567         }
568         lock_ReleaseWrite(&cm_connLock);
569     lock_ReleaseMutex(&userp->mx);
570
571         /* return this pointer to our caller */
572     osi_Log1(afsd_logp, "cm_ConnByServer returning conn 0x%x", (long) tcp);
573         *connpp = tcp;
574
575     return 0;
576 }
577
578 long cm_Conn(struct cm_fid *fidp, struct cm_user *userp, cm_req_t *reqp,
579         cm_conn_t **connpp)
580 {
581         long code;
582
583         cm_serverRef_t *serversp;
584
585         code = cm_GetServerList(fidp, userp, reqp, &serversp);
586         if (code) {
587                 *connpp = NULL;
588                 return code;
589         }
590
591         code = cm_ConnByMServers(serversp, userp, reqp, connpp);
592     cm_FreeServerList(&serversp);
593         return code;
594 }