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