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