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