windows-volstate-update-post-network-change-20070614
[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_daemonCheckBusyVolInterval = 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, "DownServerCheckInterval", NULL, NULL,
244                             (BYTE *) &dummy, &dummyLen);
245     if (code == ERROR_SUCCESS)
246         cm_daemonCheckDownInterval = dummy;
247     
248     dummyLen = sizeof(DWORD);
249     code = RegQueryValueEx(parmKey, "UpServerCheckInterval", NULL, NULL,
250                             (BYTE *) &dummy, &dummyLen);
251     if (code == ERROR_SUCCESS)
252         cm_daemonCheckUpInterval = dummy;
253     
254     dummyLen = sizeof(DWORD);
255     code = RegQueryValueEx(parmKey, "VolumeCheckInterval", NULL, NULL,
256                             (BYTE *) &dummy, &dummyLen);
257     if (code == ERROR_SUCCESS)
258         cm_daemonCheckVolInterval = dummy;
259     
260     dummyLen = sizeof(DWORD);
261     code = RegQueryValueEx(parmKey, "CallbackCheckInterval", NULL, NULL,
262                             (BYTE *) &dummy, &dummyLen);
263     if (code == ERROR_SUCCESS)
264         cm_daemonCheckCBInterval = dummy;
265     
266     dummyLen = sizeof(DWORD);
267     code = RegQueryValueEx(parmKey, "LockCheckInterval", NULL, NULL,
268                             (BYTE *) &dummy, &dummyLen);
269     if (code == ERROR_SUCCESS)
270         cm_daemonCheckLockInterval = dummy;
271     
272     dummyLen = sizeof(DWORD);
273     code = RegQueryValueEx(parmKey, "TokenCheckInterval", NULL, NULL,
274                             (BYTE *) &dummy, &dummyLen);
275     if (code == ERROR_SUCCESS)
276         cm_daemonTokenCheckInterval = dummy;
277     
278     dummyLen = sizeof(DWORD);
279     code = RegQueryValueEx(parmKey, "BusyVolumeCheckInterval", NULL, NULL,
280                             (BYTE *) &dummy, &dummyLen);
281     if (code == ERROR_SUCCESS)
282         cm_daemonCheckBusyVolInterval = dummy;
283     
284     RegCloseKey(parmKey);
285 }
286
287 /* periodic check daemon */
288 void cm_Daemon(long parm)
289 {
290     time_t now;
291     time_t lastLockCheck;
292     time_t lastVolCheck;
293     time_t lastCBExpirationCheck;
294     time_t lastDownServerCheck;
295     time_t lastUpServerCheck;
296     time_t lastTokenCacheCheck;
297     time_t lastBusyVolCheck;
298     char thostName[200];
299     unsigned long code;
300     struct hostent *thp;
301     HMODULE hHookDll;
302     int configureFirewall = IsWindowsFirewallPresent();
303
304     if (!configureFirewall) {
305         afsi_log("No Windows Firewall detected");
306     }
307
308     /* ping all file servers, up or down, with unauthenticated connection,
309      * to find out whether we have all our callbacks from the server still.
310      * Also, ping down VLDBs.
311      */
312     /*
313      * Seed the random number generator with our own address, so that
314      * clients starting at the same time don't all do vol checks at the
315      * same time.
316      */
317     gethostname(thostName, sizeof(thostName));
318     thp = gethostbyname(thostName);
319     if (thp == NULL)    /* In djgpp, gethostname returns the netbios
320                            name of the machine.  gethostbyname will fail
321                            looking this up if it differs from DNS name. */
322         code = 0;
323     else
324         memcpy(&code, thp->h_addr_list[0], 4);
325     
326     srand(ntohl(code));
327
328     cm_DaemonCheckInit();
329
330     now = osi_Time();
331     lastVolCheck = now - cm_daemonCheckVolInterval/2 + (rand() % cm_daemonCheckVolInterval);
332     lastCBExpirationCheck = now - cm_daemonCheckCBInterval/2 + (rand() % cm_daemonCheckCBInterval);
333     lastLockCheck = now - cm_daemonCheckLockInterval/2 + (rand() % cm_daemonCheckLockInterval);
334     lastDownServerCheck = now - cm_daemonCheckDownInterval/2 + (rand() % cm_daemonCheckDownInterval);
335     lastUpServerCheck = now - cm_daemonCheckUpInterval/2 + (rand() % cm_daemonCheckUpInterval);
336     lastTokenCacheCheck = now - cm_daemonTokenCheckInterval/2 + (rand() % cm_daemonTokenCheckInterval);
337     lastBusyVolCheck = now - cm_daemonCheckBusyVolInterval/2 * (rand() % cm_daemonCheckBusyVolInterval);
338
339     while (daemon_ShutdownFlag == 0) {
340         /* check to see if the listener threads halted due to network 
341          * disconnect or other issues.  If so, attempt to restart them.
342          */
343         smb_RestartListeners();
344
345         if (configureFirewall) {
346             /* Open Microsoft Firewall to allow in port 7001 */
347             switch (icf_CheckAndAddAFSPorts(AFS_PORTSET_CLIENT)) {
348             case 0:
349                 afsi_log("Windows Firewall Configuration succeeded");
350                 configureFirewall = 0;
351                 break;
352             case 1:
353                 afsi_log("Invalid Windows Firewall Port Set");
354                 break;
355             case 2:
356                 afsi_log("Unable to open Windows Firewall Profile");
357                 break;
358             case 3:
359                 afsi_log("Unable to create/modify Windows Firewall Port entries");
360                 break;
361             default:
362                 afsi_log("Unknown Windows Firewall Configuration error");
363             }
364         } 
365
366         /* find out what time it is */
367         now = osi_Time();
368
369         /* check down servers */
370         if (now > lastDownServerCheck + cm_daemonCheckDownInterval) {
371             lastDownServerCheck = now;
372             osi_Log0(afsd_logp, "cm_Daemon CheckDownServers");
373             cm_CheckServers(CM_FLAG_CHECKDOWNSERVERS, NULL);
374             now = osi_Time();
375         }
376
377         /* check up servers */
378         if (now > lastUpServerCheck + cm_daemonCheckUpInterval) {
379             lastUpServerCheck = now;
380             osi_Log0(afsd_logp, "cm_Daemon CheckUpServers");
381             cm_CheckServers(CM_FLAG_CHECKUPSERVERS, NULL);
382             now = osi_Time();
383         }
384
385         if (now > lastVolCheck + cm_daemonCheckVolInterval) {
386             lastVolCheck = now;
387             cm_RefreshVolumes();
388             now = osi_Time();
389         }
390
391         if (now > lastBusyVolCheck + cm_daemonCheckBusyVolInterval) {
392             lastVolCheck = now;
393             cm_CheckOfflineVolumes();
394             now = osi_Time();
395         }
396
397         if (now > lastCBExpirationCheck + cm_daemonCheckCBInterval) {
398             lastCBExpirationCheck = now;
399             cm_CheckCBExpiration();
400             now = osi_Time();
401         }
402
403         if (now > lastLockCheck + cm_daemonCheckLockInterval) {
404             lastLockCheck = now;
405             cm_CheckLocks();
406             now = osi_Time();
407         }
408
409         if (now > lastTokenCacheCheck + cm_daemonTokenCheckInterval) {
410             lastTokenCacheCheck = now;
411             cm_CheckTokenCache(now);
412             now = osi_Time();
413         }
414
415         /* allow an exit to be called prior to stopping the service */
416         hHookDll = LoadLibrary(AFSD_HOOK_DLL);
417         if (hHookDll)
418         {
419             BOOL hookRc = TRUE;
420             AfsdDaemonHook daemonHook = ( AfsdDaemonHook ) GetProcAddress(hHookDll, AFSD_DAEMON_HOOK);
421             if (daemonHook)
422             {
423                 hookRc = daemonHook();
424             }
425             FreeLibrary(hHookDll);
426             hHookDll = NULL;
427
428             if (hookRc == FALSE)
429             {
430                 SetEvent(WaitToTerminate);
431             }
432         }
433
434         thrd_Sleep(30 * 1000);          /* sleep 30 seconds */
435         if (daemon_ShutdownFlag == 1)
436             return;
437     }
438 }       
439
440 void cm_DaemonShutdown(void)
441 {
442     daemon_ShutdownFlag = 1;
443 }
444
445 void cm_InitDaemon(int nDaemons)
446 {
447     static osi_once_t once;
448     long pid;
449     thread_t phandle;
450     int i;
451         
452     if (osi_Once(&once)) {
453         lock_InitializeRWLock(&cm_daemonLock, "cm_daemonLock");
454         osi_EndOnce(&once);
455
456         /* creating IP Address Change monitor daemon */
457         phandle = thrd_Create((SecurityAttrib) 0, 0,
458                                (ThreadFunc) cm_IpAddrDaemon, 0, 0, &pid, "cm_IpAddrDaemon");
459         osi_assert(phandle != NULL);
460         thrd_CloseHandle(phandle);
461
462         /* creating pinging daemon */
463         phandle = thrd_Create((SecurityAttrib) 0, 0,
464                                (ThreadFunc) cm_Daemon, 0, 0, &pid, "cm_Daemon");
465         osi_assert(phandle != NULL);
466         thrd_CloseHandle(phandle);
467
468         for(i=0; i < nDaemons; i++) {
469             phandle = thrd_Create((SecurityAttrib) 0, 0,
470                                    (ThreadFunc) cm_BkgDaemon, 0, 0, &pid,
471                                    "cm_BkgDaemon");
472             osi_assert(phandle != NULL);
473             thrd_CloseHandle(phandle);
474         }
475     }
476 }