i-need-sleep-20040406
[openafs.git] / src / WINNT / afsd / afsd_init.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 #include <afs/afs_args.h>
13
14 #include <windows.h>
15 #include <string.h>
16 #include <nb30.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <winsock2.h>
20
21 #include <osi.h>
22 #include "afsd.h"
23 #include <rx\rx.h>
24 #include <rx\rx_null.h>
25
26 #include <WINNT/syscfg.h>
27
28 #include "smb.h"
29 #include "cm_rpc.h"
30 #include "lanahelper.h"
31
32 extern int RXAFSCB_ExecuteRequest(struct rx_call *z_call);
33 extern int RXSTATS_ExecuteRequest(struct rx_call *z_call);
34
35 extern afs_int32 cryptall;
36
37 char AFSConfigKeyName[] =
38         "SYSTEM\\CurrentControlSet\\Services\\TransarcAFSDaemon\\Parameters";
39
40 osi_log_t *afsd_logp;
41
42 char cm_rootVolumeName[64];
43 DWORD cm_rootVolumeNameLen;
44 cm_volume_t *cm_rootVolumep = NULL;
45 cm_cell_t *cm_rootCellp = NULL;
46 cm_fid_t cm_rootFid;
47 cm_scache_t *cm_rootSCachep;
48 char cm_mountRoot[1024];
49 DWORD cm_mountRootLen;
50 int cm_logChunkSize;
51 int cm_chunkSize;
52 #ifdef AFS_FREELANCE_CLIENT
53 char *cm_FakeRootDir;
54 #endif /* freelance */
55
56 int smb_UseV3;
57
58 int LANadapter;
59
60 int numBkgD;
61 int numSvThreads;
62
63 int traceOnPanic = 0;
64
65 int logReady = 0;
66
67 char cm_HostName[200];
68 long cm_HostAddr;
69
70 char cm_NetbiosName[MAX_NB_NAME_LENGTH];
71
72 char cm_CachePath[200];
73 DWORD cm_CachePathLen;
74
75 BOOL isGateway = FALSE;
76
77 BOOL reportSessionStartups = FALSE;
78
79 cm_initparams_v1 cm_initParams;
80
81 /*
82  * AFSD Initialization Log
83  *
84  * This is distinct from the regular debug logging facility.
85  * Log items go directly to a file, not to an array in memory, so that even
86  * if AFSD crashes, the log can be inspected.
87  */
88
89 HANDLE afsi_file;
90
91 #ifdef AFS_AFSDB_ENV
92 int cm_dnsEnabled = 1;
93 #endif
94
95 char cm_NetBiosName[32];
96
97 void
98 afsi_start()
99 {
100         char wd[100];
101         char t[100], u[100], *p, *path;
102         int zilch;
103         int code;
104
105         afsi_file = INVALID_HANDLE_VALUE;
106     if (getenv("TEMP"))
107     {
108         strcpy(wd, getenv("TEMP"));
109     }
110     else
111     {
112         code = GetWindowsDirectory(wd, sizeof(wd));
113         if (code == 0) return;
114     }
115         strcat(wd, "\\afsd_init.log");
116         GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
117         afsi_file = CreateFile(wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
118                            OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
119     SetFilePointer(afsi_file, 0, NULL, FILE_END);
120         GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, u, sizeof(u));
121         strcat(t, ": Create log file\n");
122         strcat(u, ": Created log file\n");
123         WriteFile(afsi_file, t, strlen(t), &zilch, NULL);
124         WriteFile(afsi_file, u, strlen(u), &zilch, NULL);
125     p = "PATH=";
126     path = getenv("PATH");
127         WriteFile(afsi_file, p, strlen(p), &zilch, NULL);
128         WriteFile(afsi_file, path, strlen(path), &zilch, NULL);
129         WriteFile(afsi_file, "\n", 1, &zilch, NULL);
130 }
131
132 static int afsi_log_useTimestamp = 1;
133
134 void
135 afsi_log(char *pattern, ...)
136 {
137         char s[100], t[100], d[100], u[300];
138         int zilch;
139         va_list ap;
140         va_start(ap, pattern);
141
142         vsprintf(s, pattern, ap);
143     if ( afsi_log_useTimestamp ) {
144         GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
145                 GetDateFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, d, sizeof(d));
146                 sprintf(u, "%s %s: %s\n", d, t, s);
147         if (afsi_file != INVALID_HANDLE_VALUE)
148             WriteFile(afsi_file, u, strlen(u), &zilch, NULL);
149 #ifdef NOTSERVICE
150         printf("%s", u);
151 #endif 
152     } else {
153         if (afsi_file != INVALID_HANDLE_VALUE)
154             WriteFile(afsi_file, s, strlen(s), &zilch, NULL);
155     }
156 }
157
158 /*
159  * Standard AFSD trace
160  */
161
162 void afsd_ForceTrace(BOOL flush)
163 {
164         HANDLE handle;
165         int len;
166         char buf[256];
167
168         if (!logReady) 
169         return;
170
171         len = GetTempPath(sizeof(buf)-10, buf);
172         strcpy(&buf[len], "/afsd.log");
173         handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
174                             NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
175         if (handle == INVALID_HANDLE_VALUE) {
176                 logReady = 0;
177                 osi_panic("Cannot create log file", __FILE__, __LINE__);
178         }
179         osi_LogPrint(afsd_logp, handle);
180         if (flush)
181                 FlushFileBuffers(handle);
182         CloseHandle(handle);
183 }
184
185 /*
186  * AFSD Initialization
187  */
188
189 int afsd_InitCM(char **reasonP)
190 {
191         osi_uid_t debugID;
192         long cacheBlocks;
193         long cacheSize;
194         long logChunkSize;
195         long stats;
196         long traceBufSize;
197         long ltt, ltto;
198     long rx_mtu, rx_nojumbo;
199         char rootCellName[256];
200         struct rx_service *serverp;
201         static struct rx_securityClass *nullServerSecurityClassp;
202         struct hostent *thp;
203         char *msgBuf;
204         char buf[200];
205         HKEY parmKey;
206         DWORD dummyLen;
207         long code;
208         /*int freelanceEnabled;*/
209         WSADATA WSAjunk;
210     lana_number_t lanaNum;
211
212         WSAStartup(0x0101, &WSAjunk);
213
214         /* setup osidebug server at RPC slot 1000 */
215         osi_LongToUID(1000, &debugID);
216         code = osi_InitDebug(&debugID);
217         afsi_log("osi_InitDebug code %d", code);
218
219     //  osi_LockTypeSetDefault("stat"); /* comment this out for speed *
220         if (code != 0) {
221                 *reasonP = "unknown error";
222                 return -1;
223         }
224
225         /* who are we ? */
226         gethostname(cm_HostName, sizeof(cm_HostName));
227         afsi_log("gethostname %s", cm_HostName);
228         thp = gethostbyname(cm_HostName);
229         memcpy(&cm_HostAddr, thp->h_addr_list[0], 4);
230
231         /* seed random number generator */
232         srand(ntohl(cm_HostAddr));
233
234         /* Look up configuration parameters in Registry */
235         code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSConfigKeyName,
236                                 0, KEY_QUERY_VALUE, &parmKey);
237         if (code != ERROR_SUCCESS) {
238                 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
239                                 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
240                               NULL, code, 0, (LPTSTR)&msgBuf, 0, NULL);
241                 sprintf(buf,
242                         "Failure in configuration while opening Registry: %s",
243                         msgBuf);
244                 osi_panic(buf, __FILE__, __LINE__);
245         }
246
247         dummyLen = sizeof(traceBufSize);
248         code = RegQueryValueEx(parmKey, "TraceBufferSize", NULL, NULL,
249                                 (BYTE *) &traceBufSize, &dummyLen);
250         if (code == ERROR_SUCCESS)
251                 afsi_log("Trace Buffer size %d", traceBufSize);
252         else {
253                 traceBufSize = CM_CONFIGDEFAULT_TRACEBUFSIZE;
254                 afsi_log("Default trace buffer size %d", traceBufSize);
255         }
256
257         /* setup and enable debug log */
258         afsd_logp = osi_LogCreate("afsd", traceBufSize);
259         afsi_log("osi_LogCreate log addr %x", (int)afsd_logp);
260     osi_LogEnable(afsd_logp);
261         logReady = 1;
262
263     osi_Log0(afsd_logp, "Log init");
264
265         dummyLen = sizeof(cacheSize);
266         code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
267                                 (BYTE *) &cacheSize, &dummyLen);
268         if (code == ERROR_SUCCESS)
269                 afsi_log("Cache size %d", cacheSize);
270         else {
271                 cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
272                 afsi_log("Default cache size %d", cacheSize);
273         }
274
275         dummyLen = sizeof(logChunkSize);
276         code = RegQueryValueEx(parmKey, "ChunkSize", NULL, NULL,
277                                 (BYTE *) &logChunkSize, &dummyLen);
278         if (code == ERROR_SUCCESS) {
279                 if (logChunkSize < 12 || logChunkSize > 30) {
280                         afsi_log("Invalid chunk size %d, using default",
281                                  logChunkSize);
282                         logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
283                 }
284                 afsi_log("Chunk size %d", logChunkSize);
285         } else {
286                 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
287                 afsi_log("Default chunk size %d", logChunkSize);
288         }
289         cm_logChunkSize = logChunkSize;
290         cm_chunkSize = 1 << logChunkSize;
291
292         dummyLen = sizeof(numBkgD);
293         code = RegQueryValueEx(parmKey, "Daemons", NULL, NULL,
294                                 (BYTE *) &numBkgD, &dummyLen);
295         if (code == ERROR_SUCCESS)
296                 afsi_log("%d background daemons", numBkgD);
297         else {
298                 numBkgD = CM_CONFIGDEFAULT_DAEMONS;
299                 afsi_log("Defaulting to %d background daemons", numBkgD);
300         }
301
302         dummyLen = sizeof(numSvThreads);
303         code = RegQueryValueEx(parmKey, "ServerThreads", NULL, NULL,
304                                 (BYTE *) &numSvThreads, &dummyLen);
305         if (code == ERROR_SUCCESS)
306                 afsi_log("%d server threads", numSvThreads);
307         else {
308                 numSvThreads = CM_CONFIGDEFAULT_SVTHREADS;
309                 afsi_log("Defaulting to %d server threads", numSvThreads);
310         }
311
312         dummyLen = sizeof(stats);
313         code = RegQueryValueEx(parmKey, "Stats", NULL, NULL,
314                                 (BYTE *) &stats, &dummyLen);
315         if (code == ERROR_SUCCESS)
316                 afsi_log("Status cache size %d", stats);
317         else {
318                 stats = CM_CONFIGDEFAULT_STATS;
319                 afsi_log("Default status cache size %d", stats);
320         }
321
322         dummyLen = sizeof(ltt);
323         code = RegQueryValueEx(parmKey, "LogoffTokenTransfer", NULL, NULL,
324                                 (BYTE *) &ltt, &dummyLen);
325         if (code == ERROR_SUCCESS)
326                 afsi_log("Logoff token transfer %s",  (ltt ? "on" : "off"));
327         else {
328                 ltt = 1;
329                 afsi_log("Logoff token transfer on by default");
330         }
331         smb_LogoffTokenTransfer = ltt;
332
333         if (ltt) {
334                 dummyLen = sizeof(ltto);
335                 code = RegQueryValueEx(parmKey, "LogoffTokenTransferTimeout",
336                                         NULL, NULL, (BYTE *) &ltto, &dummyLen);
337                 if (code == ERROR_SUCCESS)
338                         afsi_log("Logoff token tranfer timeout %d seconds",
339                                  ltto);
340                 else {
341                         ltto = 10;
342                         afsi_log("Default logoff token transfer timeout 10 seconds");
343                 }
344         }
345         smb_LogoffTransferTimeout = ltto;
346
347         dummyLen = sizeof(cm_rootVolumeName);
348         code = RegQueryValueEx(parmKey, "RootVolume", NULL, NULL,
349                                 cm_rootVolumeName, &dummyLen);
350         if (code == ERROR_SUCCESS)
351                 afsi_log("Root volume %s", cm_rootVolumeName);
352         else {
353                 strcpy(cm_rootVolumeName, "root.afs");
354                 afsi_log("Default root volume name root.afs");
355         }
356
357         cm_mountRootLen = sizeof(cm_mountRoot);
358         code = RegQueryValueEx(parmKey, "Mountroot", NULL, NULL,
359                                 cm_mountRoot, &cm_mountRootLen);
360         if (code == ERROR_SUCCESS) {
361                 afsi_log("Mount root %s", cm_mountRoot);
362                 cm_mountRootLen = strlen(cm_mountRoot);
363         } else {
364                 strcpy(cm_mountRoot, "/afs");
365                 cm_mountRootLen = 4;
366                 /* Don't log */
367         }
368
369         dummyLen = sizeof(cm_CachePath);
370         code = RegQueryValueEx(parmKey, "CachePath", NULL, NULL,
371                                 cm_CachePath, &dummyLen);
372         if (code == ERROR_SUCCESS)
373                 afsi_log("Cache path %s", cm_CachePath);
374         else {
375                 GetWindowsDirectory(cm_CachePath, sizeof(cm_CachePath));
376                 cm_CachePath[2] = 0;    /* get drive letter only */
377                 strcat(cm_CachePath, "\\AFSCache");
378                 afsi_log("Default cache path %s", cm_CachePath);
379         }
380
381         dummyLen = sizeof(traceOnPanic);
382         code = RegQueryValueEx(parmKey, "TrapOnPanic", NULL, NULL,
383                                 (BYTE *) &traceOnPanic, &dummyLen);
384         if (code == ERROR_SUCCESS)
385                 afsi_log("Set to %s on panic",
386                          traceOnPanic ? "trap" : "not trap");
387         else {
388                 traceOnPanic = 0;
389                 /* Don't log */
390         }
391
392         dummyLen = sizeof(reportSessionStartups);
393         code = RegQueryValueEx(parmKey, "ReportSessionStartups", NULL, NULL,
394                                 (BYTE *) &reportSessionStartups, &dummyLen);
395         if (code == ERROR_SUCCESS)
396                 afsi_log("Session startups %s be recorded in the Event Log",
397                          reportSessionStartups ? "will" : "will not");
398         else {
399                 reportSessionStartups = 0;
400                 /* Don't log */
401         }
402
403         dummyLen = sizeof(cm_sysName);
404         code = RegQueryValueEx(parmKey, "SysName", NULL, NULL,
405                                 cm_sysName, &dummyLen);
406         if (code == ERROR_SUCCESS)
407                 afsi_log("Sys name %s", cm_sysName);
408         else {
409                 strcat(cm_sysName, "i386_nt40");
410                 afsi_log("Default sys name %s", cm_sysName);
411         }
412
413         dummyLen = sizeof(cryptall);
414         code = RegQueryValueEx(parmKey, "SecurityLevel", NULL, NULL,
415                                 (BYTE *) &cryptall, &dummyLen);
416         if (code == ERROR_SUCCESS)
417                 afsi_log("SecurityLevel is %s", cryptall?"crypt":"clear");
418         else {
419                 cryptall = rxkad_clear;
420                 afsi_log("Default SecurityLevel is clear");
421         }
422
423 #ifdef AFS_AFSDB_ENV
424         dummyLen = sizeof(cm_dnsEnabled);
425         code = RegQueryValueEx(parmKey, "UseDNS", NULL, NULL,
426                                 (BYTE *) &cm_dnsEnabled, &dummyLen);
427         if (code == ERROR_SUCCESS) {
428                 afsi_log("DNS %s be used to find AFS cell servers",
429                          cm_dnsEnabled ? "will" : "will not");
430         }
431         else {
432           cm_dnsEnabled = 1;   /* default on */
433           afsi_log("Default to use DNS to find AFS cell servers");
434         }
435 #else /* AFS_AFSDB_ENV */
436         afsi_log("AFS not built with DNS support to find AFS cell servers");
437 #endif /* AFS_AFSDB_ENV */
438
439 #ifdef AFS_FREELANCE_CLIENT
440         dummyLen = sizeof(cm_freelanceEnabled);
441         code = RegQueryValueEx(parmKey, "FreelanceClient", NULL, NULL,
442                                 (BYTE *) &cm_freelanceEnabled, &dummyLen);
443         if (code == ERROR_SUCCESS) {
444                 afsi_log("Freelance client feature %s activated",
445                          cm_freelanceEnabled ? "is" : "is not");
446         }
447         else {
448           cm_freelanceEnabled = 0;  /* default off */
449         }
450 #endif /* AFS_FREELANCE_CLIENT */
451
452     dummyLen = sizeof(buf);
453     code = RegQueryValueEx(parmKey, "NetbiosName", NULL, NULL,
454                            (BYTE *) &buf, &dummyLen);
455     if (code == ERROR_SUCCESS) {
456         DWORD len = ExpandEnvironmentStrings(buf, cm_NetBiosName, MAX_NB_NAME_LENGTH);
457         if ( len > 0 && len <= MAX_NB_NAME_LENGTH ) {
458             afsi_log("Explicit NetBios name is used %s", cm_NetBiosName);
459         } else {
460             afsi_log("Unable to Expand Explicit NetBios name: %s", buf);
461             cm_NetBiosName[0] = 0;  /* turn it off */
462         }
463     }
464     else {
465         cm_NetBiosName[0] = 0;   /* default off */
466     }
467
468     dummyLen = sizeof(smb_hideDotFiles);
469     code = RegQueryValueEx(parmKey, "HideDotFiles", NULL, NULL,
470                            (BYTE *) &smb_hideDotFiles, &dummyLen);
471     if (code != ERROR_SUCCESS) {
472         smb_hideDotFiles = 1; /* default on */
473     }
474     afsi_log("Dot files/dirs will %sbe marked hidden",
475               smb_hideDotFiles ? "" : "not ");
476
477     dummyLen = sizeof(smb_maxMpxRequests);
478     code = RegQueryValueEx(parmKey, "MaxMpxRequests", NULL, NULL,
479                            (BYTE *) &smb_maxMpxRequests, &dummyLen);
480     if (code != ERROR_SUCCESS) {
481         smb_maxMpxRequests = 50;
482     }
483     afsi_log("Maximum number of multiplexed sessions is %d", smb_maxMpxRequests);
484
485     dummyLen = sizeof(smb_maxVCPerServer);
486     code = RegQueryValueEx(parmKey, "MaxVCPerServer", NULL, NULL,
487                            (BYTE *) &smb_maxVCPerServer, &dummyLen);
488     if (code != ERROR_SUCCESS) {
489         smb_maxVCPerServer = 100;
490     }
491     afsi_log("Maximum number of VCs per server is %d", smb_maxVCPerServer);
492
493     dummyLen = sizeof(rx_nojumbo);
494     code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
495                            (BYTE *) &rx_nojumbo, &dummyLen);
496     if (code != ERROR_SUCCESS) {
497         rx_nojumbo = 0;
498     }
499     if(rx_nojumbo)
500         afsi_log("RX Jumbograms are disabled");
501
502     dummyLen = sizeof(rx_mtu);
503     code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
504                            (BYTE *) &rx_mtu, &dummyLen);
505     if (code != ERROR_SUCCESS || !rx_mtu) {
506         rx_mtu = -1;
507     }
508     if(rx_mtu != -1)
509         afsi_log("RX maximum MTU is %d", rx_mtu);
510
511         RegCloseKey (parmKey);
512
513     /* Call lanahelper to get Netbios name, lan adapter number and gateway flag */
514     if(SUCCEEDED(code = lana_GetUncServerNameEx(cm_NetbiosName, &lanaNum, &isGateway, LANA_NETBIOS_NAME_FULL))) {
515         LANadapter = (lanaNum == LANA_INVALID)? -1: lanaNum;
516
517         if(LANadapter != -1)
518             afsi_log("LAN adapter number %d", LANadapter);
519         else
520             afsi_log("LAN adapter number not determined");
521
522         if(isGateway)
523             afsi_log("Set for gateway service");
524
525         afsi_log("Using >%s< as SMB server name", cm_NetbiosName);
526     } else {
527         /* something went horribly wrong.  We can't proceed without a netbios name */
528         sprintf(buf,"Netbios name could not be determined: %li", code);
529         osi_panic(buf, __FILE__, __LINE__);
530     }
531
532         /* setup early variables */
533         /* These both used to be configurable. */
534         smb_UseV3 = 1;
535     buf_bufferSize = CM_CONFIGDEFAULT_BLOCKSIZE;
536
537         /* turn from 1024 byte units into memory blocks */
538     cacheBlocks = (cacheSize * 1024) / buf_bufferSize;
539         
540         /* get network related info */
541         cm_noIPAddr = CM_MAXINTERFACE_ADDR;
542         code = syscfg_GetIFInfo(&cm_noIPAddr,
543                             cm_IPAddr, cm_SubnetMask,
544                             cm_NetMtu, cm_NetFlags);
545
546         if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
547             afsi_log("syscfg_GetIFInfo error code %d", code);
548         else
549             afsi_log("First Network address %x SubnetMask %x",
550                  cm_IPAddr[0], cm_SubnetMask[0]);
551
552         /*
553          * Save client configuration for GetCacheConfig requests
554          */
555         cm_initParams.nChunkFiles = 0;
556         cm_initParams.nStatCaches = stats;
557         cm_initParams.nDataCaches = 0;
558         cm_initParams.nVolumeCaches = 0;
559         cm_initParams.firstChunkSize = cm_chunkSize;
560         cm_initParams.otherChunkSize = cm_chunkSize;
561         cm_initParams.cacheSize = cacheSize;
562         cm_initParams.setTime = 0;
563         cm_initParams.memCache = 0;
564
565     /* Set RX parameters before initializing RX */
566     if ( rx_nojumbo ) {
567         rx_SetNoJumbo();
568         afsi_log("rx_SetNoJumbo successful");
569     }
570
571     if ( rx_mtu != -1 ) {
572         rx_SetMaxMTU(rx_mtu);
573         afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
574     }
575
576     /* Open Microsoft Firewall to allow in port 7001 */
577     {
578         HKEY hk;
579         DWORD dwDisp;
580         TCHAR* value = TEXT("7001:UDP:*:Enabled:AFS Cache Manager Callback");
581         if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, 
582                             "SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\DomainProfile\\GloballyOpenP", 
583                             0, TEXT("container"), 0, KEY_SET_VALUE, NULL, &hk, &dwDisp) == ERROR_SUCCESS)
584         {
585             RegSetValueEx (hk, TEXT("7001:UDP"), 0, REG_SZ, (PBYTE)value, sizeof(TCHAR) * (1+lstrlen(value)));
586             RegCloseKey (hk);
587         }
588         if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, 
589                             "SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\StandardProfile\\GloballyOpenP", 
590                             0, TEXT("container"), 0, KEY_SET_VALUE, NULL, &hk, &dwDisp) == ERROR_SUCCESS)
591         {
592             RegSetValueEx (hk, TEXT("7001:UDP"), 0, REG_SZ, (PBYTE)value, sizeof(TCHAR) * (1+lstrlen(value)));
593             RegCloseKey (hk);
594         }
595     }
596
597         /* initialize RX, and tell it to listen to port 7001, which is used for
598      * callback RPC messages.
599      */
600         code = rx_Init(htons(7001));
601         afsi_log("rx_Init code %x", code);
602         if (code != 0) {
603                 *reasonP = "afsd: failed to init rx client on port 7001";
604                 return -1;
605         }
606
607         /* Initialize the RPC server for session keys */
608         RpcInit();
609
610         /* create an unauthenticated service #1 for callbacks */
611         nullServerSecurityClassp = rxnull_NewServerSecurityObject();
612     serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
613                             RXAFSCB_ExecuteRequest);
614         afsi_log("rx_NewService addr %x", (int)serverp);
615         if (serverp == NULL) {
616                 *reasonP = "unknown error";
617                 return -1;
618         }
619
620         nullServerSecurityClassp = rxnull_NewServerSecurityObject();
621     serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
622                             &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
623         afsi_log("rx_NewService addr %x", (int)serverp);
624         if (serverp == NULL) {
625                 *reasonP = "unknown error";
626                 return -1;
627         }
628         
629     /* start server threads, *not* donating this one to the pool */
630     rx_StartServer(0);
631         afsi_log("rx_StartServer");
632
633         /* init user daemon, and other packages */
634         cm_InitUser();
635
636         cm_InitACLCache(2*stats);
637
638         cm_InitConn();
639
640     cm_InitCell();
641         
642     cm_InitServer();
643         
644     cm_InitVolume();
645
646     cm_InitIoctl();
647         
648     smb_InitIoctl();
649         
650     cm_InitCallback();
651         
652     cm_InitSCache(stats);
653         
654     code = cm_InitDCache(0, cacheBlocks);
655         afsi_log("cm_InitDCache code %x", code);
656         if (code != 0) {
657                 *reasonP = "error initializing cache";
658                 return -1;
659         }
660
661 #ifdef AFS_AFSDB_ENV
662 #if !defined(_WIN32_WINNT) || _WIN32_WINNT < 0x500
663         if (cm_InitDNS(cm_dnsEnabled) == -1)
664           cm_dnsEnabled = 0;  /* init failed, so deactivate */
665         afsi_log("cm_InitDNS %d", cm_dnsEnabled);
666 #endif
667 #endif
668
669         code = cm_GetRootCellName(rootCellName);
670         afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s", 
671              code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
672         if (code != 0 && !cm_freelanceEnabled) 
673     {
674             *reasonP = "can't find root cell name in afsd.ini";
675             return -1;
676     }
677     else if (cm_freelanceEnabled)
678         cm_rootCellp = NULL;
679
680     if (code == 0 && !cm_freelanceEnabled) 
681     {
682         cm_rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
683         afsi_log("cm_GetCell addr %x", (int)cm_rootCellp);
684         if (cm_rootCellp == NULL) 
685         {
686             *reasonP = "can't find root cell in afsdcell.ini";
687             return -1;
688         }
689         }
690
691 #ifdef AFS_FREELANCE_CLIENT
692         if (cm_freelanceEnabled)
693           cm_InitFreelance();
694 #endif
695
696         return 0;
697 }
698
699 int afsd_InitDaemons(char **reasonP)
700 {
701         long code;
702         cm_req_t req;
703
704         cm_InitReq(&req);
705
706         /* this should really be in an init daemon from here on down */
707
708     if (!cm_freelanceEnabled) {
709         code = cm_GetVolumeByName(cm_rootCellp, cm_rootVolumeName, cm_rootUserp,
710                                   &req, CM_FLAG_CREATE, &cm_rootVolumep);
711         afsi_log("cm_GetVolumeByName code %x root vol %x", code,
712                  (code ? (cm_volume_t *)-1 : cm_rootVolumep));
713         if (code != 0) {
714             *reasonP = "can't find root volume in root cell";
715             return -1;
716         }
717     }
718
719         /* compute the root fid */
720         if (!cm_freelanceEnabled) {
721         cm_rootFid.cell = cm_rootCellp->cellID;
722         cm_rootFid.volume = cm_GetROVolumeID(cm_rootVolumep);
723         cm_rootFid.vnode = 1;
724         cm_rootFid.unique = 1;
725         }
726         else
727         cm_FakeRootFid(&cm_rootFid);
728         
729     code = cm_GetSCache(&cm_rootFid, &cm_rootSCachep, cm_rootUserp, &req);
730         afsi_log("cm_GetSCache code %x scache %x", code,
731              (code ? (cm_scache_t *)-1 : cm_rootSCachep));
732         if (code != 0) {
733                 *reasonP = "unknown error";
734                 return -1;
735         }
736
737         cm_InitDaemon(numBkgD);
738         afsi_log("cm_InitDaemon");
739
740         return 0;
741 }
742
743 int afsd_InitSMB(char **reasonP, void *aMBfunc)
744 {
745         /* Do this last so that we don't handle requests before init is done.
746      * Here we initialize the SMB listener.
747      */
748     smb_Init(afsd_logp, cm_NetbiosName, smb_UseV3, LANadapter, numSvThreads, aMBfunc);
749     afsi_log("smb_Init");
750
751         return 0;
752 }
753
754 #ifdef ReadOnly
755 #undef ReadOnly
756 #endif
757
758 #ifdef File
759 #undef File
760 #endif
761
762 #pragma pack( push, before_imagehlp, 8 )
763 #include <imagehlp.h>
764 #pragma pack( pop, before_imagehlp )
765
766 #define MAXNAMELEN 1024
767
768 void afsd_printStack(HANDLE hThread, CONTEXT *c)
769 {
770     HANDLE hProcess = GetCurrentProcess();
771     int frameNum;
772     DWORD offset;
773     DWORD symOptions;
774     char functionName[MAXNAMELEN];
775   
776     IMAGEHLP_MODULE Module;
777     IMAGEHLP_LINE Line;
778   
779     STACKFRAME s;
780     IMAGEHLP_SYMBOL *pSym;
781   
782     afsi_log_useTimestamp = 0;
783   
784     pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
785   
786     memset( &s, '\0', sizeof s );
787     if (!SymInitialize(hProcess, NULL, 1) )
788     {
789         afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
790       
791         SymCleanup( hProcess );
792         GlobalFree(pSym);
793       
794         return;
795     }
796   
797     symOptions = SymGetOptions();
798     symOptions |= SYMOPT_LOAD_LINES;
799     symOptions &= ~SYMOPT_UNDNAME;
800     SymSetOptions( symOptions );
801   
802     /*
803      * init STACKFRAME for first call
804      * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
805      * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
806      * and good riddance.
807      */
808 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
809 #error The STACKFRAME initialization in afsd_printStack() for this platform
810 #error must be properly configured
811 #else
812     s.AddrPC.Offset = c->Eip;
813     s.AddrPC.Mode = AddrModeFlat;
814     s.AddrFrame.Offset = c->Ebp;
815     s.AddrFrame.Mode = AddrModeFlat;
816 #endif
817
818     memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
819     pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
820     pSym->MaxNameLength = MAXNAMELEN;
821   
822     memset( &Line, '\0', sizeof Line );
823     Line.SizeOfStruct = sizeof Line;
824   
825     memset( &Module, '\0', sizeof Module );
826     Module.SizeOfStruct = sizeof Module;
827   
828     offset = 0;
829   
830     afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
831   
832     for ( frameNum = 0; ; ++ frameNum )
833     {
834         /*
835          * get next stack frame (StackWalk(), SymFunctionTableAccess(), 
836          * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
837          * ERROR_NOACCESS (998), you can assume that either you are done, or
838          * that the stack is so hosed that the next deeper frame could not be
839          * found.
840          */
841         if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c, 
842                           NULL, SymFunctionTableAccess, SymGetModuleBase, 
843                           NULL ) )
844             break;
845       
846         /* display its contents */
847         afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
848                  frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
849                  s.AddrPC.Offset, s.AddrReturn.Offset,
850                  s.AddrFrame.Offset, s.AddrStack.Offset );
851       
852         if ( s.AddrPC.Offset == 0 )
853         {
854             afsi_log("(-nosymbols- PC == 0)" );
855         }
856         else
857         { 
858             /* show procedure info from a valid PC */
859             if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
860             {
861                 if ( GetLastError() != ERROR_INVALID_ADDRESS )
862                 {
863                     afsi_log("SymGetSymFromAddr(): errno = %lu", 
864                              GetLastError());
865                 }
866             }
867             else
868             {
869                 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN, 
870                                      UNDNAME_NAME_ONLY);
871                 afsi_log("%s", functionName );
872
873                 if ( offset != 0 )
874                 {
875                     afsi_log(" %+ld bytes", (long) offset);
876                 }
877             }
878
879             if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
880             {
881                 if (GetLastError() != ERROR_INVALID_ADDRESS)
882                 {
883                     afsi_log("Error: SymGetLineFromAddr(): errno = %lu", 
884                              GetLastError());
885                 }
886             }
887             else
888             {
889                 afsi_log("    Line: %s(%lu) %+ld bytes", Line.FileName, 
890                          Line.LineNumber, offset);
891             }
892         }
893       
894         /* no return address means no deeper stackframe */
895         if (s.AddrReturn.Offset == 0)
896         {
897             SetLastError(0);
898             break;
899         }
900     }
901   
902     if (GetLastError() != 0)
903     {
904         afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
905     }
906   
907     SymCleanup(hProcess);
908     GlobalFree(pSym);
909 }
910
911 #ifdef _DEBUG
912 static DWORD *afsd_crtDbgBreakCurrent = NULL;
913 static DWORD afsd_crtDbgBreaks[256];
914 #endif
915
916 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
917 {
918     CONTEXT context;
919 #ifdef _DEBUG  
920     BOOL allocRequestBrk = FALSE;
921 #endif 
922   
923     afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n", 
924              ep->ExceptionRecord->ExceptionCode, 
925              ep->ExceptionRecord->ExceptionAddress);
926            
927 #ifdef _DEBUG
928     if (afsd_crtDbgBreakCurrent && 
929         *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
930     { 
931         allocRequestBrk = TRUE;
932         afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
933     }
934 #endif
935            
936     /* save context if we want to print the stack information */
937     context = *ep->ContextRecord;
938            
939     afsd_printStack(GetCurrentThread(), &context);
940            
941     if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
942     {
943         afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
944     
945 #ifdef _DEBUG
946         if (allocRequestBrk)
947         {
948             afsd_crtDbgBreakCurrent++;
949             _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
950         }
951 #endif         
952     
953         ep->ContextRecord->Eip++;
954         return EXCEPTION_CONTINUE_EXECUTION;
955     }
956     else
957     {
958         return EXCEPTION_CONTINUE_SEARCH;
959     }
960 }
961   
962 void afsd_SetUnhandledExceptionFilter()
963 {
964     SetUnhandledExceptionFilter(afsd_ExceptionFilter);
965 }
966   
967 #ifdef _DEBUG
968 void afsd_DbgBreakAllocInit()
969 {
970     memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
971     afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
972 }
973   
974 void afsd_DbgBreakAdd(DWORD requestNumber)
975 {
976     int i;
977     for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
978         {
979         if (afsd_crtDbgBreaks[i] == -1)
980             {
981             break;
982             }
983         }
984     afsd_crtDbgBreaks[i] = requestNumber;
985
986     _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);
987 }
988 #endif