b851b425ebca4f6d1f0e4f9eaddb221aa6cd0074
[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 <locale.h>
20 #include <mbctype.h>
21 #include <winsock2.h>
22 #include <ErrorRep.h>
23
24 #include <osi.h>
25 #include "afsd.h"
26 #include <rx\rx.h>
27 #include <rx\rx_null.h>
28 #include <WINNT/syscfg.h>
29 #include <WINNT/afsreg.h>
30
31 #include "smb.h"
32 #include "cm_rpc.h"
33 #include "lanahelper.h"
34 #include <strsafe.h>
35 #include "cm_memmap.h"
36
37 extern int RXAFSCB_ExecuteRequest(struct rx_call *z_call);
38 extern int RXSTATS_ExecuteRequest(struct rx_call *z_call);
39
40 extern afs_int32 cryptall;
41
42 osi_log_t *afsd_logp;
43
44 cm_config_data_t        cm_data;
45
46 char cm_rootVolumeName[VL_MAXNAMELEN];
47 DWORD cm_rootVolumeNameLen;
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 = 1;
57
58 int LANadapter;
59
60 int numBkgD;
61 int numSvThreads;
62 long rx_mtu = -1;
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[MAX_PATH];
73 DWORD cm_CachePathLen;
74 DWORD cm_ValidateCache = 1;
75
76 BOOL isGateway = FALSE;
77
78 BOOL reportSessionStartups = FALSE;
79
80 cm_initparams_v1 cm_initParams;
81
82 char *cm_sysName = 0;
83 unsigned int   cm_sysNameCount = 0;
84 char *cm_sysNameList[MAXNUMSYSNAMES];
85
86 DWORD TraceOption = 0;
87
88 /*
89  * AFSD Initialization Log
90  *
91  * This is distinct from the regular debug logging facility.
92  * Log items go directly to a file, not to an array in memory, so that even
93  * if AFSD crashes, the log can be inspected.
94  */
95
96 HANDLE afsi_file;
97
98 #ifdef AFS_AFSDB_ENV
99 int cm_dnsEnabled = 1;
100 #endif
101
102
103 static int afsi_log_useTimestamp = 1;
104
105 void
106 afsi_log(char *pattern, ...)
107 {
108     char s[256], t[100], d[100], u[512];
109     DWORD zilch;
110     va_list ap;
111     va_start(ap, pattern);
112
113     StringCbVPrintfA(s, sizeof(s), pattern, ap);
114     if ( afsi_log_useTimestamp ) {
115         GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
116         GetDateFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, d, sizeof(d));
117         StringCbPrintfA(u, sizeof(u), "%s %s: %s\n", d, t, s);
118         if (afsi_file != INVALID_HANDLE_VALUE)
119             WriteFile(afsi_file, u, (DWORD)strlen(u), &zilch, NULL);
120 #ifdef NOTSERVICE
121         printf("%s", u);
122 #endif 
123     } else {
124         if (afsi_file != INVALID_HANDLE_VALUE)
125             WriteFile(afsi_file, s, (DWORD)strlen(s), &zilch, NULL);
126     }
127 }
128
129 extern initUpperCaseTable();
130 void afsd_initUpperCaseTable() 
131 {
132     initUpperCaseTable();
133 }
134
135 void
136 afsi_start()
137 {
138     char wd[256];
139     char t[100], u[100], *p, *path;
140     int zilch;
141     DWORD code;
142     DWORD dwLow, dwHigh;
143     HKEY parmKey;
144     DWORD dummyLen;
145     DWORD maxLogSize = 100 * 1024;
146
147     afsi_file = INVALID_HANDLE_VALUE;
148     code = GetEnvironmentVariable("TEMP", wd, sizeof(wd));
149     if ( code == 0 || code > sizeof(wd) )
150     {
151         code = GetWindowsDirectory(wd, sizeof(wd));
152         if (code == 0) 
153             return;
154     }
155     StringCbCatA(wd, sizeof(wd), "\\afsd_init.log");
156     GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
157     afsi_file = CreateFile(wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
158                            OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
159
160     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
161                          0, KEY_QUERY_VALUE, &parmKey);
162     if (code == ERROR_SUCCESS) {
163         dummyLen = sizeof(maxLogSize);
164         code = RegQueryValueEx(parmKey, "MaxLogSize", NULL, NULL,
165                                 (BYTE *) &maxLogSize, &dummyLen);
166         RegCloseKey (parmKey);
167     }
168
169     if (maxLogSize) {
170         dwLow = GetFileSize( afsi_file, &dwHigh );
171         if ( dwHigh > 0 || dwLow >= maxLogSize ) {
172             CloseHandle(afsi_file);
173             afsi_file = CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
174                                     CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
175         }
176     }
177
178     SetFilePointer(afsi_file, 0, NULL, FILE_END);
179     GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, u, sizeof(u));
180     StringCbCatA(t, sizeof(t), ": Create log file\n");
181     StringCbCatA(u, sizeof(u), ": Created log file\n");
182     WriteFile(afsi_file, t, (DWORD)strlen(t), &zilch, NULL);
183     WriteFile(afsi_file, u, (DWORD)strlen(u), &zilch, NULL);
184     p = "PATH=";
185     code = GetEnvironmentVariable("PATH", NULL, 0);
186     path = malloc(code);
187     code = GetEnvironmentVariable("PATH", path, code);
188     WriteFile(afsi_file, p, (DWORD)strlen(p), &zilch, NULL);
189     WriteFile(afsi_file, path, (DWORD)strlen(path), &zilch, NULL);
190     WriteFile(afsi_file, "\n", (DWORD)1, &zilch, NULL);
191     free(path);
192
193     /* Initialize C RTL Code Page conversion functions */
194     /* All of the path info obtained from the SMB client is in the OEM code page */
195     afsi_log("OEM Code Page = %d", GetOEMCP());
196     afsi_log("locale =  %s", setlocale(LC_ALL,NULL));
197 #ifdef COMMENT
198     /* Two things to look into.  First, should mbstowcs() be performing 
199      * character set translations from OEM to Unicode in smb3.c; 
200      * Second, do we need to set this translation in each function 
201      * due to multi-threading. 
202      */
203     afsi_log("locale -> %s", setlocale(LC_ALL, ".OCP"));
204     afsi_log("_setmbcp = %d -> %d", _setmbcp(_MB_CP_OEM), _getmbcp());
205 #endif /* COMMENT */
206 }
207
208 /*
209  * Standard AFSD trace
210  */
211
212 void afsd_ForceTrace(BOOL flush)
213 {
214     HANDLE handle;
215     int len;
216     char buf[256];
217
218     if (!logReady) 
219         return;
220
221     len = GetTempPath(sizeof(buf)-10, buf);
222     StringCbCopyA(&buf[len], sizeof(buf)-len, "/afsd.log");
223     handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
224                          NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
225     if (handle == INVALID_HANDLE_VALUE) {
226         logReady = 0;
227         osi_panic("Cannot create log file", __FILE__, __LINE__);
228     }
229     osi_LogPrint(afsd_logp, handle);
230     if (flush)
231         FlushFileBuffers(handle);
232     CloseHandle(handle);
233 }
234
235 static void
236 configureBackConnectionHostNames(void)
237 {
238     /* On Windows XP SP2, Windows 2003 SP1, and all future Windows operating systems
239      * there is a restriction on the use of SMB authentication on loopback connections.
240      * There are two work arounds available:
241      * 
242      *   (1) We can disable the check for matching host names.  This does not
243      *   require a reboot:
244      *   [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa]
245      *     "DisableLoopbackCheck"=dword:00000001
246      *
247      *   (2) We can add the AFS SMB/CIFS service name to an approved list.  This
248      *   does require a reboot:
249      *   [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0]
250      *     "BackConnectionHostNames"=multi-sz
251      *
252      * The algorithm will be:
253      *   (1) Check to see if cm_NetbiosName exists in the BackConnectionHostNames list
254      *   (2a) If not, add it to the list.  (This will not take effect until the next reboot.)
255      *   (2b1)    and check to see if DisableLoopbackCheck is set.
256      *   (2b2)    If not set, set the DisableLoopbackCheck value to 0x1 
257      *   (2b3)                and create HKLM\SOFTWARE\OpenAFS\Client  UnsetDisableLoopbackCheck
258      *   (2c) else If cm_NetbiosName exists in the BackConnectionHostNames list,
259      *             check for the UnsetDisableLoopbackCheck value.  
260      *             If set, set the DisableLoopbackCheck flag to 0x0 
261      *             and delete the UnsetDisableLoopbackCheck value
262      *
263      * Starting in Longhorn Beta 1, an entry in the BackConnectionHostNames value will
264      * force Windows to use the loopback authentication mechanism for the specified 
265      * services.
266      */
267     HKEY hkLsa;
268     HKEY hkMSV10;
269     HKEY hkClient;
270     DWORD dwType;
271     DWORD dwSize;
272     DWORD dwValue;
273     PBYTE pHostNames = NULL, pName = NULL;
274     BOOL  bNameFound = FALSE;   
275
276     if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
277                        "SYSTEM\\CurrentControlSet\\Control\\Lsa\\MSV1_0",
278                        0,
279                        KEY_READ|KEY_WRITE,
280                        &hkMSV10) == ERROR_SUCCESS )
281     {
282         if (RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0, &dwType, NULL, &dwSize) == ERROR_SUCCESS) {
283             pHostNames = malloc(dwSize + strlen(cm_NetbiosName) + 1);
284             RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0, &dwType, pHostNames, &dwSize);
285
286             for (pName = pHostNames; *pName ; pName += strlen(pName) + 1)
287             {
288                 if ( !stricmp(pName, cm_NetbiosName) ) {
289                     bNameFound = TRUE;
290                     break;
291                 }   
292             }
293         }
294              
295         if ( !bNameFound ) {
296             size_t size = strlen(cm_NetbiosName) + 2;
297             if ( !pHostNames ) {
298                 pHostNames = malloc(size);
299                 dwSize = 1;
300             }
301             pName = pHostNames;
302             StringCbCopyA(pName, size, cm_NetbiosName);
303             pName += size - 1;
304             *pName = '\0';  /* add a second nul terminator */
305
306             dwType = REG_MULTI_SZ;
307             dwSize += (DWORD)strlen(cm_NetbiosName) + 1;
308             RegSetValueEx( hkMSV10, "BackConnectionHostNames", 0, dwType, pHostNames, dwSize);
309
310             if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
311                                "SYSTEM\\CurrentControlSet\\Control\\Lsa",
312                                0,
313                                KEY_READ|KEY_WRITE,
314                                &hkLsa) == ERROR_SUCCESS )
315             {
316                 dwSize = sizeof(DWORD);
317                 if ( RegQueryValueEx( hkLsa, "DisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) != ERROR_SUCCESS ||
318                      dwValue == 0 ) {
319                     dwType = REG_DWORD;
320                     dwSize = sizeof(DWORD);
321                     dwValue = 1;
322                     RegSetValueEx( hkLsa, "DisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
323
324                     if (RegCreateKeyEx( HKEY_LOCAL_MACHINE, 
325                                         AFSREG_CLT_OPENAFS_SUBKEY,
326                                         0,
327                                         NULL,
328                                         REG_OPTION_NON_VOLATILE,
329                                         KEY_READ|KEY_WRITE,
330                                         NULL,
331                                         &hkClient,
332                                         NULL) == ERROR_SUCCESS) {
333
334                         dwType = REG_DWORD;
335                         dwSize = sizeof(DWORD);
336                         dwValue = 1;
337                         RegSetValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
338                         RegCloseKey(hkClient);
339                     }
340                     RegCloseKey(hkLsa);
341                 }
342             }
343         } else {
344             if (RegCreateKeyEx( HKEY_LOCAL_MACHINE, 
345                                 AFSREG_CLT_OPENAFS_SUBKEY,
346                                 0,
347                                 NULL,
348                                 REG_OPTION_NON_VOLATILE,
349                                 KEY_READ|KEY_WRITE,
350                                 NULL,
351                                 &hkClient,
352                                 NULL) == ERROR_SUCCESS) {
353
354                 dwSize = sizeof(DWORD);
355                 if ( RegQueryValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) == ERROR_SUCCESS &&
356                      dwValue == 1 ) {
357                     if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
358                                        "SYSTEM\\CurrentControlSet\\Control\\Lsa",
359                                        0,
360                                        KEY_READ|KEY_WRITE,
361                                        &hkLsa) == ERROR_SUCCESS )
362                     {
363                         RegDeleteValue(hkLsa, "DisableLoopbackCheck");
364                         RegCloseKey(hkLsa);
365                     }
366                 }
367                 RegDeleteValue(hkClient, "RemoveDisableLoopbackCheck");
368                 RegCloseKey(hkClient);
369             }
370         }
371         RegCloseKey(hkMSV10);
372     }
373 }
374
375 #if !defined(DJGPP)
376 static void afsd_InitServerPreferences(void)
377 {
378     HKEY hkPrefs = 0;
379     DWORD dwType, dwSize;
380     DWORD dwPrefs = 0;
381     DWORD dwIndex;
382     TCHAR szHost[256];
383     DWORD dwHostSize = 256;
384     DWORD dwRank;
385     struct sockaddr_in  saddr;
386     cm_server_t       *tsp;
387
388     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
389                       AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\VLDB",
390                       0,
391                       KEY_READ|KEY_QUERY_VALUE,
392                       &hkPrefs) == ERROR_SUCCESS) {
393
394         RegQueryInfoKey( hkPrefs,
395                          NULL,  /* lpClass */
396                          NULL,  /* lpcClass */
397                          NULL,  /* lpReserved */
398                          NULL,  /* lpcSubKeys */
399                          NULL,  /* lpcMaxSubKeyLen */
400                          NULL,  /* lpcMaxClassLen */
401                          &dwPrefs, /* lpcValues */
402                          NULL,  /* lpcMaxValueNameLen */
403                          NULL,  /* lpcMaxValueLen */
404                          NULL,  /* lpcbSecurityDescriptor */
405                          NULL   /* lpftLastWriteTime */
406                          );
407
408         for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
409
410             dwSize = sizeof(DWORD);
411             dwHostSize = 256;
412
413             if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
414                               &dwType, (LPBYTE)&dwRank, &dwSize))
415             {
416                 afsi_log("RegEnumValue(hkPrefs) failed");
417                 continue;
418             }
419
420             afsi_log("VLDB Server Preference: %s = %d",szHost, dwRank);
421
422             if (isdigit(szHost[0]))
423             {
424                 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
425                     continue;
426             } else {
427                 HOSTENT *pEntry;
428                 if ((pEntry = gethostbyname (szHost)) == NULL)
429                     continue;
430
431                 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
432             }
433             saddr.sin_family = AF_INET;
434             dwRank += (rand() & 0x000f);
435
436             tsp = cm_FindServer(&saddr, CM_SERVER_VLDB);
437             if ( tsp )          /* an existing server - ref count increased */
438             {
439                 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
440
441                 /* set preferences for an existing vlserver */
442                 cm_ChangeRankCellVLServer(tsp);
443                 cm_PutServer(tsp);  /* decrease refcount */
444             }
445             else        /* add a new server without a cell */
446             {
447                 tsp = cm_NewServer(&saddr, CM_SERVER_VLDB, NULL); /* refcount = 1 */
448                 tsp->ipRank = (USHORT)dwRank;
449             }
450         }
451
452         RegCloseKey(hkPrefs);
453     }
454
455     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
456                       AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\File",
457                       0,
458                       KEY_READ|KEY_QUERY_VALUE,
459                       &hkPrefs) == ERROR_SUCCESS) {
460
461         RegQueryInfoKey( hkPrefs,
462                          NULL,  /* lpClass */
463                          NULL,  /* lpcClass */
464                          NULL,  /* lpReserved */
465                          NULL,  /* lpcSubKeys */
466                          NULL,  /* lpcMaxSubKeyLen */
467                          NULL,  /* lpcMaxClassLen */
468                          &dwPrefs, /* lpcValues */
469                          NULL,  /* lpcMaxValueNameLen */
470                          NULL,  /* lpcMaxValueLen */
471                          NULL,  /* lpcbSecurityDescriptor */
472                          NULL   /* lpftLastWriteTime */
473                          );
474
475         for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
476
477             dwSize = sizeof(DWORD);
478             dwHostSize = 256;
479
480             if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
481                               &dwType, (LPBYTE)&dwRank, &dwSize))
482             {
483                 afsi_log("RegEnumValue(hkPrefs) failed");
484                 continue;
485             }
486
487             afsi_log("File Server Preference: %s = %d",szHost, dwRank);
488
489             if (isdigit(szHost[0]))
490             {
491                 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
492                     continue;
493             } else {
494                 HOSTENT *pEntry;
495                 if ((pEntry = gethostbyname (szHost)) == NULL)
496                     continue;
497
498                 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
499             }
500             saddr.sin_family = AF_INET;
501             dwRank += (rand() & 0x000f);
502
503             tsp = cm_FindServer(&saddr, CM_SERVER_FILE);
504             if ( tsp )          /* an existing server - ref count increased */
505             {
506                 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
507
508                 /* find volumes which might have RO copy 
509                 /* on server and change the ordering of 
510                  * their RO list 
511                  */
512                 cm_ChangeRankVolume(tsp);
513                 cm_PutServer(tsp);  /* decrease refcount */
514             }
515             else        /* add a new server without a cell */
516             {
517                 tsp = cm_NewServer(&saddr, CM_SERVER_FILE, NULL); /* refcount = 1 */
518                 tsp->ipRank = (USHORT)dwRank;
519             }
520         }
521
522         RegCloseKey(hkPrefs);
523     }
524 }
525 #endif /* DJGPP */
526
527 /*
528  * AFSD Initialization
529  */
530
531 int afsd_InitCM(char **reasonP)
532 {
533     osi_uid_t debugID;
534     afs_uint64 cacheBlocks;
535     DWORD cacheSize;
536     long logChunkSize;
537     DWORD stats;
538     DWORD rx_enable_peer_stats = 0;
539     DWORD rx_enable_process_stats = 0;
540     long traceBufSize;
541     long maxcpus;
542     long ltt, ltto;
543     long rx_nojumbo;
544     long virtualCache = 0;
545     char rootCellName[256];
546     struct rx_service *serverp;
547     static struct rx_securityClass *nullServerSecurityClassp;
548     struct hostent *thp;
549     char *msgBuf;
550     char buf[1024];
551     HKEY parmKey;
552     DWORD dummyLen;
553     DWORD regType;
554     long code;
555     /*int freelanceEnabled;*/
556     WSADATA WSAjunk;
557     lana_number_t lanaNum;
558     int i;
559     char *p, *q; 
560     int cm_noIPAddr;         /* number of client network interfaces */
561     int cm_IPAddr[CM_MAXINTERFACE_ADDR];    /* client's IP address in host order */
562     int cm_SubnetMask[CM_MAXINTERFACE_ADDR];/* client's subnet mask in host order*/
563     int cm_NetMtu[CM_MAXINTERFACE_ADDR];    /* client's MTU sizes */
564     int cm_NetFlags[CM_MAXINTERFACE_ADDR];  /* network flags */
565
566     WSAStartup(0x0101, &WSAjunk);
567
568     afsd_initUpperCaseTable();
569     init_et_to_sys_error();
570
571     /* setup osidebug server at RPC slot 1000 */
572     osi_LongToUID(1000, &debugID);
573     code = osi_InitDebug(&debugID);
574     afsi_log("osi_InitDebug code %d", code);
575
576     //  osi_LockTypeSetDefault("stat"); /* comment this out for speed */
577     if (code != 0) {
578         if (code == RPC_S_NO_PROTSEQS)
579             *reasonP = "No RPC Protocol Sequences registered.  Check HKLM\\SOFTWARE\\Microsoft\\RPC\\ClientProtocols";
580         else
581             *reasonP = "unknown error";
582         return -1;
583     }
584
585     /* who are we ? */
586     gethostname(cm_HostName, sizeof(cm_HostName));
587     afsi_log("gethostname %s", cm_HostName);
588     thp = gethostbyname(cm_HostName);
589     memcpy(&cm_HostAddr, thp->h_addr_list[0], 4);
590
591     /* seed random number generator */
592     srand(ntohl(cm_HostAddr));
593
594     /* Look up configuration parameters in Registry */
595     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
596                          0, KEY_QUERY_VALUE, &parmKey);
597     if (code != ERROR_SUCCESS) {
598         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
599                        | FORMAT_MESSAGE_ALLOCATE_BUFFER,
600                        NULL, code, 0, (LPTSTR)&msgBuf, 0, NULL);
601         StringCbPrintfA(buf, sizeof(buf),
602                          "Failure in configuration while opening Registry: %s",
603                          msgBuf);
604         osi_panic(buf, __FILE__, __LINE__);
605     }
606
607     dummyLen = sizeof(maxcpus);
608     code = RegQueryValueEx(parmKey, "MaxCPUs", NULL, NULL,
609                             (BYTE *) &maxcpus, &dummyLen);
610     if (code == ERROR_SUCCESS) {
611         HANDLE hProcess;
612         DWORD_PTR processAffinityMask, systemAffinityMask;
613
614         hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION,
615                                FALSE, GetCurrentProcessId());
616         if ( hProcess != NULL &&
617              GetProcessAffinityMask(hProcess, &processAffinityMask, &systemAffinityMask) )
618         {
619             int i, n, bits;
620             DWORD_PTR mask, newAffinityMask;
621
622 #if defined(_WIN64)
623             bits = 64;
624 #else
625             bits = 32;
626 #endif
627             for ( i=0, n=0, mask=1, newAffinityMask=0; i<bits && n<maxcpus; i++ ) {
628                 if ( processAffinityMask & mask ) {
629                     newAffinityMask |= mask;
630                     n++;
631                 }
632                 mask *= 2;
633             }
634
635             SetProcessAffinityMask(hProcess, newAffinityMask);
636             CloseHandle(hProcess);
637             afsi_log("CPU Restrictions set to %d cpu(s); %d cpu(s) available", maxcpus, n);
638         } else {
639             afsi_log("CPU Restrictions set to %d cpu(s); unable to access process information", maxcpus);
640         }
641     }
642
643     dummyLen = sizeof(TraceOption);
644     code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
645                             (BYTE *) &TraceOption, &dummyLen);
646     afsi_log("Trace Options = %lX", TraceOption);
647
648     dummyLen = sizeof(traceBufSize);
649     code = RegQueryValueEx(parmKey, "TraceBufferSize", NULL, NULL,
650                             (BYTE *) &traceBufSize, &dummyLen);
651     if (code == ERROR_SUCCESS)
652         afsi_log("Trace Buffer size %d", traceBufSize);
653     else {
654         traceBufSize = CM_CONFIGDEFAULT_TRACEBUFSIZE;
655         afsi_log("Default trace buffer size %d", traceBufSize);
656     }
657
658     /* setup and enable debug log */
659     afsd_logp = osi_LogCreate("afsd", traceBufSize);
660     afsi_log("osi_LogCreate log addr %x", PtrToUlong(afsd_logp));
661     if ((TraceOption & 0x8)
662 #ifdef DEBUG
663          || 1
664 #endif
665          ) {
666         osi_LogEnable(afsd_logp);
667     }
668     logReady = 1;
669
670     osi_Log0(afsd_logp, "Log init");
671
672     dummyLen = sizeof(cacheSize);
673     code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
674                             (BYTE *) &cacheSize, &dummyLen);
675     if (code == ERROR_SUCCESS)
676         afsi_log("Cache size %d", cacheSize);
677     else {
678         cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
679         afsi_log("Default cache size %d", cacheSize);
680     }
681
682     dummyLen = sizeof(logChunkSize);
683     code = RegQueryValueEx(parmKey, "ChunkSize", NULL, NULL,
684                             (BYTE *) &logChunkSize, &dummyLen);
685     if (code == ERROR_SUCCESS) {
686         if (logChunkSize < 12 || logChunkSize > 30) {
687             afsi_log("Invalid chunk size %d, using default",
688                       logChunkSize);
689             logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
690         }
691         afsi_log("Chunk size %d", logChunkSize);
692     } else {
693         logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
694         afsi_log("Default chunk size %d", logChunkSize);
695     }
696     cm_logChunkSize = logChunkSize;
697     cm_chunkSize = 1 << logChunkSize;
698
699     dummyLen = sizeof(numBkgD);
700     code = RegQueryValueEx(parmKey, "Daemons", NULL, NULL,
701                             (BYTE *) &numBkgD, &dummyLen);
702     if (code == ERROR_SUCCESS)
703         afsi_log("%d background daemons", numBkgD);
704     else {
705         numBkgD = CM_CONFIGDEFAULT_DAEMONS;
706         afsi_log("Defaulting to %d background daemons", numBkgD);
707     }
708
709     dummyLen = sizeof(numSvThreads);
710     code = RegQueryValueEx(parmKey, "ServerThreads", NULL, NULL,
711                             (BYTE *) &numSvThreads, &dummyLen);
712     if (code == ERROR_SUCCESS)
713         afsi_log("%d server threads", numSvThreads);
714     else {
715         numSvThreads = CM_CONFIGDEFAULT_SVTHREADS;
716         afsi_log("Defaulting to %d server threads", numSvThreads);
717     }
718
719     dummyLen = sizeof(stats);
720     code = RegQueryValueEx(parmKey, "Stats", NULL, NULL,
721                             (BYTE *) &stats, &dummyLen);
722     if (code == ERROR_SUCCESS)
723         afsi_log("Status cache size %d", stats);
724     else {
725         stats = CM_CONFIGDEFAULT_STATS;
726         afsi_log("Default status cache size %d", stats);
727     }
728
729     dummyLen = sizeof(ltt);
730     code = RegQueryValueEx(parmKey, "LogoffTokenTransfer", NULL, NULL,
731                             (BYTE *) &ltt, &dummyLen);
732     if (code == ERROR_SUCCESS)
733         afsi_log("Logoff token transfer %s",  (ltt ? "on" : "off"));
734     else {
735         ltt = 1;
736         afsi_log("Logoff token transfer on by default");
737     }
738     smb_LogoffTokenTransfer = ltt;
739     afsi_log("Logoff token transfer is currently ignored");
740
741     if (ltt) {
742         dummyLen = sizeof(ltto);
743         code = RegQueryValueEx(parmKey, "LogoffTokenTransferTimeout",
744                                 NULL, NULL, (BYTE *) &ltto, &dummyLen);
745         if (code == ERROR_SUCCESS)
746             afsi_log("Logoff token tranfer timeout %d seconds", ltto);
747         else {
748             ltto = 10;
749             afsi_log("Default logoff token transfer timeout 10 seconds");
750         }
751     } else {
752         ltto = 0;
753     }   
754     smb_LogoffTransferTimeout = ltto;
755     afsi_log("Default logoff token is currently ignored");
756
757     dummyLen = sizeof(cm_rootVolumeName);
758     code = RegQueryValueEx(parmKey, "RootVolume", NULL, NULL,
759                             cm_rootVolumeName, &dummyLen);
760     if (code == ERROR_SUCCESS)
761         afsi_log("Root volume %s", cm_rootVolumeName);
762     else {
763         StringCbCopyA(cm_rootVolumeName, sizeof(cm_rootVolumeName), "root.afs");
764         afsi_log("Default root volume name root.afs");
765     }
766
767     cm_mountRootLen = sizeof(cm_mountRoot);
768     code = RegQueryValueEx(parmKey, "MountRoot", NULL, NULL,
769                             cm_mountRoot, &cm_mountRootLen);
770     if (code == ERROR_SUCCESS) {
771         afsi_log("Mount root %s", cm_mountRoot);
772         cm_mountRootLen = (DWORD)strlen(cm_mountRoot);
773     } else {
774         StringCbCopyA(cm_mountRoot, sizeof(cm_mountRoot), "/afs");
775         cm_mountRootLen = 4;
776         /* Don't log */
777     }
778
779     dummyLen = sizeof(buf);
780     code = RegQueryValueEx(parmKey, "CachePath", NULL, &regType,
781                             buf, &dummyLen);
782     if (code == ERROR_SUCCESS && buf[0]) {
783         if (regType == REG_EXPAND_SZ) {
784             dummyLen = ExpandEnvironmentStrings(buf, cm_CachePath, sizeof(cm_CachePath));
785             if (dummyLen > sizeof(cm_CachePath)) {
786                 afsi_log("Cache path [%s] longer than %d after expanding env strings", buf, sizeof(cm_CachePath));
787                 osi_panic("CachePath too long", __FILE__, __LINE__);
788             }
789         } else {
790             StringCbCopyA(cm_CachePath, sizeof(cm_CachePath), buf);
791         }
792         afsi_log("Cache path %s", cm_CachePath);
793     } else {
794         dummyLen = ExpandEnvironmentStrings("%TEMP%\\AFSCache", cm_CachePath, sizeof(cm_CachePath));
795         if (dummyLen > sizeof(cm_CachePath)) {
796             afsi_log("Cache path [%%TEMP%%\\AFSCache] longer than %d after expanding env strings", 
797                      sizeof(cm_CachePath));
798             osi_panic("CachePath too long", __FILE__, __LINE__);
799         }
800         afsi_log("Default cache path %s", cm_CachePath);
801     }
802
803     dummyLen = sizeof(virtualCache);
804     code = RegQueryValueEx(parmKey, "NonPersistentCaching", NULL, NULL,
805                             (LPBYTE)&virtualCache, &dummyLen);
806     afsi_log("Cache type is %s", (virtualCache?"VIRTUAL":"FILE"));
807
808     if (!virtualCache) {
809         dummyLen = sizeof(cm_ValidateCache);
810         code = RegQueryValueEx(parmKey, "ValidateCache", NULL, NULL,
811                                (LPBYTE)&cm_ValidateCache, &dummyLen);
812         if ( cm_ValidateCache < 0 || cm_ValidateCache > 2 )
813             cm_ValidateCache = 1;
814         switch (cm_ValidateCache) {
815         case 0:
816             afsi_log("Cache Validation disabled");
817             break;
818         case 1:
819             afsi_log("Cache Validation on Startup");
820             break;
821         case 2:
822             afsi_log("Cache Validation on Startup and Shutdown");
823             break;
824         }
825     }
826
827     dummyLen = sizeof(traceOnPanic);
828     code = RegQueryValueEx(parmKey, "TrapOnPanic", NULL, NULL,
829                             (BYTE *) &traceOnPanic, &dummyLen);
830     if (code != ERROR_SUCCESS)
831         traceOnPanic = 1;              /* log */
832     afsi_log("Set to %s on panic", traceOnPanic ? "trap" : "not trap");
833
834     dummyLen = sizeof(reportSessionStartups);
835     code = RegQueryValueEx(parmKey, "ReportSessionStartups", NULL, NULL,
836                             (BYTE *) &reportSessionStartups, &dummyLen);
837     if (code == ERROR_SUCCESS)
838         afsi_log("Session startups %s be recorded in the Event Log",
839                   reportSessionStartups ? "will" : "will not");
840     else {
841         reportSessionStartups = 0;
842         /* Don't log */
843     }
844
845     for ( i=0; i < MAXNUMSYSNAMES; i++ ) {
846         cm_sysNameList[i] = osi_Alloc(MAXSYSNAME);
847         cm_sysNameList[i][0] = '\0';
848     }
849     cm_sysName = cm_sysNameList[0];
850
851     dummyLen = sizeof(buf);
852     code = RegQueryValueEx(parmKey, "SysName", NULL, NULL, buf, &dummyLen);
853     if (code != ERROR_SUCCESS || !buf[0]) {
854 #if defined(_IA64_)
855         StringCbCopyA(buf, sizeof(buf), "ia64_win64");
856 #elif defined(_AMD64)
857         StringCbCopyA(buf, sizeof(buf), "amd64_win64");
858 #else /* assume x86 32-bit */
859         StringCbCopyA(buf, sizeof(buf), "x86_win32 i386_w2k i386_nt40");
860 #endif
861     }
862     afsi_log("Sys name %s", buf); 
863
864     /* breakup buf into individual search string entries */
865     for (p = q = buf; p < buf + dummyLen; p++)
866     {
867         if (*p == '\0' || isspace(*p)) {
868             memcpy(cm_sysNameList[cm_sysNameCount],q,p-q);
869             cm_sysNameList[cm_sysNameCount][p-q] = '\0';
870             cm_sysNameCount++;
871
872             do {
873                 if (*p == '\0')
874                     goto done_sysname;
875                 p++;
876             } while (*p == '\0' || isspace(*p));
877             q = p;
878             p--;
879         }
880     }
881   done_sysname:
882     StringCbCopyA(cm_sysName, MAXSYSNAME, cm_sysNameList[0]);
883
884     dummyLen = sizeof(cryptall);
885     code = RegQueryValueEx(parmKey, "SecurityLevel", NULL, NULL,
886                             (BYTE *) &cryptall, &dummyLen);
887     if (code == ERROR_SUCCESS) {
888         afsi_log("SecurityLevel is %s", cryptall?"crypt":"clear");
889     } else {
890         cryptall = 0;
891         afsi_log("Default SecurityLevel is clear");
892     }
893
894     if (cryptall)
895         LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_ON);
896     else
897         LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_OFF);
898
899 #ifdef AFS_AFSDB_ENV
900     dummyLen = sizeof(cm_dnsEnabled);
901     code = RegQueryValueEx(parmKey, "UseDNS", NULL, NULL,
902                             (BYTE *) &cm_dnsEnabled, &dummyLen);
903     if (code == ERROR_SUCCESS) {
904         afsi_log("DNS %s be used to find AFS cell servers",
905                   cm_dnsEnabled ? "will" : "will not");
906     }       
907     else {
908         cm_dnsEnabled = 1;   /* default on */
909         afsi_log("Default to use DNS to find AFS cell servers");
910     }
911 #else /* AFS_AFSDB_ENV */
912     afsi_log("AFS not built with DNS support to find AFS cell servers");
913 #endif /* AFS_AFSDB_ENV */
914
915 #ifdef AFS_FREELANCE_CLIENT
916     dummyLen = sizeof(cm_freelanceEnabled);
917     code = RegQueryValueEx(parmKey, "FreelanceClient", NULL, NULL,
918                             (BYTE *) &cm_freelanceEnabled, &dummyLen);
919     if (code == ERROR_SUCCESS) {
920         afsi_log("Freelance client feature %s activated",
921                   cm_freelanceEnabled ? "is" : "is not");
922     }       
923     else {
924         cm_freelanceEnabled = 0;  /* default off */
925     }
926 #endif /* AFS_FREELANCE_CLIENT */
927
928 #ifdef COMMENT
929     /* The netbios name is looked up in lana_GetUNCServerNameEx */
930     dummyLen = sizeof(buf);
931     code = RegQueryValueEx(parmKey, "NetbiosName", NULL, NULL,
932                            (BYTE *) &buf, &dummyLen);
933     if (code == ERROR_SUCCESS) {
934         DWORD len = ExpandEnvironmentStrings(buf, cm_NetbiosName, MAX_NB_NAME_LENGTH);
935         if ( len > 0 && len <= MAX_NB_NAME_LENGTH ) {
936             afsi_log("Explicit NetBios name is used %s", cm_NetbiosName);
937         } else {
938             afsi_log("Unable to Expand Explicit NetBios name: %s", buf);
939             cm_NetbiosName[0] = 0;  /* turn it off */
940         }
941     }
942     else {
943         cm_NetbiosName[0] = 0;   /* default off */
944     }
945 #endif
946
947     dummyLen = sizeof(smb_hideDotFiles);
948     code = RegQueryValueEx(parmKey, "HideDotFiles", NULL, NULL,
949                            (BYTE *) &smb_hideDotFiles, &dummyLen);
950     if (code != ERROR_SUCCESS) {
951         smb_hideDotFiles = 1; /* default on */
952     }
953     afsi_log("Dot files/dirs will %sbe marked hidden",
954               smb_hideDotFiles ? "" : "not ");
955
956     dummyLen = sizeof(smb_maxMpxRequests);
957     code = RegQueryValueEx(parmKey, "MaxMpxRequests", NULL, NULL,
958                            (BYTE *) &smb_maxMpxRequests, &dummyLen);
959     if (code != ERROR_SUCCESS) {
960         smb_maxMpxRequests = 50;
961     }
962     afsi_log("Maximum number of multiplexed sessions is %d", smb_maxMpxRequests);
963
964     dummyLen = sizeof(smb_maxVCPerServer);
965     code = RegQueryValueEx(parmKey, "MaxVCPerServer", NULL, NULL,
966                            (BYTE *) &smb_maxVCPerServer, &dummyLen);
967     if (code != ERROR_SUCCESS) {
968         smb_maxVCPerServer = 100;
969     }
970     afsi_log("Maximum number of VCs per server is %d", smb_maxVCPerServer);
971
972     dummyLen = sizeof(smb_authType);
973     code = RegQueryValueEx(parmKey, "SMBAuthType", NULL, NULL,
974                             (BYTE *) &smb_authType, &dummyLen);
975
976     if (code != ERROR_SUCCESS || 
977          (smb_authType != SMB_AUTH_EXTENDED && smb_authType != SMB_AUTH_NTLM && smb_authType != SMB_AUTH_NONE)) {
978         smb_authType = SMB_AUTH_EXTENDED; /* default is to use extended authentication */
979     }
980     afsi_log("SMB authentication type is %s", ((smb_authType == SMB_AUTH_NONE)?"NONE":((smb_authType == SMB_AUTH_EXTENDED)?"EXTENDED":"NTLM")));
981
982     dummyLen = sizeof(rx_nojumbo);
983     code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
984                            (BYTE *) &rx_nojumbo, &dummyLen);
985     if (code != ERROR_SUCCESS) {
986         rx_nojumbo = 0;
987     }
988     if (rx_nojumbo)
989         afsi_log("RX Jumbograms are disabled");
990
991     dummyLen = sizeof(rx_mtu);
992     code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
993                            (BYTE *) &rx_mtu, &dummyLen);
994     if (code != ERROR_SUCCESS || !rx_mtu) {
995         rx_mtu = -1;
996     }
997     if (rx_mtu != -1)
998         afsi_log("RX maximum MTU is %d", rx_mtu);
999
1000     dummyLen = sizeof(rx_enable_peer_stats);
1001     code = RegQueryValueEx(parmKey, "RxEnablePeerStats", NULL, NULL,
1002                            (BYTE *) &rx_enable_peer_stats, &dummyLen);
1003     if (code != ERROR_SUCCESS) {
1004         rx_enable_peer_stats = 0;
1005     }
1006     if (rx_enable_peer_stats)
1007         afsi_log("RX Peer Statistics gathering is enabled");
1008
1009     dummyLen = sizeof(rx_enable_process_stats);
1010     code = RegQueryValueEx(parmKey, "RxEnableProcessStats", NULL, NULL,
1011                            (BYTE *) &rx_enable_process_stats, &dummyLen);
1012     if (code != ERROR_SUCCESS) {
1013         rx_enable_process_stats = 0;
1014     }
1015     if (rx_enable_process_stats)
1016         afsi_log("RX Process Statistics gathering is enabled");
1017
1018     dummyLen = sizeof(ConnDeadtimeout);
1019     code = RegQueryValueEx(parmKey, "ConnDeadTimeout", NULL, NULL,
1020                            (BYTE *) &ConnDeadtimeout, &dummyLen);
1021     afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
1022
1023     dummyLen = sizeof(HardDeadtimeout);
1024     code = RegQueryValueEx(parmKey, "HardDeadTimeout", NULL, NULL,
1025                            (BYTE *) &HardDeadtimeout, &dummyLen);
1026     afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
1027
1028     RegCloseKey (parmKey);
1029
1030     /* Call lanahelper to get Netbios name, lan adapter number and gateway flag */
1031     if (SUCCEEDED(code = lana_GetUncServerNameEx(cm_NetbiosName, &lanaNum, &isGateway, LANA_NETBIOS_NAME_FULL))) {
1032         LANadapter = (lanaNum == LANA_INVALID)? -1: lanaNum;
1033
1034         if (LANadapter != -1)
1035             afsi_log("LAN adapter number %d", LANadapter);
1036         else
1037             afsi_log("LAN adapter number not determined");
1038
1039         if (isGateway)
1040             afsi_log("Set for gateway service");
1041
1042         afsi_log("Using >%s< as SMB server name", cm_NetbiosName);
1043     } else {
1044         /* something went horribly wrong.  We can't proceed without a netbios name */
1045         StringCbPrintfA(buf,sizeof(buf),"Netbios name could not be determined: %li", code);
1046         osi_panic(buf, __FILE__, __LINE__);
1047     }
1048
1049     cacheBlocks = ((afs_uint64)cacheSize * 1024) / CM_CONFIGDEFAULT_BLOCKSIZE;
1050         
1051     /* get network related info */
1052     cm_noIPAddr = CM_MAXINTERFACE_ADDR;
1053     code = syscfg_GetIFInfo(&cm_noIPAddr,
1054                              cm_IPAddr, cm_SubnetMask,
1055                              cm_NetMtu, cm_NetFlags);
1056
1057     if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
1058         afsi_log("syscfg_GetIFInfo error code %d", code);
1059     else
1060         afsi_log("First Network address %x SubnetMask %x",
1061                   cm_IPAddr[0], cm_SubnetMask[0]);
1062
1063     /*
1064      * Save client configuration for GetCacheConfig requests
1065      */
1066     cm_initParams.nChunkFiles = 0;
1067     cm_initParams.nStatCaches = stats;
1068     cm_initParams.nDataCaches = (afs_uint32)(cacheBlocks > 0xFFFFFFFF ? 0xFFFFFFFF : cacheBlocks);
1069     cm_initParams.nVolumeCaches = stats/2;
1070     cm_initParams.firstChunkSize = cm_chunkSize;
1071     cm_initParams.otherChunkSize = cm_chunkSize;
1072     cm_initParams.cacheSize = cacheSize;
1073     cm_initParams.setTime = 0;
1074     cm_initParams.memCache = 1;
1075
1076     /* Ensure the AFS Netbios Name is registered to allow loopback access */
1077     configureBackConnectionHostNames();
1078
1079     /* init user daemon, and other packages */
1080     cm_InitUser();
1081
1082     cm_InitConn();
1083
1084     cm_InitServer();
1085         
1086     cm_InitIoctl();
1087         
1088     smb_InitIoctl();
1089         
1090     cm_InitCallback();
1091         
1092     code = cm_InitMappedMemory(virtualCache, cm_CachePath, stats, cm_chunkSize, cacheBlocks);
1093     afsi_log("cm_InitMappedMemory code %x", code);
1094     if (code != 0) {
1095         *reasonP = "error initializing cache file";
1096         return -1;
1097     }
1098
1099 #ifdef AFS_AFSDB_ENV
1100 #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
1101     if (cm_InitDNS(cm_dnsEnabled) == -1)
1102         cm_dnsEnabled = 0;  /* init failed, so deactivate */
1103     afsi_log("cm_InitDNS %d", cm_dnsEnabled);
1104 #endif
1105 #endif
1106
1107     /* Set RX parameters before initializing RX */
1108     if ( rx_nojumbo ) {
1109         rx_SetNoJumbo();
1110         afsi_log("rx_SetNoJumbo successful");
1111     }
1112
1113     if ( rx_mtu != -1 ) {
1114         rx_SetMaxMTU(rx_mtu);
1115         afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
1116     }
1117
1118     /* initialize RX, and tell it to listen to port 7001, which is used for
1119      * callback RPC messages.
1120      */
1121     code = rx_Init(htons(7001));
1122     afsi_log("rx_Init code %x", code);
1123     if (code != 0) {
1124         *reasonP = "afsd: failed to init rx client on port 7001";
1125         return -1;
1126     }
1127
1128     /* create an unauthenticated service #1 for callbacks */
1129     nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1130     serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
1131                              RXAFSCB_ExecuteRequest);
1132     afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1133     if (serverp == NULL) {
1134         *reasonP = "unknown error";
1135         return -1;
1136     }
1137
1138     nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1139     serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
1140                              &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
1141     afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1142     if (serverp == NULL) {
1143         *reasonP = "unknown error";
1144         return -1;
1145     }
1146         
1147     /* start server threads, *not* donating this one to the pool */
1148     rx_StartServer(0);
1149     afsi_log("rx_StartServer");
1150
1151     if (rx_enable_peer_stats)
1152         rx_enablePeerRPCStats();
1153
1154     if (rx_enable_process_stats)
1155         rx_enableProcessRPCStats();
1156
1157     code = cm_GetRootCellName(rootCellName);
1158     afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s", 
1159               code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
1160     if (code != 0 && !cm_freelanceEnabled) 
1161     {
1162         *reasonP = "can't find root cell name in afsd.ini";
1163         return -1;
1164     }   
1165     else if (cm_freelanceEnabled)
1166         cm_data.rootCellp = NULL;
1167
1168     if (code == 0 && !cm_freelanceEnabled) 
1169     {
1170         cm_data.rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
1171         afsi_log("cm_GetCell addr %x", PtrToUlong(cm_data.rootCellp));
1172         if (cm_data.rootCellp == NULL) 
1173         {
1174             *reasonP = "can't find root cell in afsdcell.ini";
1175             return -1;
1176         }
1177     }
1178
1179 #ifdef AFS_FREELANCE_CLIENT
1180     if (cm_freelanceEnabled)
1181         cm_InitFreelance();
1182 #endif
1183
1184     /* Initialize the RPC server for session keys */
1185     RpcInit();
1186
1187 #if !defined(DJGPP)
1188     afsd_InitServerPreferences();
1189 #endif
1190     return 0;
1191 }
1192
1193 int afsd_InitDaemons(char **reasonP)
1194 {
1195     long code;
1196     cm_req_t req;
1197
1198     cm_InitReq(&req);
1199
1200     /* this should really be in an init daemon from here on down */
1201
1202     if (!cm_freelanceEnabled) {
1203         osi_Log0(afsd_logp, "Loading Root Volume from cell");
1204         code = cm_GetVolumeByName(cm_data.rootCellp, cm_rootVolumeName, cm_rootUserp,
1205                                   &req, CM_FLAG_CREATE, &cm_data.rootVolumep);
1206         afsi_log("cm_GetVolumeByName code %x root vol %x", code,
1207                  (code ? (cm_volume_t *)-1 : cm_data.rootVolumep));
1208         if (code != 0) {
1209             *reasonP = "can't find root volume in root cell";
1210             return -1;
1211         }
1212     }
1213
1214     /* compute the root fid */
1215     if (!cm_freelanceEnabled) {
1216         cm_data.rootFid.cell = cm_data.rootCellp->cellID;
1217         cm_data.rootFid.volume = cm_GetROVolumeID(cm_data.rootVolumep);
1218         cm_data.rootFid.vnode = 1;
1219         cm_data.rootFid.unique = 1;
1220     }
1221     else
1222         cm_FakeRootFid(&cm_data.rootFid);
1223         
1224     code = cm_GetSCache(&cm_data.rootFid, &cm_data.rootSCachep, cm_rootUserp, &req);
1225     afsi_log("cm_GetSCache code %x scache %x", code,
1226              (code ? (cm_scache_t *)-1 : cm_data.rootSCachep));
1227     if (code != 0) {
1228         *reasonP = "unknown error";
1229         return -1;
1230     }
1231
1232     cm_InitDaemon(numBkgD);
1233     afsi_log("cm_InitDaemon complete");
1234
1235     return 0;
1236 }
1237
1238 int afsd_InitSMB(char **reasonP, void *aMBfunc)
1239 {
1240     HKEY parmKey;
1241     DWORD dummyLen;
1242     DWORD dwValue;
1243     DWORD code;
1244
1245     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1246                          0, KEY_QUERY_VALUE, &parmKey);
1247     if (code == ERROR_SUCCESS) {
1248         dummyLen = sizeof(DWORD);
1249         code = RegQueryValueEx(parmKey, "StoreAnsiFilenames", NULL, NULL,
1250                                 (BYTE *) &dwValue, &dummyLen);
1251         if (code == ERROR_SUCCESS)
1252             smb_StoreAnsiFilenames = dwValue ? 1 : 0;
1253         RegCloseKey (parmKey);
1254     }
1255
1256     /* Do this last so that we don't handle requests before init is done.
1257      * Here we initialize the SMB listener.
1258      */
1259     smb_Init(afsd_logp, cm_NetbiosName, smb_UseV3, LANadapter, numSvThreads, aMBfunc);
1260     afsi_log("smb_Init complete");
1261
1262     return 0;
1263 }
1264
1265 #ifdef ReadOnly
1266 #undef ReadOnly
1267 #endif
1268
1269 #ifdef File
1270 #undef File
1271 #endif
1272
1273 #pragma pack( push, before_imagehlp, 8 )
1274 #include <imagehlp.h>
1275 #pragma pack( pop, before_imagehlp )
1276
1277 #define MAXNAMELEN 1024
1278
1279 void afsd_printStack(HANDLE hThread, CONTEXT *c)
1280 {
1281 #if defined(_X86_)
1282     HANDLE hProcess = GetCurrentProcess();
1283     int frameNum;
1284 #if defined(_AMD64_)
1285     DWORD64 offset;
1286 #elif defined(_X86_)
1287     DWORD offset;
1288 #endif
1289     DWORD symOptions;
1290     char functionName[MAXNAMELEN];
1291   
1292     IMAGEHLP_MODULE Module;
1293     IMAGEHLP_LINE Line;
1294   
1295     STACKFRAME s;
1296     IMAGEHLP_SYMBOL *pSym;
1297   
1298     afsi_log_useTimestamp = 0;
1299   
1300     pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
1301   
1302     memset( &s, '\0', sizeof s );
1303     if (!SymInitialize(hProcess, NULL, 1) )
1304     {
1305         afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
1306       
1307         SymCleanup( hProcess );
1308         GlobalFree(pSym);
1309       
1310         return;
1311     }
1312   
1313     symOptions = SymGetOptions();
1314     symOptions |= SYMOPT_LOAD_LINES;
1315     symOptions &= ~SYMOPT_UNDNAME;
1316     SymSetOptions( symOptions );
1317   
1318     /*
1319      * init STACKFRAME for first call
1320      * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
1321      * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
1322      * and good riddance.
1323      */
1324 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
1325 #error The STACKFRAME initialization in afsd_printStack() for this platform
1326 #error must be properly configured
1327 #elif defined(_AMD64_)
1328     s.AddrPC.Offset = 0;
1329     s.AddrPC.Mode = AddrModeFlat;
1330     s.AddrFrame.Offset = 0;
1331     s.AddrFrame.Mode = AddrModeFlat;
1332 #else
1333     s.AddrPC.Offset = c->Eip;
1334     s.AddrPC.Mode = AddrModeFlat;
1335     s.AddrFrame.Offset = c->Ebp;
1336     s.AddrFrame.Mode = AddrModeFlat;
1337 #endif
1338
1339     memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
1340     pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
1341     pSym->MaxNameLength = MAXNAMELEN;
1342   
1343     memset( &Line, '\0', sizeof Line );
1344     Line.SizeOfStruct = sizeof Line;
1345   
1346     memset( &Module, '\0', sizeof Module );
1347     Module.SizeOfStruct = sizeof Module;
1348   
1349     offset = 0;
1350   
1351     afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
1352   
1353     for ( frameNum = 0; ; ++ frameNum )
1354     {
1355         /*
1356          * get next stack frame (StackWalk(), SymFunctionTableAccess(), 
1357          * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
1358          * ERROR_NOACCESS (998), you can assume that either you are done, or
1359          * that the stack is so hosed that the next deeper frame could not be
1360          * found.
1361          */
1362         if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c, 
1363                           NULL, SymFunctionTableAccess, SymGetModuleBase, 
1364                           NULL ) )
1365             break;
1366       
1367         /* display its contents */
1368         afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
1369                  frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
1370                  s.AddrPC.Offset, s.AddrReturn.Offset,
1371                  s.AddrFrame.Offset, s.AddrStack.Offset );
1372       
1373         if ( s.AddrPC.Offset == 0 )
1374         {
1375             afsi_log("(-nosymbols- PC == 0)" );
1376         }
1377         else
1378         { 
1379             /* show procedure info from a valid PC */
1380             if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
1381             {
1382                 if ( GetLastError() != ERROR_INVALID_ADDRESS )
1383                 {
1384                     afsi_log("SymGetSymFromAddr(): errno = %lu", 
1385                              GetLastError());
1386                 }
1387             }
1388             else
1389             {
1390                 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN, 
1391                                      UNDNAME_NAME_ONLY);
1392                 afsi_log("%s", functionName );
1393
1394                 if ( offset != 0 )
1395                 {
1396                     afsi_log(" %+ld bytes", (long) offset);
1397                 }
1398             }
1399
1400             if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
1401             {
1402                 if (GetLastError() != ERROR_INVALID_ADDRESS)
1403                 {
1404                     afsi_log("Error: SymGetLineFromAddr(): errno = %lu", 
1405                              GetLastError());
1406                 }
1407             }
1408             else
1409             {
1410                 afsi_log("    Line: %s(%lu) %+ld bytes", Line.FileName, 
1411                          Line.LineNumber, offset);
1412             }
1413         }
1414       
1415         /* no return address means no deeper stackframe */
1416         if (s.AddrReturn.Offset == 0)
1417         {
1418             SetLastError(0);
1419             break;
1420         }
1421     }
1422   
1423     if (GetLastError() != 0)
1424     {
1425         afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
1426     }
1427   
1428     SymCleanup(hProcess);
1429     GlobalFree(pSym);
1430 #endif /* _X86_ */
1431 }
1432
1433 #ifdef _DEBUG
1434 static DWORD *afsd_crtDbgBreakCurrent = NULL;
1435 static DWORD afsd_crtDbgBreaks[256];
1436 #endif
1437
1438 static EFaultRepRetVal (WINAPI *pReportFault)(LPEXCEPTION_POINTERS pep, DWORD dwMode) = NULL;
1439 static BOOL (WINAPI *pMiniDumpWriteDump)(HANDLE hProcess,DWORD ProcessId,HANDLE hFile,
1440                                   MINIDUMP_TYPE DumpType,
1441                                   PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
1442                                   PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
1443                                   PMINIDUMP_CALLBACK_INFORMATION CallbackParam) = NULL;
1444
1445
1446 static HANDLE
1447 OpenDumpFile(void)
1448 {
1449     char wd[256];
1450     DWORD code;
1451
1452     code = GetEnvironmentVariable("TEMP", wd, sizeof(wd));
1453     if ( code == 0 || code > sizeof(wd) )
1454     {
1455         if (!GetWindowsDirectory(wd, sizeof(wd)))
1456             return NULL;
1457     }
1458     StringCbCatA(wd, sizeof(wd), "\\afsd.dmp");
1459     return CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1460                             CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
1461 }
1462
1463 void 
1464 GenerateMiniDump(PEXCEPTION_POINTERS ep)
1465 {
1466     if (ep == NULL) 
1467     {
1468         // Generate exception to get proper context in dump
1469         __try 
1470         {
1471             RaiseException(DBG_CONTINUE, 0, 0, NULL);
1472         } 
1473         __except(GenerateMiniDump(GetExceptionInformation()), EXCEPTION_CONTINUE_EXECUTION) 
1474         {
1475         }
1476     } 
1477     else
1478     {
1479         MINIDUMP_EXCEPTION_INFORMATION eInfo;
1480         HANDLE hFile = NULL;
1481         HMODULE hDbgHelp = NULL;
1482
1483         hDbgHelp = LoadLibrary("Dbghelp.dll");
1484         if ( hDbgHelp == NULL )
1485             return;
1486
1487         (FARPROC) pMiniDumpWriteDump = GetProcAddress(hDbgHelp, "MiniDumpWriteDump");
1488         if ( pMiniDumpWriteDump == NULL ) {
1489             FreeLibrary(hDbgHelp);
1490             return;
1491         }
1492
1493         hFile = OpenDumpFile();
1494
1495         if ( hFile ) {
1496             HKEY parmKey;
1497             DWORD dummyLen;
1498             DWORD dwValue;
1499             DWORD code;
1500             DWORD dwMiniDumpType = MiniDumpNormal;
1501
1502             code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1503                                  0, KEY_QUERY_VALUE, &parmKey);
1504             if (code == ERROR_SUCCESS) {
1505                 dummyLen = sizeof(DWORD);
1506                 code = RegQueryValueEx(parmKey, "MiniDumpType", NULL, NULL,
1507                                         (BYTE *) &dwValue, &dummyLen);
1508                 if (code == ERROR_SUCCESS)
1509                     dwMiniDumpType = dwValue ? 1 : 0;
1510                 RegCloseKey (parmKey);
1511             }
1512
1513             eInfo.ThreadId = GetCurrentThreadId();
1514             eInfo.ExceptionPointers = ep;
1515             eInfo.ClientPointers = FALSE;
1516
1517             pMiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(),
1518                                 hFile, dwMiniDumpType, ep ? &eInfo : NULL,
1519                                 NULL, NULL);
1520
1521             CloseHandle(hFile);
1522         }
1523         FreeLibrary(hDbgHelp);
1524     }
1525 }
1526
1527 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
1528 {
1529     CONTEXT context;
1530 #ifdef _DEBUG  
1531     BOOL allocRequestBrk = FALSE;
1532 #endif 
1533     HMODULE hLib = NULL;
1534   
1535     afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n", 
1536              ep->ExceptionRecord->ExceptionCode, 
1537              ep->ExceptionRecord->ExceptionAddress);
1538            
1539 #ifdef _DEBUG
1540     if (afsd_crtDbgBreakCurrent && 
1541         *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
1542     { 
1543         allocRequestBrk = TRUE;
1544         afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
1545     }
1546 #endif
1547            
1548     /* save context if we want to print the stack information */
1549     context = *ep->ContextRecord;
1550            
1551     afsd_printStack(GetCurrentThread(), &context);
1552
1553     GenerateMiniDump(ep);
1554
1555     hLib = LoadLibrary("Faultrep.dll");
1556     if ( hLib ) {
1557         (FARPROC) pReportFault = GetProcAddress(hLib, "ReportFault");
1558         if ( pReportFault )
1559             pReportFault(ep, 0);
1560         FreeLibrary(hLib);
1561     }
1562
1563     if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
1564     {
1565         afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
1566     
1567 #ifdef _DEBUG
1568         if (allocRequestBrk)
1569         {
1570             afsd_crtDbgBreakCurrent++;
1571             _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
1572         }
1573 #endif         
1574 #if defined(_X86)    
1575         ep->ContextRecord->Eip++;
1576 #endif
1577         return EXCEPTION_CONTINUE_EXECUTION;
1578     }
1579     else
1580     {
1581         return EXCEPTION_CONTINUE_SEARCH;
1582     }
1583 }
1584   
1585 void afsd_SetUnhandledExceptionFilter()
1586 {
1587     SetUnhandledExceptionFilter(afsd_ExceptionFilter);
1588 }
1589   
1590 #ifdef _DEBUG
1591 void afsd_DbgBreakAllocInit()
1592 {
1593     memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
1594     afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
1595 }
1596   
1597 void afsd_DbgBreakAdd(DWORD requestNumber)
1598 {
1599     int i;
1600     for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
1601         {
1602         if (afsd_crtDbgBreaks[i] == -1)
1603             {
1604             break;
1605             }
1606         }
1607     afsd_crtDbgBreaks[i] = requestNumber;
1608
1609     _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);
1610 }
1611 #endif