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