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