b3e22c0e3cb3256878270ffd7be5adca08b08be6
[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             cm_ForceUpdateVolume(fidp, userp, reqp);
205             retry = 1;
206         }
207
208         /* if all servers are busy, mark them non-busy and start over */
209         if (errorCode == CM_ERROR_ALLBUSY) {
210                 cm_GetServerList(fidp, userp, reqp, &serversp);
211                 for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
212                         if (tsrp->status == busy)
213                                 tsrp->status = not_busy;
214                 }
215                 thrd_Sleep(5000);
216                 retry = 1;
217         }
218
219         /* special codes:  VBUSY and VRESTARTING */
220         if (errorCode == VBUSY || errorCode == VRESTARTING) {
221                 cm_GetServerList(fidp, userp, reqp, &serversp);
222                 for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
223                         if (tsrp->server == serverp
224                             && tsrp->status == not_busy) {
225                                 tsrp->status = busy;
226                                 break;
227                         }
228                 }
229                 retry = 1;
230         }
231
232         /* special codes:  missing volumes */
233         if (errorCode == VNOVOL || errorCode == VMOVED || errorCode == VOFFLINE
234             || errorCode == VSALVAGE || errorCode == VNOSERVICE) {
235                 /* Log server being offline for this volume */
236                 osi_Log4(afsd_logp, "cm_Analyze found server %d.%d.%d.%d marked offline for a volume",
237                          ((serverp->addr.sin_addr.s_addr & 0xff)),
238                          ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
239                          ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
240                          ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
241                 /* Create Event Log message */ 
242                 {
243                     HANDLE h;
244                     char *ptbuf[1];
245                     char s[100];
246                     h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
247                     sprintf(s, "cm_Analyze: Server %d.%d.%d.%d reported volume %d as missing.",
248                             ((serverp->addr.sin_addr.s_addr & 0xff)),
249                             ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
250                             ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
251                             ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24),
252                             fidp->volume);
253                     ptbuf[0] = s;
254                     ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1009, NULL,
255                                 1, 0, ptbuf, NULL);
256                     DeregisterEventSource(h);
257                 }
258
259                 /* Mark server offline for this volume */
260                 cm_GetServerList(fidp, userp, reqp, &serversp);
261
262                 for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
263                         if (tsrp->server == serverp)
264                                 tsrp->status = offline;
265                 }
266                 retry = 1;
267         }
268
269         /* RX codes */
270         if (errorCode == RX_CALL_TIMEOUT) {
271                 /* server took longer than hardDeadTime 
272                  * don't mark server as down but don't retry
273                  * this is to prevent the SMB session from timing out
274                  * In addition, we log an event to the event log 
275                  */
276 #ifndef DJGPP
277                 HANDLE h;
278                 char *ptbuf[1];
279                 char s[100];
280                 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
281                 sprintf(s, "cm_Analyze: HardDeadTime exceeded.");
282                 ptbuf[0] = s;
283                 ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1009, NULL,
284                         1, 0, ptbuf, NULL);
285                 DeregisterEventSource(h);
286 #endif /* !DJGPP */
287           
288                 retry = 0;
289                 osi_Log0(afsd_logp, "cm_Analyze: hardDeadTime exceeded");
290         }
291         else if (errorCode >= -64 && errorCode < 0) {
292                 /* mark server as down */
293                 lock_ObtainMutex(&serverp->mx);
294                 serverp->flags |= CM_SERVERFLAG_DOWN;
295                 lock_ReleaseMutex(&serverp->mx);
296                 retry = 1;
297         }
298
299         if (errorCode == RXKADEXPIRED && !dead_session) {
300                 lock_ObtainMutex(&userp->mx);
301                 ucellp = cm_GetUCell(userp, serverp->cellp);
302                 if (ucellp->ticketp) {
303                         free(ucellp->ticketp);
304                         ucellp->ticketp = NULL;
305                 }
306                 ucellp->flags &= ~CM_UCELLFLAG_RXKAD;
307                 ucellp->gen++;
308                 lock_ReleaseMutex(&userp->mx);
309                 retry = 1;
310         }
311
312         if (retry && dead_session)
313                 retry = 0;
314  
315 out:
316         /* drop this on the way out */
317         if (connp)
318                 cm_PutConn(connp);
319
320         /* retry until we fail to find a connection */
321         return retry;
322 }
323
324 long cm_ConnByMServers(cm_serverRef_t *serversp, cm_user_t *usersp,
325         cm_req_t *reqp, cm_conn_t **connpp)
326 {
327         long code;
328         cm_serverRef_t *tsrp;
329         cm_server_t *tsp;
330         long firstError = 0;
331         int someBusy = 0, someOffline = 0, allDown = 1;
332         long timeUsed, timeLeft, hardTimeLeft;
333 #ifdef DJGPP
334         struct timeval now;
335 #endif /* DJGPP */        
336
337         *connpp = NULL;
338
339 #ifndef DJGPP
340         timeUsed = (GetCurrentTime() - reqp->startTime) / 1000;
341 #else
342         gettimeofday(&now, NULL);
343         timeUsed = sub_time(now, reqp->startTime) / 1000;
344 #endif
345         
346         /* leave 5 seconds margin of safety */
347         timeLeft =  ConnDeadtimeout - timeUsed - 5;
348         hardTimeLeft = HardDeadtimeout - timeUsed - 5;
349
350         lock_ObtainWrite(&cm_serverLock);
351
352     for(tsrp = serversp; tsrp; tsrp=tsrp->next) {
353         tsp = tsrp->server;
354         tsp->refCount++;
355         lock_ReleaseWrite(&cm_serverLock);
356         if (!(tsp->flags & CM_SERVERFLAG_DOWN)) {
357             allDown = 0;
358             if (tsrp->status == busy)
359                 someBusy = 1;
360             else if (tsrp->status == offline)
361                 someOffline = 1;
362             else {
363                 code = cm_ConnByServer(tsp, usersp, connpp);
364                 if (code == 0) {
365                     cm_PutServer(tsp);
366                     /* Set RPC timeout */
367                     if (timeLeft > ConnDeadtimeout)
368                         timeLeft = ConnDeadtimeout;
369
370                     if (hardTimeLeft > HardDeadtimeout) 
371                         hardTimeLeft = HardDeadtimeout;
372
373                     lock_ObtainMutex(&(*connpp)->mx);
374                     rx_SetConnDeadTime((*connpp)->callp,
375                                         timeLeft);
376                     rx_SetConnHardDeadTime((*connpp)->callp, 
377                                             (u_short) hardTimeLeft);
378                     lock_ReleaseMutex(&(*connpp)->mx);
379
380                     return 0;
381                 }
382                 if (firstError == 0) 
383                     firstError = code;
384             }
385                 } 
386         lock_ObtainWrite(&cm_serverLock);
387         osi_assert(tsp->refCount-- > 0);
388     }   
389
390         lock_ReleaseWrite(&cm_serverLock);
391         if (firstError == 0) {
392                 if (someBusy) 
393                         firstError = CM_ERROR_ALLBUSY;
394                 else if (someOffline) 
395                         firstError = CM_ERROR_ALLOFFLINE;
396                 else if (!allDown && serversp) 
397                         firstError = CM_ERROR_TIMEDOUT;
398                 /* Only return CM_ERROR_NOSUCHVOLUME if there are no
399                    servers for this volume */
400                 else 
401                         firstError = CM_ERROR_NOSUCHVOLUME;
402         }
403         osi_Log1(afsd_logp, "cm_ConnByMServers returning %x", firstError);
404     return firstError;
405 }
406
407 /* called with a held server to GC all bad connections hanging off of the server */
408 void cm_GCConnections(cm_server_t *serverp)
409 {
410         cm_conn_t *tcp;
411     cm_conn_t **lcpp;
412     cm_user_t *userp;
413
414         lock_ObtainWrite(&cm_connLock);
415         lcpp = &serverp->connsp;
416         for(tcp = *lcpp; tcp; tcp = *lcpp) {
417                 userp = tcp->userp;
418                 if (userp && tcp->refCount == 0 && (userp->vcRefs == 0)) {
419                         /* do the deletion of this guy */
420             cm_ReleaseUser(userp);
421             *lcpp = tcp->nextp;
422                         rx_DestroyConnection(tcp->callp);
423             lock_FinalizeMutex(&tcp->mx);
424             free(tcp);
425         }
426         else {
427                         /* just advance to the next */
428             lcpp = &tcp->nextp;
429         }
430     }
431         lock_ReleaseWrite(&cm_connLock);
432 }
433
434 static void cm_NewRXConnection(cm_conn_t *tcp, cm_ucell_t *ucellp,
435         cm_server_t *serverp)
436 {
437     unsigned short port;
438     int serviceID;
439     int secIndex;
440     struct rx_securityClass *secObjp;
441         afs_int32 level;
442
443         if (serverp->type == CM_SERVER_VLDB) {
444                 port = htons(7003);
445         serviceID = 52;
446     }
447     else {
448                 osi_assert(serverp->type == CM_SERVER_FILE);
449         port = htons(7000);
450         serviceID = 1;
451     }
452         if (ucellp->flags & CM_UCELLFLAG_RXKAD) {
453                 secIndex = 2;
454                 if (cryptall) {
455                         level = rxkad_crypt;
456                         tcp->cryptlevel = rxkad_crypt;
457                 } else {
458                         level = rxkad_clear;
459                 }
460         secObjp = rxkad_NewClientSecurityObject(level,
461                                                 &ucellp->sessionKey, ucellp->kvno,
462                                                 ucellp->ticketLen, ucellp->ticketp);    
463     }
464     else {
465         /* normal auth */
466         secIndex = 0;
467         secObjp = rxnull_NewClientSecurityObject();
468     }
469         osi_assert(secObjp != NULL);
470     tcp->callp = rx_NewConnection(serverp->addr.sin_addr.s_addr,
471                                   port,
472                                   serviceID,
473                                   secObjp,
474                                   secIndex);
475         rx_SetConnDeadTime(tcp->callp, ConnDeadtimeout);
476         rx_SetConnHardDeadTime(tcp->callp, HardDeadtimeout);
477         tcp->ucgen = ucellp->gen;
478     if (secObjp)
479         rxs_Release(secObjp);   /* Decrement the initial refCount */
480 }
481
482 long cm_ConnByServer(cm_server_t *serverp, cm_user_t *userp, cm_conn_t **connpp)
483 {
484         cm_conn_t *tcp;
485     cm_ucell_t *ucellp;
486
487         lock_ObtainMutex(&userp->mx);
488         lock_ObtainWrite(&cm_connLock);
489         for(tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
490                 if (tcp->userp == userp) break;
491     }
492         /* find ucell structure */
493     ucellp = cm_GetUCell(userp, serverp->cellp);
494         if (!tcp) {
495                 tcp = malloc(sizeof(*tcp));
496         memset(tcp, 0, sizeof(*tcp));
497         tcp->nextp = serverp->connsp;
498         serverp->connsp = tcp;
499         cm_HoldUser(userp);
500         tcp->userp = userp;
501         lock_InitializeMutex(&tcp->mx, "cm_conn_t mutex");
502         tcp->serverp = serverp;
503                 tcp->cryptlevel = rxkad_clear;
504                 cm_NewRXConnection(tcp, ucellp, serverp);
505                 tcp->refCount = 1;
506     }
507         else {
508                 if ((tcp->ucgen < ucellp->gen) || (tcp->cryptlevel != cryptall))
509                 {
510                         rx_DestroyConnection(tcp->callp);
511                         cm_NewRXConnection(tcp, ucellp, serverp);
512                 }
513         tcp->refCount++;
514         }
515         lock_ReleaseWrite(&cm_connLock);
516     lock_ReleaseMutex(&userp->mx);
517
518         /* return this pointer to our caller */
519     osi_Log1(afsd_logp, "cm_ConnByServer returning conn 0x%x", (long) tcp);
520         *connpp = tcp;
521
522     return 0;
523 }
524
525 long cm_Conn(struct cm_fid *fidp, struct cm_user *userp, cm_req_t *reqp,
526         cm_conn_t **connpp)
527 {
528         long code;
529
530         cm_serverRef_t *serversp;
531
532         code = cm_GetServerList(fidp, userp, reqp, &serversp);
533         if (code) {
534                 *connpp = NULL;
535                 return code;
536         }
537
538         code = cm_ConnByMServers(serversp, userp, reqp, connpp);
539         return code;
540 }