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