win-xp-sp2-20040325
[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     /* Open Microsoft Firewall to allow in port 7001 */
575     {
576         HKEY hk;
577         DWORD dwDisp;
578         TCHAR value = TEXT("7001:UDP:*:Enabled:AFS Cache Manager Callback");
579         if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, 
580                             "SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\DomainProfile\GloballyOpenP", 
581                             0, TEXT("container"), 0, KEY_SET_VALUE, NULL, &hk, &dwDisp) == ERROR_SUCCESS)
582         {
583             RegSetValueEx (hk, TEXT("7001:UDP"), NULL, REG_SZ, (PBYTE)value, sizeof(TCHAR) * (1+lstrlen(value)));
584             RegCloseKey (hk);
585         }
586         if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, 
587                             "SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\StandardProfile\GloballyOpenP", 
588                             0, TEXT("container"), 0, KEY_SET_VALUE, NULL, &hk, &dwDisp) == ERROR_SUCCESS)
589         {
590             RegSetValueEx (hk, TEXT("7001:UDP"), NULL, REG_SZ, (PBYTE)value, sizeof(TCHAR) * (1+lstrlen(value)));
591             RegCloseKey (hk);
592         }
593     }
594
595         /* initialize RX, and tell it to listen to port 7001, which is used for
596      * callback RPC messages.
597      */
598         code = rx_Init(htons(7001));
599         afsi_log("rx_Init code %x", code);
600         if (code != 0) {
601                 *reasonP = "afsd: failed to init rx client on port 7001";
602                 return -1;
603         }
604
605         /* Initialize the RPC server for session keys */
606         RpcInit();
607
608         /* create an unauthenticated service #1 for callbacks */
609         nullServerSecurityClassp = rxnull_NewServerSecurityObject();
610     serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
611                             RXAFSCB_ExecuteRequest);
612         afsi_log("rx_NewService addr %x", (int)serverp);
613         if (serverp == NULL) {
614                 *reasonP = "unknown error";
615                 return -1;
616         }
617
618         nullServerSecurityClassp = rxnull_NewServerSecurityObject();
619     serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
620                             &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
621         afsi_log("rx_NewService addr %x", (int)serverp);
622         if (serverp == NULL) {
623                 *reasonP = "unknown error";
624                 return -1;
625         }
626         
627     /* start server threads, *not* donating this one to the pool */
628     rx_StartServer(0);
629         afsi_log("rx_StartServer");
630
631         /* init user daemon, and other packages */
632         cm_InitUser();
633
634         cm_InitACLCache(2*stats);
635
636         cm_InitConn();
637
638     cm_InitCell();
639         
640     cm_InitServer();
641         
642     cm_InitVolume();
643
644     cm_InitIoctl();
645         
646     smb_InitIoctl();
647         
648     cm_InitCallback();
649         
650     cm_InitSCache(stats);
651         
652     code = cm_InitDCache(0, cacheBlocks);
653         afsi_log("cm_InitDCache code %x", code);
654         if (code != 0) {
655                 *reasonP = "error initializing cache";
656                 return -1;
657         }
658
659 #ifdef AFS_AFSDB_ENV
660 #if !defined(_WIN32_WINNT) || _WIN32_WINNT < 0x500
661         if (cm_InitDNS(cm_dnsEnabled) == -1)
662           cm_dnsEnabled = 0;  /* init failed, so deactivate */
663         afsi_log("cm_InitDNS %d", cm_dnsEnabled);
664 #endif
665 #endif
666
667         code = cm_GetRootCellName(rootCellName);
668         afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s", 
669              code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
670         if (code != 0 && !cm_freelanceEnabled) 
671     {
672             *reasonP = "can't find root cell name in afsd.ini";
673             return -1;
674     }
675     else if (cm_freelanceEnabled)
676         cm_rootCellp = NULL;
677
678     if (code == 0 && !cm_freelanceEnabled) 
679     {
680         cm_rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
681         afsi_log("cm_GetCell addr %x", (int)cm_rootCellp);
682         if (cm_rootCellp == NULL) 
683         {
684             *reasonP = "can't find root cell in afsdcell.ini";
685             return -1;
686         }
687         }
688
689 #ifdef AFS_FREELANCE_CLIENT
690         if (cm_freelanceEnabled)
691           cm_InitFreelance();
692 #endif
693
694         return 0;
695 }
696
697 int afsd_InitDaemons(char **reasonP)
698 {
699         long code;
700         cm_req_t req;
701
702         cm_InitReq(&req);
703
704         /* this should really be in an init daemon from here on down */
705
706     if (!cm_freelanceEnabled) {
707         code = cm_GetVolumeByName(cm_rootCellp, cm_rootVolumeName, cm_rootUserp,
708                                   &req, CM_FLAG_CREATE, &cm_rootVolumep);
709         afsi_log("cm_GetVolumeByName code %x root vol %x", code,
710                  (code ? (cm_volume_t *)-1 : cm_rootVolumep));
711         if (code != 0) {
712             *reasonP = "can't find root volume in root cell";
713             return -1;
714         }
715     }
716
717         /* compute the root fid */
718         if (!cm_freelanceEnabled) {
719         cm_rootFid.cell = cm_rootCellp->cellID;
720         cm_rootFid.volume = cm_GetROVolumeID(cm_rootVolumep);
721         cm_rootFid.vnode = 1;
722         cm_rootFid.unique = 1;
723         }
724         else
725         cm_FakeRootFid(&cm_rootFid);
726         
727     code = cm_GetSCache(&cm_rootFid, &cm_rootSCachep, cm_rootUserp, &req);
728         afsi_log("cm_GetSCache code %x scache %x", code,
729              (code ? (cm_scache_t *)-1 : cm_rootSCachep));
730         if (code != 0) {
731                 *reasonP = "unknown error";
732                 return -1;
733         }
734
735         cm_InitDaemon(numBkgD);
736         afsi_log("cm_InitDaemon");
737
738         return 0;
739 }
740
741 int afsd_InitSMB(char **reasonP, void *aMBfunc)
742 {
743         /* Do this last so that we don't handle requests before init is done.
744      * Here we initialize the SMB listener.
745      */
746     smb_Init(afsd_logp, cm_NetbiosName, 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" );
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)" );
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", 
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", (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", 
882                              GetLastError());
883                 }
884             }
885             else
886             {
887                 afsi_log("    Line: %s(%lu) %+ld bytes", Line.FileName, 
888                          Line.LineNumber, offset);
889             }
890         }
891       
892         /* no return address means no deeper stackframe */
893         if (s.AddrReturn.Offset == 0)
894         {
895             SetLastError(0);
896             break;
897         }
898     }
899   
900     if (GetLastError() != 0)
901     {
902         afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
903     }
904   
905     SymCleanup(hProcess);
906     GlobalFree(pSym);
907 }
908
909 #ifdef _DEBUG
910 static DWORD *afsd_crtDbgBreakCurrent = NULL;
911 static DWORD afsd_crtDbgBreaks[256];
912 #endif
913
914 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
915 {
916     CONTEXT context;
917 #ifdef _DEBUG  
918     BOOL allocRequestBrk = FALSE;
919 #endif 
920   
921     afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n", 
922              ep->ExceptionRecord->ExceptionCode, 
923              ep->ExceptionRecord->ExceptionAddress);
924            
925 #ifdef _DEBUG
926     if (afsd_crtDbgBreakCurrent && 
927         *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
928     { 
929         allocRequestBrk = TRUE;
930         afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
931     }
932 #endif
933            
934     /* save context if we want to print the stack information */
935     context = *ep->ContextRecord;
936            
937     afsd_printStack(GetCurrentThread(), &context);
938            
939     if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
940     {
941         afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
942     
943 #ifdef _DEBUG
944         if (allocRequestBrk)
945         {
946             afsd_crtDbgBreakCurrent++;
947             _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
948         }
949 #endif         
950     
951         ep->ContextRecord->Eip++;
952         return EXCEPTION_CONTINUE_EXECUTION;
953     }
954     else
955     {
956         return EXCEPTION_CONTINUE_SEARCH;
957     }
958 }
959   
960 void afsd_SetUnhandledExceptionFilter()
961 {
962     SetUnhandledExceptionFilter(afsd_ExceptionFilter);
963 }
964   
965 #ifdef _DEBUG
966 void afsd_DbgBreakAllocInit()
967 {
968     memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
969     afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
970 }
971   
972 void afsd_DbgBreakAdd(DWORD requestNumber)
973 {
974     int i;
975     for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
976         {
977         if (afsd_crtDbgBreaks[i] == -1)
978             {
979             break;
980             }
981         }
982     afsd_crtDbgBreaks[i] = requestNumber;
983
984     _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);
985 }
986 #endif