30b905c6b80eaed4ff6a3e2008402df1d48d7889
[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         } else {
345         ltto = 0;
346     }
347     smb_LogoffTransferTimeout = ltto;
348
349         dummyLen = sizeof(cm_rootVolumeName);
350         code = RegQueryValueEx(parmKey, "RootVolume", NULL, NULL,
351                                 cm_rootVolumeName, &dummyLen);
352         if (code == ERROR_SUCCESS)
353                 afsi_log("Root volume %s", cm_rootVolumeName);
354         else {
355                 strcpy(cm_rootVolumeName, "root.afs");
356                 afsi_log("Default root volume name root.afs");
357         }
358
359         cm_mountRootLen = sizeof(cm_mountRoot);
360         code = RegQueryValueEx(parmKey, "Mountroot", NULL, NULL,
361                                 cm_mountRoot, &cm_mountRootLen);
362         if (code == ERROR_SUCCESS) {
363                 afsi_log("Mount root %s", cm_mountRoot);
364                 cm_mountRootLen = strlen(cm_mountRoot);
365         } else {
366                 strcpy(cm_mountRoot, "/afs");
367                 cm_mountRootLen = 4;
368                 /* Don't log */
369         }
370
371         dummyLen = sizeof(cm_CachePath);
372         code = RegQueryValueEx(parmKey, "CachePath", NULL, NULL,
373                                 cm_CachePath, &dummyLen);
374         if (code == ERROR_SUCCESS)
375                 afsi_log("Cache path %s", cm_CachePath);
376         else {
377                 GetWindowsDirectory(cm_CachePath, sizeof(cm_CachePath));
378                 cm_CachePath[2] = 0;    /* get drive letter only */
379                 strcat(cm_CachePath, "\\AFSCache");
380                 afsi_log("Default cache path %s", cm_CachePath);
381         }
382
383         dummyLen = sizeof(traceOnPanic);
384         code = RegQueryValueEx(parmKey, "TrapOnPanic", NULL, NULL,
385                                 (BYTE *) &traceOnPanic, &dummyLen);
386         if (code == ERROR_SUCCESS)
387                 afsi_log("Set to %s on panic",
388                          traceOnPanic ? "trap" : "not trap");
389         else {
390                 traceOnPanic = 0;
391                 /* Don't log */
392         }
393
394         dummyLen = sizeof(reportSessionStartups);
395         code = RegQueryValueEx(parmKey, "ReportSessionStartups", NULL, NULL,
396                                 (BYTE *) &reportSessionStartups, &dummyLen);
397         if (code == ERROR_SUCCESS)
398                 afsi_log("Session startups %s be recorded in the Event Log",
399                          reportSessionStartups ? "will" : "will not");
400         else {
401                 reportSessionStartups = 0;
402                 /* Don't log */
403         }
404
405         dummyLen = sizeof(cm_sysName);
406         code = RegQueryValueEx(parmKey, "SysName", NULL, NULL,
407                                 cm_sysName, &dummyLen);
408         if (code == ERROR_SUCCESS)
409                 afsi_log("Sys name %s", cm_sysName);
410         else {
411                 strcat(cm_sysName, "i386_nt40");
412                 afsi_log("Default sys name %s", cm_sysName);
413         }
414
415         dummyLen = sizeof(cryptall);
416         code = RegQueryValueEx(parmKey, "SecurityLevel", NULL, NULL,
417                                 (BYTE *) &cryptall, &dummyLen);
418         if (code == ERROR_SUCCESS)
419                 afsi_log("SecurityLevel is %s", cryptall?"crypt":"clear");
420         else {
421                 cryptall = rxkad_clear;
422                 afsi_log("Default SecurityLevel is clear");
423         }
424
425 #ifdef AFS_AFSDB_ENV
426         dummyLen = sizeof(cm_dnsEnabled);
427         code = RegQueryValueEx(parmKey, "UseDNS", NULL, NULL,
428                                 (BYTE *) &cm_dnsEnabled, &dummyLen);
429         if (code == ERROR_SUCCESS) {
430                 afsi_log("DNS %s be used to find AFS cell servers",
431                          cm_dnsEnabled ? "will" : "will not");
432         }
433         else {
434           cm_dnsEnabled = 1;   /* default on */
435           afsi_log("Default to use DNS to find AFS cell servers");
436         }
437 #else /* AFS_AFSDB_ENV */
438         afsi_log("AFS not built with DNS support to find AFS cell servers");
439 #endif /* AFS_AFSDB_ENV */
440
441 #ifdef AFS_FREELANCE_CLIENT
442         dummyLen = sizeof(cm_freelanceEnabled);
443         code = RegQueryValueEx(parmKey, "FreelanceClient", NULL, NULL,
444                                 (BYTE *) &cm_freelanceEnabled, &dummyLen);
445         if (code == ERROR_SUCCESS) {
446                 afsi_log("Freelance client feature %s activated",
447                          cm_freelanceEnabled ? "is" : "is not");
448         }
449         else {
450           cm_freelanceEnabled = 0;  /* default off */
451         }
452 #endif /* AFS_FREELANCE_CLIENT */
453
454     dummyLen = sizeof(buf);
455     code = RegQueryValueEx(parmKey, "NetbiosName", NULL, NULL,
456                            (BYTE *) &buf, &dummyLen);
457     if (code == ERROR_SUCCESS) {
458         DWORD len = ExpandEnvironmentStrings(buf, cm_NetBiosName, MAX_NB_NAME_LENGTH);
459         if ( len > 0 && len <= MAX_NB_NAME_LENGTH ) {
460             afsi_log("Explicit NetBios name is used %s", cm_NetBiosName);
461         } else {
462             afsi_log("Unable to Expand Explicit NetBios name: %s", buf);
463             cm_NetBiosName[0] = 0;  /* turn it off */
464         }
465     }
466     else {
467         cm_NetBiosName[0] = 0;   /* default off */
468     }
469
470     dummyLen = sizeof(smb_hideDotFiles);
471     code = RegQueryValueEx(parmKey, "HideDotFiles", NULL, NULL,
472                            (BYTE *) &smb_hideDotFiles, &dummyLen);
473     if (code != ERROR_SUCCESS) {
474         smb_hideDotFiles = 1; /* default on */
475     }
476     afsi_log("Dot files/dirs will %sbe marked hidden",
477               smb_hideDotFiles ? "" : "not ");
478
479     dummyLen = sizeof(smb_maxMpxRequests);
480     code = RegQueryValueEx(parmKey, "MaxMpxRequests", NULL, NULL,
481                            (BYTE *) &smb_maxMpxRequests, &dummyLen);
482     if (code != ERROR_SUCCESS) {
483         smb_maxMpxRequests = 50;
484     }
485     afsi_log("Maximum number of multiplexed sessions is %d", smb_maxMpxRequests);
486
487     dummyLen = sizeof(smb_maxVCPerServer);
488     code = RegQueryValueEx(parmKey, "MaxVCPerServer", NULL, NULL,
489                            (BYTE *) &smb_maxVCPerServer, &dummyLen);
490     if (code != ERROR_SUCCESS) {
491         smb_maxVCPerServer = 100;
492     }
493     afsi_log("Maximum number of VCs per server is %d", smb_maxVCPerServer);
494
495     dummyLen = sizeof(rx_nojumbo);
496     code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
497                            (BYTE *) &rx_nojumbo, &dummyLen);
498     if (code != ERROR_SUCCESS) {
499         rx_nojumbo = 0;
500     }
501     if(rx_nojumbo)
502         afsi_log("RX Jumbograms are disabled");
503
504     dummyLen = sizeof(rx_mtu);
505     code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
506                            (BYTE *) &rx_mtu, &dummyLen);
507     if (code != ERROR_SUCCESS || !rx_mtu) {
508         rx_mtu = -1;
509     }
510     if(rx_mtu != -1)
511         afsi_log("RX maximum MTU is %d", rx_mtu);
512
513         RegCloseKey (parmKey);
514
515     /* Call lanahelper to get Netbios name, lan adapter number and gateway flag */
516     if(SUCCEEDED(code = lana_GetUncServerNameEx(cm_NetbiosName, &lanaNum, &isGateway, LANA_NETBIOS_NAME_FULL))) {
517         LANadapter = (lanaNum == LANA_INVALID)? -1: lanaNum;
518
519         if(LANadapter != -1)
520             afsi_log("LAN adapter number %d", LANadapter);
521         else
522             afsi_log("LAN adapter number not determined");
523
524         if(isGateway)
525             afsi_log("Set for gateway service");
526
527         afsi_log("Using >%s< as SMB server name", cm_NetbiosName);
528     } else {
529         /* something went horribly wrong.  We can't proceed without a netbios name */
530         sprintf(buf,"Netbios name could not be determined: %li", code);
531         osi_panic(buf, __FILE__, __LINE__);
532     }
533
534         /* setup early variables */
535         /* These both used to be configurable. */
536         smb_UseV3 = 1;
537     buf_bufferSize = CM_CONFIGDEFAULT_BLOCKSIZE;
538
539         /* turn from 1024 byte units into memory blocks */
540     cacheBlocks = (cacheSize * 1024) / buf_bufferSize;
541         
542         /* get network related info */
543         cm_noIPAddr = CM_MAXINTERFACE_ADDR;
544         code = syscfg_GetIFInfo(&cm_noIPAddr,
545                             cm_IPAddr, cm_SubnetMask,
546                             cm_NetMtu, cm_NetFlags);
547
548         if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
549             afsi_log("syscfg_GetIFInfo error code %d", code);
550         else
551             afsi_log("First Network address %x SubnetMask %x",
552                  cm_IPAddr[0], cm_SubnetMask[0]);
553
554         /*
555          * Save client configuration for GetCacheConfig requests
556          */
557         cm_initParams.nChunkFiles = 0;
558         cm_initParams.nStatCaches = stats;
559         cm_initParams.nDataCaches = 0;
560         cm_initParams.nVolumeCaches = 0;
561         cm_initParams.firstChunkSize = cm_chunkSize;
562         cm_initParams.otherChunkSize = cm_chunkSize;
563         cm_initParams.cacheSize = cacheSize;
564         cm_initParams.setTime = 0;
565         cm_initParams.memCache = 0;
566
567     /* Set RX parameters before initializing RX */
568     if ( rx_nojumbo ) {
569         rx_SetNoJumbo();
570         afsi_log("rx_SetNoJumbo successful");
571     }
572
573     if ( rx_mtu != -1 ) {
574         rx_SetMaxMTU(rx_mtu);
575         afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
576     }
577
578     /* Open Microsoft Firewall to allow in port 7001 */
579     {
580         HKEY hk;
581         DWORD dwDisp;
582         TCHAR* value = TEXT("7001:UDP:*:Enabled:AFS Cache Manager Callback");
583         if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, 
584                             "SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\DomainProfile\\GloballyOpenP", 
585                             0, TEXT("container"), 0, KEY_SET_VALUE, NULL, &hk, &dwDisp) == ERROR_SUCCESS)
586         {
587             RegSetValueEx (hk, TEXT("7001:UDP"), 0, REG_SZ, (PBYTE)value, sizeof(TCHAR) * (1+lstrlen(value)));
588             RegCloseKey (hk);
589         }
590         if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, 
591                             "SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\StandardProfile\\GloballyOpenP", 
592                             0, TEXT("container"), 0, KEY_SET_VALUE, NULL, &hk, &dwDisp) == ERROR_SUCCESS)
593         {
594             RegSetValueEx (hk, TEXT("7001:UDP"), 0, REG_SZ, (PBYTE)value, sizeof(TCHAR) * (1+lstrlen(value)));
595             RegCloseKey (hk);
596         }
597     }
598
599         /* initialize RX, and tell it to listen to port 7001, which is used for
600      * callback RPC messages.
601      */
602         code = rx_Init(htons(7001));
603         afsi_log("rx_Init code %x", code);
604         if (code != 0) {
605                 *reasonP = "afsd: failed to init rx client on port 7001";
606                 return -1;
607         }
608
609         /* Initialize the RPC server for session keys */
610         RpcInit();
611
612         /* create an unauthenticated service #1 for callbacks */
613         nullServerSecurityClassp = rxnull_NewServerSecurityObject();
614     serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
615                             RXAFSCB_ExecuteRequest);
616         afsi_log("rx_NewService addr %x", (int)serverp);
617         if (serverp == NULL) {
618                 *reasonP = "unknown error";
619                 return -1;
620         }
621
622         nullServerSecurityClassp = rxnull_NewServerSecurityObject();
623     serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
624                             &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
625         afsi_log("rx_NewService addr %x", (int)serverp);
626         if (serverp == NULL) {
627                 *reasonP = "unknown error";
628                 return -1;
629         }
630         
631     /* start server threads, *not* donating this one to the pool */
632     rx_StartServer(0);
633         afsi_log("rx_StartServer");
634
635         /* init user daemon, and other packages */
636         cm_InitUser();
637
638         cm_InitACLCache(2*stats);
639
640         cm_InitConn();
641
642     cm_InitCell();
643         
644     cm_InitServer();
645         
646     cm_InitVolume();
647
648     cm_InitIoctl();
649         
650     smb_InitIoctl();
651         
652     cm_InitCallback();
653         
654     cm_InitSCache(stats);
655         
656     code = cm_InitDCache(0, cacheBlocks);
657         afsi_log("cm_InitDCache code %x", code);
658         if (code != 0) {
659                 *reasonP = "error initializing cache";
660                 return -1;
661         }
662
663 #ifdef AFS_AFSDB_ENV
664 #if !defined(_WIN32_WINNT) || _WIN32_WINNT < 0x500
665         if (cm_InitDNS(cm_dnsEnabled) == -1)
666           cm_dnsEnabled = 0;  /* init failed, so deactivate */
667         afsi_log("cm_InitDNS %d", cm_dnsEnabled);
668 #endif
669 #endif
670
671         code = cm_GetRootCellName(rootCellName);
672         afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s", 
673              code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
674         if (code != 0 && !cm_freelanceEnabled) 
675     {
676             *reasonP = "can't find root cell name in afsd.ini";
677             return -1;
678     }
679     else if (cm_freelanceEnabled)
680         cm_rootCellp = NULL;
681
682     if (code == 0 && !cm_freelanceEnabled) 
683     {
684         cm_rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
685         afsi_log("cm_GetCell addr %x", (int)cm_rootCellp);
686         if (cm_rootCellp == NULL) 
687         {
688             *reasonP = "can't find root cell in afsdcell.ini";
689             return -1;
690         }
691         }
692
693 #ifdef AFS_FREELANCE_CLIENT
694         if (cm_freelanceEnabled)
695           cm_InitFreelance();
696 #endif
697
698         return 0;
699 }
700
701 int afsd_InitDaemons(char **reasonP)
702 {
703         long code;
704         cm_req_t req;
705
706         cm_InitReq(&req);
707
708         /* this should really be in an init daemon from here on down */
709
710     if (!cm_freelanceEnabled) {
711         code = cm_GetVolumeByName(cm_rootCellp, cm_rootVolumeName, cm_rootUserp,
712                                   &req, CM_FLAG_CREATE, &cm_rootVolumep);
713         afsi_log("cm_GetVolumeByName code %x root vol %x", code,
714                  (code ? (cm_volume_t *)-1 : cm_rootVolumep));
715         if (code != 0) {
716             *reasonP = "can't find root volume in root cell";
717             return -1;
718         }
719     }
720
721         /* compute the root fid */
722         if (!cm_freelanceEnabled) {
723         cm_rootFid.cell = cm_rootCellp->cellID;
724         cm_rootFid.volume = cm_GetROVolumeID(cm_rootVolumep);
725         cm_rootFid.vnode = 1;
726         cm_rootFid.unique = 1;
727         }
728         else
729         cm_FakeRootFid(&cm_rootFid);
730         
731     code = cm_GetSCache(&cm_rootFid, &cm_rootSCachep, cm_rootUserp, &req);
732         afsi_log("cm_GetSCache code %x scache %x", code,
733              (code ? (cm_scache_t *)-1 : cm_rootSCachep));
734         if (code != 0) {
735                 *reasonP = "unknown error";
736                 return -1;
737         }
738
739         cm_InitDaemon(numBkgD);
740         afsi_log("cm_InitDaemon");
741
742         return 0;
743 }
744
745 int afsd_InitSMB(char **reasonP, void *aMBfunc)
746 {
747         /* Do this last so that we don't handle requests before init is done.
748      * Here we initialize the SMB listener.
749      */
750     smb_Init(afsd_logp, cm_NetbiosName, smb_UseV3, LANadapter, numSvThreads, aMBfunc);
751     afsi_log("smb_Init");
752
753         return 0;
754 }
755
756 #ifdef ReadOnly
757 #undef ReadOnly
758 #endif
759
760 #ifdef File
761 #undef File
762 #endif
763
764 #pragma pack( push, before_imagehlp, 8 )
765 #include <imagehlp.h>
766 #pragma pack( pop, before_imagehlp )
767
768 #define MAXNAMELEN 1024
769
770 void afsd_printStack(HANDLE hThread, CONTEXT *c)
771 {
772     HANDLE hProcess = GetCurrentProcess();
773     int frameNum;
774     DWORD offset;
775     DWORD symOptions;
776     char functionName[MAXNAMELEN];
777   
778     IMAGEHLP_MODULE Module;
779     IMAGEHLP_LINE Line;
780   
781     STACKFRAME s;
782     IMAGEHLP_SYMBOL *pSym;
783   
784     afsi_log_useTimestamp = 0;
785   
786     pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
787   
788     memset( &s, '\0', sizeof s );
789     if (!SymInitialize(hProcess, NULL, 1) )
790     {
791         afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
792       
793         SymCleanup( hProcess );
794         GlobalFree(pSym);
795       
796         return;
797     }
798   
799     symOptions = SymGetOptions();
800     symOptions |= SYMOPT_LOAD_LINES;
801     symOptions &= ~SYMOPT_UNDNAME;
802     SymSetOptions( symOptions );
803   
804     /*
805      * init STACKFRAME for first call
806      * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
807      * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
808      * and good riddance.
809      */
810 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
811 #error The STACKFRAME initialization in afsd_printStack() for this platform
812 #error must be properly configured
813 #else
814     s.AddrPC.Offset = c->Eip;
815     s.AddrPC.Mode = AddrModeFlat;
816     s.AddrFrame.Offset = c->Ebp;
817     s.AddrFrame.Mode = AddrModeFlat;
818 #endif
819
820     memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
821     pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
822     pSym->MaxNameLength = MAXNAMELEN;
823   
824     memset( &Line, '\0', sizeof Line );
825     Line.SizeOfStruct = sizeof Line;
826   
827     memset( &Module, '\0', sizeof Module );
828     Module.SizeOfStruct = sizeof Module;
829   
830     offset = 0;
831   
832     afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
833   
834     for ( frameNum = 0; ; ++ frameNum )
835     {
836         /*
837          * get next stack frame (StackWalk(), SymFunctionTableAccess(), 
838          * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
839          * ERROR_NOACCESS (998), you can assume that either you are done, or
840          * that the stack is so hosed that the next deeper frame could not be
841          * found.
842          */
843         if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c, 
844                           NULL, SymFunctionTableAccess, SymGetModuleBase, 
845                           NULL ) )
846             break;
847       
848         /* display its contents */
849         afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
850                  frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
851                  s.AddrPC.Offset, s.AddrReturn.Offset,
852                  s.AddrFrame.Offset, s.AddrStack.Offset );
853       
854         if ( s.AddrPC.Offset == 0 )
855         {
856             afsi_log("(-nosymbols- PC == 0)" );
857         }
858         else
859         { 
860             /* show procedure info from a valid PC */
861             if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
862             {
863                 if ( GetLastError() != ERROR_INVALID_ADDRESS )
864                 {
865                     afsi_log("SymGetSymFromAddr(): errno = %lu", 
866                              GetLastError());
867                 }
868             }
869             else
870             {
871                 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN, 
872                                      UNDNAME_NAME_ONLY);
873                 afsi_log("%s", functionName );
874
875                 if ( offset != 0 )
876                 {
877                     afsi_log(" %+ld bytes", (long) offset);
878                 }
879             }
880
881             if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
882             {
883                 if (GetLastError() != ERROR_INVALID_ADDRESS)
884                 {
885                     afsi_log("Error: SymGetLineFromAddr(): errno = %lu", 
886                              GetLastError());
887                 }
888             }
889             else
890             {
891                 afsi_log("    Line: %s(%lu) %+ld bytes", Line.FileName, 
892                          Line.LineNumber, offset);
893             }
894         }
895       
896         /* no return address means no deeper stackframe */
897         if (s.AddrReturn.Offset == 0)
898         {
899             SetLastError(0);
900             break;
901         }
902     }
903   
904     if (GetLastError() != 0)
905     {
906         afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
907     }
908   
909     SymCleanup(hProcess);
910     GlobalFree(pSym);
911 }
912
913 #ifdef _DEBUG
914 static DWORD *afsd_crtDbgBreakCurrent = NULL;
915 static DWORD afsd_crtDbgBreaks[256];
916 #endif
917
918 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
919 {
920     CONTEXT context;
921 #ifdef _DEBUG  
922     BOOL allocRequestBrk = FALSE;
923 #endif 
924   
925     afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n", 
926              ep->ExceptionRecord->ExceptionCode, 
927              ep->ExceptionRecord->ExceptionAddress);
928            
929 #ifdef _DEBUG
930     if (afsd_crtDbgBreakCurrent && 
931         *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
932     { 
933         allocRequestBrk = TRUE;
934         afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
935     }
936 #endif
937            
938     /* save context if we want to print the stack information */
939     context = *ep->ContextRecord;
940            
941     afsd_printStack(GetCurrentThread(), &context);
942            
943     if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
944     {
945         afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
946     
947 #ifdef _DEBUG
948         if (allocRequestBrk)
949         {
950             afsd_crtDbgBreakCurrent++;
951             _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
952         }
953 #endif         
954     
955         ep->ContextRecord->Eip++;
956         return EXCEPTION_CONTINUE_EXECUTION;
957     }
958     else
959     {
960         return EXCEPTION_CONTINUE_SEARCH;
961     }
962 }
963   
964 void afsd_SetUnhandledExceptionFilter()
965 {
966     SetUnhandledExceptionFilter(afsd_ExceptionFilter);
967 }
968   
969 #ifdef _DEBUG
970 void afsd_DbgBreakAllocInit()
971 {
972     memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
973     afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
974 }
975   
976 void afsd_DbgBreakAdd(DWORD requestNumber)
977 {
978     int i;
979     for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
980         {
981         if (afsd_crtDbgBreaks[i] == -1)
982             {
983             break;
984             }
985         }
986     afsd_crtDbgBreaks[i] = requestNumber;
987
988     _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);
989 }
990 #endif