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