windows-afsd-nat-handling-20070310
[openafs.git] / src / WINNT / afsd / cm_daemon.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 #include <windows.h>
14 #include <winsock2.h>
15 #include <iphlpapi.h>
16 #include <stdlib.h>
17 #include <malloc.h>
18 #include <string.h>
19
20 #include "afsd.h"
21
22 #include <rx/rx.h>
23 #include <rx/rx_prototypes.h>
24 #include <WINNT/afsreg.h>
25
26 #include "afsicf.h"
27
28 /* in seconds */
29 long cm_daemonCheckDownInterval  = 180;
30 long cm_daemonCheckUpInterval    = 240;
31 long cm_daemonCheckVolInterval   = 3600;
32 long cm_daemonCheckCBInterval    = 60;
33 long cm_daemonCheckLockInterval  = 60;
34 long cm_daemonTokenCheckInterval = 180;
35
36 osi_rwlock_t cm_daemonLock;
37
38 long cm_bkgQueueCount;          /* # of queued requests */
39
40 int cm_bkgWaitingForCount;      /* true if someone's waiting for cm_bkgQueueCount to drop */
41
42 cm_bkgRequest_t *cm_bkgListp;           /* first elt in the list of requests */
43 cm_bkgRequest_t *cm_bkgListEndp;        /* last elt in the list of requests */
44
45 static int daemon_ShutdownFlag = 0;
46
47 void cm_IpAddrDaemon(long parm)
48 {
49     extern void smb_CheckVCs(void);
50
51     rx_StartClientThread();
52
53     while (daemon_ShutdownFlag == 0) {
54         DWORD Result = NotifyAddrChange(NULL,NULL);
55         if (Result == NO_ERROR && daemon_ShutdownFlag == 0) {
56             osi_Log0(afsd_logp, "cm_IpAddrDaemon CheckDownServers");
57             Sleep(2500);
58             cm_ForceNewConnectionsAllServers();
59             cm_CheckServers(CM_FLAG_CHECKUPSERVERS | CM_FLAG_CHECKDOWNSERVERS, NULL);
60             smb_CheckVCs();
61         }       
62     }
63 }
64
65 void cm_BkgDaemon(long parm)
66 {
67     cm_bkgRequest_t *rp;
68     afs_int32 code;
69
70     rx_StartClientThread();
71
72     lock_ObtainWrite(&cm_daemonLock);
73     while (daemon_ShutdownFlag == 0) {
74         if (!cm_bkgListEndp) {
75             osi_SleepW((LONG_PTR)&cm_bkgListp, &cm_daemonLock);
76             lock_ObtainWrite(&cm_daemonLock);
77             continue;
78         }
79                 
80         /* we found a request */
81         for (rp = cm_bkgListEndp; rp; rp = (cm_bkgRequest_t *) osi_QPrev(&rp->q))
82         {
83             if (cm_ServerAvailable(&rp->scp->fid, rp->userp))
84                 break;
85         }
86         if (rp == NULL) {
87             /* we couldn't find a request that we could process at the current time */
88             lock_ReleaseWrite(&cm_daemonLock);
89             Sleep(1000);
90             lock_ObtainWrite(&cm_daemonLock);
91             continue;
92         }
93
94         osi_QRemoveHT((osi_queue_t **) &cm_bkgListp, (osi_queue_t **) &cm_bkgListEndp, &rp->q);
95         osi_assert(cm_bkgQueueCount-- > 0);
96         lock_ReleaseWrite(&cm_daemonLock);
97
98         osi_Log1(afsd_logp,"cm_BkgDaemon processing request 0x%p", rp);
99
100 #ifdef DEBUG_REFCOUNT
101         osi_Log2(afsd_logp,"cm_BkgDaemon (before) scp 0x%x ref %d",rp->scp, rp->scp->refCount);
102 #endif
103         code = (*rp->procp)(rp->scp, rp->p1, rp->p2, rp->p3, rp->p4, rp->userp);
104 #ifdef DEBUG_REFCOUNT                
105         osi_Log2(afsd_logp,"cm_BkgDaemon (after) scp 0x%x ref %d",rp->scp, rp->scp->refCount);
106 #endif
107         if (code == 0) {
108             cm_ReleaseUser(rp->userp);
109             cm_ReleaseSCache(rp->scp);
110             free(rp);
111         }
112
113         lock_ObtainWrite(&cm_daemonLock);
114
115         switch ( code ) {
116         case 0: /* success */
117             osi_Log1(afsd_logp,"cm_BkgDaemon SUCCESS: request 0x%p", rp);
118             break;
119         case CM_ERROR_TIMEDOUT: /* or server restarting */
120         case CM_ERROR_RETRY:
121         case CM_ERROR_WOULDBLOCK:
122         case CM_ERROR_ALLBUSY:
123         case CM_ERROR_ALLDOWN:
124         case CM_ERROR_ALLOFFLINE:
125         case CM_ERROR_PARTIALWRITE:
126             osi_Log2(afsd_logp,"cm_BkgDaemon re-queueing failed request 0x%p code 0x%x",
127                      rp, code);
128             cm_bkgQueueCount++;
129             osi_QAddT((osi_queue_t **) &cm_bkgListp, (osi_queue_t **)&cm_bkgListEndp, &rp->q);
130             break;
131         default:
132             osi_Log2(afsd_logp,"cm_BkgDaemon FAILED: request dropped 0x%p code 0x%x",
133                      rp, code);
134         }
135     }
136     lock_ReleaseWrite(&cm_daemonLock);
137 }
138
139 void cm_QueueBKGRequest(cm_scache_t *scp, cm_bkgProc_t *procp, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4,
140         cm_user_t *userp)
141 {
142     cm_bkgRequest_t *rp;
143         
144     rp = malloc(sizeof(*rp));
145     memset(rp, 0, sizeof(*rp));
146         
147     cm_HoldSCache(scp);
148     rp->scp = scp;
149     cm_HoldUser(userp);
150     rp->userp = userp;
151     rp->procp = procp;
152     rp->p1 = p1;
153     rp->p2 = p2;
154     rp->p3 = p3;
155     rp->p4 = p4;
156
157     lock_ObtainWrite(&cm_daemonLock);
158     cm_bkgQueueCount++;
159     osi_QAdd((osi_queue_t **) &cm_bkgListp, &rp->q);
160     if (!cm_bkgListEndp) 
161         cm_bkgListEndp = rp;
162     lock_ReleaseWrite(&cm_daemonLock);
163
164     osi_Wakeup((LONG_PTR) &cm_bkgListp);
165 }
166
167 static int
168 IsWindowsFirewallPresent(void)
169 {
170     SC_HANDLE scm;
171     SC_HANDLE svc;
172     BOOLEAN flag;
173     BOOLEAN result = FALSE;
174     LPQUERY_SERVICE_CONFIG pConfig = NULL;
175     DWORD BufSize;
176     LONG status;
177
178     /* Open services manager */
179     scm = OpenSCManager(NULL, NULL, GENERIC_READ);
180     if (!scm) return FALSE;
181
182     /* Open Windows Firewall service */
183     svc = OpenService(scm, "MpsSvc", SERVICE_QUERY_CONFIG);
184     if (!svc) {
185         afsi_log("MpsSvc Service could not be opened for query: 0x%x", GetLastError());
186         svc = OpenService(scm, "SharedAccess", SERVICE_QUERY_CONFIG);
187         if (!svc)
188             afsi_log("SharedAccess Service could not be opened for query: 0x%x", GetLastError());
189     }
190     if (!svc)
191         goto close_scm;
192
193     /* Query Windows Firewall service config, first just to get buffer size */
194     /* Expected to fail, so don't test return value */
195     (void) QueryServiceConfig(svc, NULL, 0, &BufSize);
196     status = GetLastError();
197     if (status != ERROR_INSUFFICIENT_BUFFER)
198         goto close_svc;
199
200     /* Allocate buffer */
201     pConfig = (LPQUERY_SERVICE_CONFIG)GlobalAlloc(GMEM_FIXED,BufSize);
202     if (!pConfig)
203         goto close_svc;
204
205     /* Query Windows Firewall service config, this time for real */
206     flag = QueryServiceConfig(svc, pConfig, BufSize, &BufSize);
207     if (!flag) {
208         afsi_log("QueryServiceConfig failed: 0x%x", GetLastError());
209         goto free_pConfig;
210     }
211
212     /* Is it autostart? */
213     afsi_log("AutoStart 0x%x", pConfig->dwStartType);
214     if (pConfig->dwStartType < SERVICE_DEMAND_START)
215         result = TRUE;
216
217   free_pConfig:
218     GlobalFree(pConfig);
219   close_svc:
220     CloseServiceHandle(svc);
221   close_scm:
222     CloseServiceHandle(scm);
223
224     return result;
225 }
226
227 void
228 cm_DaemonCheckInit(void)
229 {
230     HKEY parmKey;
231     DWORD dummyLen;
232     DWORD dummy;
233     DWORD code;
234
235     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
236                          0, KEY_QUERY_VALUE, &parmKey);
237     if (code)
238         return;
239
240     dummyLen = sizeof(DWORD);
241     code = RegQueryValueEx(parmKey, "DownServerCheckInterval", NULL, NULL,
242                             (BYTE *) &dummy, &dummyLen);
243     if (code == ERROR_SUCCESS)
244         cm_daemonCheckDownInterval = dummy;
245     
246     dummyLen = sizeof(DWORD);
247     code = RegQueryValueEx(parmKey, "UpServerCheckInterval", NULL, NULL,
248                             (BYTE *) &dummy, &dummyLen);
249     if (code == ERROR_SUCCESS)
250         cm_daemonCheckUpInterval = dummy;
251     
252     dummyLen = sizeof(DWORD);
253     code = RegQueryValueEx(parmKey, "VolumeCheckInterval", NULL, NULL,
254                             (BYTE *) &dummy, &dummyLen);
255     if (code == ERROR_SUCCESS)
256         cm_daemonCheckVolInterval = dummy;
257     
258     dummyLen = sizeof(DWORD);
259     code = RegQueryValueEx(parmKey, "CallbackCheckInterval", NULL, NULL,
260                             (BYTE *) &dummy, &dummyLen);
261     if (code == ERROR_SUCCESS)
262         cm_daemonCheckCBInterval = dummy;
263     
264     dummyLen = sizeof(DWORD);
265     code = RegQueryValueEx(parmKey, "LockCheckInterval", NULL, NULL,
266                             (BYTE *) &dummy, &dummyLen);
267     if (code == ERROR_SUCCESS)
268         cm_daemonCheckLockInterval = dummy;
269     
270     dummyLen = sizeof(DWORD);
271     code = RegQueryValueEx(parmKey, "TokenCheckInterval", NULL, NULL,
272                             (BYTE *) &dummy, &dummyLen);
273     if (code == ERROR_SUCCESS)
274         cm_daemonTokenCheckInterval = dummy;
275     
276     RegCloseKey(parmKey);
277 }
278
279 /* periodic check daemon */
280 void cm_Daemon(long parm)
281 {
282     time_t now;
283     time_t lastLockCheck;
284     time_t lastVolCheck;
285     time_t lastCBExpirationCheck;
286     time_t lastDownServerCheck;
287     time_t lastUpServerCheck;
288     time_t lastTokenCacheCheck;
289     char thostName[200];
290     unsigned long code;
291     struct hostent *thp;
292     HMODULE hHookDll;
293     int configureFirewall = IsWindowsFirewallPresent();
294
295     if (!configureFirewall) {
296         afsi_log("No Windows Firewall detected");
297     }
298
299     /* ping all file servers, up or down, with unauthenticated connection,
300      * to find out whether we have all our callbacks from the server still.
301      * Also, ping down VLDBs.
302      */
303     /*
304      * Seed the random number generator with our own address, so that
305      * clients starting at the same time don't all do vol checks at the
306      * same time.
307      */
308     gethostname(thostName, sizeof(thostName));
309     thp = gethostbyname(thostName);
310     if (thp == NULL)    /* In djgpp, gethostname returns the netbios
311                            name of the machine.  gethostbyname will fail
312                            looking this up if it differs from DNS name. */
313         code = 0;
314     else
315         memcpy(&code, thp->h_addr_list[0], 4);
316     
317     srand(ntohl(code));
318
319     cm_DaemonCheckInit();
320
321     now = osi_Time();
322     lastVolCheck = now - cm_daemonCheckVolInterval/2 + (rand() % cm_daemonCheckVolInterval);
323     lastCBExpirationCheck = now - cm_daemonCheckCBInterval/2 + (rand() % cm_daemonCheckCBInterval);
324     lastLockCheck = now - cm_daemonCheckLockInterval/2 + (rand() % cm_daemonCheckLockInterval);
325     lastDownServerCheck = now - cm_daemonCheckDownInterval/2 + (rand() % cm_daemonCheckDownInterval);
326     lastUpServerCheck = now - cm_daemonCheckUpInterval/2 + (rand() % cm_daemonCheckUpInterval);
327     lastTokenCacheCheck = now - cm_daemonTokenCheckInterval/2 + (rand() % cm_daemonTokenCheckInterval);
328
329     while (daemon_ShutdownFlag == 0) {
330         /* check to see if the listener threads halted due to network 
331          * disconnect or other issues.  If so, attempt to restart them.
332          */
333         smb_RestartListeners();
334
335         if (configureFirewall) {
336             /* Open Microsoft Firewall to allow in port 7001 */
337             switch (icf_CheckAndAddAFSPorts(AFS_PORTSET_CLIENT)) {
338             case 0:
339                 afsi_log("Windows Firewall Configuration succeeded");
340                 configureFirewall = 0;
341                 break;
342             case 1:
343                 afsi_log("Invalid Windows Firewall Port Set");
344                 break;
345             case 2:
346                 afsi_log("Unable to open Windows Firewall Profile");
347                 break;
348             case 3:
349                 afsi_log("Unable to create/modify Windows Firewall Port entries");
350                 break;
351             default:
352                 afsi_log("Unknown Windows Firewall Configuration error");
353             }
354         } 
355
356         /* find out what time it is */
357         now = osi_Time();
358
359         /* check down servers */
360         if (now > lastDownServerCheck + cm_daemonCheckDownInterval) {
361             lastDownServerCheck = now;
362             osi_Log0(afsd_logp, "cm_Daemon CheckDownServers");
363             cm_CheckServers(CM_FLAG_CHECKDOWNSERVERS, NULL);
364             now = osi_Time();
365         }
366
367         /* check up servers */
368         if (now > lastUpServerCheck + cm_daemonCheckUpInterval) {
369             lastUpServerCheck = now;
370             osi_Log0(afsd_logp, "cm_Daemon CheckUpServers");
371             cm_CheckServers(CM_FLAG_CHECKUPSERVERS, NULL);
372             now = osi_Time();
373         }
374
375         if (now > lastVolCheck + cm_daemonCheckVolInterval) {
376             lastVolCheck = now;
377             cm_RefreshVolumes();
378             now = osi_Time();
379         }
380
381         if (now > lastCBExpirationCheck + cm_daemonCheckCBInterval) {
382             lastCBExpirationCheck = now;
383             cm_CheckCBExpiration();
384             now = osi_Time();
385         }
386
387         if (now > lastLockCheck + cm_daemonCheckLockInterval) {
388             lastLockCheck = now;
389             cm_CheckLocks();
390             now = osi_Time();
391         }
392
393         if (now > lastTokenCacheCheck + cm_daemonTokenCheckInterval) {
394             lastTokenCacheCheck = now;
395             cm_CheckTokenCache(now);
396             now = osi_Time();
397         }
398
399         /* allow an exit to be called prior to stopping the service */
400         hHookDll = LoadLibrary(AFSD_HOOK_DLL);
401         if (hHookDll)
402         {
403             BOOL hookRc = TRUE;
404             AfsdDaemonHook daemonHook = ( AfsdDaemonHook ) GetProcAddress(hHookDll, AFSD_DAEMON_HOOK);
405             if (daemonHook)
406             {
407                 hookRc = daemonHook();
408             }
409             FreeLibrary(hHookDll);
410             hHookDll = NULL;
411
412             if (hookRc == FALSE)
413             {
414                 SetEvent(WaitToTerminate);
415             }
416         }
417
418         thrd_Sleep(30 * 1000);          /* sleep 30 seconds */
419         if (daemon_ShutdownFlag == 1)
420             return;
421     }
422 }       
423
424 void cm_DaemonShutdown(void)
425 {
426     daemon_ShutdownFlag = 1;
427 }
428
429 void cm_InitDaemon(int nDaemons)
430 {
431     static osi_once_t once;
432     long pid;
433     thread_t phandle;
434     int i;
435         
436     if (osi_Once(&once)) {
437         lock_InitializeRWLock(&cm_daemonLock, "cm_daemonLock");
438         osi_EndOnce(&once);
439
440         /* creating IP Address Change monitor daemon */
441         phandle = thrd_Create((SecurityAttrib) 0, 0,
442                                (ThreadFunc) cm_IpAddrDaemon, 0, 0, &pid, "cm_IpAddrDaemon");
443         osi_assert(phandle != NULL);
444         thrd_CloseHandle(phandle);
445
446         /* creating pinging daemon */
447         phandle = thrd_Create((SecurityAttrib) 0, 0,
448                                (ThreadFunc) cm_Daemon, 0, 0, &pid, "cm_Daemon");
449         osi_assert(phandle != NULL);
450         thrd_CloseHandle(phandle);
451
452         for(i=0; i < nDaemons; i++) {
453             phandle = thrd_Create((SecurityAttrib) 0, 0,
454                                    (ThreadFunc) cm_BkgDaemon, 0, 0, &pid,
455                                    "cm_BkgDaemon");
456             osi_assert(phandle != NULL);
457             thrd_CloseHandle(phandle);
458         }
459     }
460 }