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