windows-64-bit-type-safety-20051105
[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         *reasonP = "unknown error";
579         return -1;
580     }
581
582     /* who are we ? */
583     gethostname(cm_HostName, sizeof(cm_HostName));
584     afsi_log("gethostname %s", cm_HostName);
585     thp = gethostbyname(cm_HostName);
586     memcpy(&cm_HostAddr, thp->h_addr_list[0], 4);
587
588     /* seed random number generator */
589     srand(ntohl(cm_HostAddr));
590
591     /* Look up configuration parameters in Registry */
592     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
593                          0, KEY_QUERY_VALUE, &parmKey);
594     if (code != ERROR_SUCCESS) {
595         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
596                        | FORMAT_MESSAGE_ALLOCATE_BUFFER,
597                        NULL, code, 0, (LPTSTR)&msgBuf, 0, NULL);
598         StringCbPrintfA(buf, sizeof(buf),
599                          "Failure in configuration while opening Registry: %s",
600                          msgBuf);
601         osi_panic(buf, __FILE__, __LINE__);
602     }
603
604     dummyLen = sizeof(maxcpus);
605     code = RegQueryValueEx(parmKey, "MaxCPUs", NULL, NULL,
606                             (BYTE *) &maxcpus, &dummyLen);
607     if (code == ERROR_SUCCESS) {
608         HANDLE hProcess;
609         DWORD_PTR processAffinityMask, systemAffinityMask;
610
611         hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION,
612                                FALSE, GetCurrentProcessId());
613         if ( hProcess != NULL &&
614              GetProcessAffinityMask(hProcess, &processAffinityMask, &systemAffinityMask) )
615         {
616             int i, n, bits;
617             DWORD_PTR mask, newAffinityMask;
618
619 #if defined(_WIN64)
620             bits = 64;
621 #else
622             bits = 32;
623 #endif
624             for ( i=0, n=0, mask=1, newAffinityMask=0; i<bits && n<maxcpus; i++ ) {
625                 if ( processAffinityMask & mask ) {
626                     newAffinityMask |= mask;
627                     n++;
628                 }
629                 mask *= 2;
630             }
631
632             SetProcessAffinityMask(hProcess, newAffinityMask);
633             CloseHandle(hProcess);
634             afsi_log("CPU Restrictions set to %d cpu(s); %d cpu(s) available", maxcpus, n);
635         } else {
636             afsi_log("CPU Restrictions set to %d cpu(s); unable to access process information", maxcpus);
637         }
638     }
639
640     dummyLen = sizeof(TraceOption);
641     code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
642                             (BYTE *) &TraceOption, &dummyLen);
643     afsi_log("Trace Options = %lX", TraceOption);
644
645     dummyLen = sizeof(traceBufSize);
646     code = RegQueryValueEx(parmKey, "TraceBufferSize", NULL, NULL,
647                             (BYTE *) &traceBufSize, &dummyLen);
648     if (code == ERROR_SUCCESS)
649         afsi_log("Trace Buffer size %d", traceBufSize);
650     else {
651         traceBufSize = CM_CONFIGDEFAULT_TRACEBUFSIZE;
652         afsi_log("Default trace buffer size %d", traceBufSize);
653     }
654
655     /* setup and enable debug log */
656     afsd_logp = osi_LogCreate("afsd", traceBufSize);
657     afsi_log("osi_LogCreate log addr %x", PtrToUlong(afsd_logp));
658     if ((TraceOption & 0x8)
659 #ifdef DEBUG
660          || 1
661 #endif
662          ) {
663         osi_LogEnable(afsd_logp);
664     }
665     logReady = 1;
666
667     osi_Log0(afsd_logp, "Log init");
668
669     dummyLen = sizeof(cacheSize);
670     code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
671                             (BYTE *) &cacheSize, &dummyLen);
672     if (code == ERROR_SUCCESS)
673         afsi_log("Cache size %d", cacheSize);
674     else {
675         cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
676         afsi_log("Default cache size %d", cacheSize);
677     }
678
679     dummyLen = sizeof(logChunkSize);
680     code = RegQueryValueEx(parmKey, "ChunkSize", NULL, NULL,
681                             (BYTE *) &logChunkSize, &dummyLen);
682     if (code == ERROR_SUCCESS) {
683         if (logChunkSize < 12 || logChunkSize > 30) {
684             afsi_log("Invalid chunk size %d, using default",
685                       logChunkSize);
686             logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
687         }
688         afsi_log("Chunk size %d", logChunkSize);
689     } else {
690         logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
691         afsi_log("Default chunk size %d", logChunkSize);
692     }
693     cm_logChunkSize = logChunkSize;
694     cm_chunkSize = 1 << logChunkSize;
695
696     dummyLen = sizeof(numBkgD);
697     code = RegQueryValueEx(parmKey, "Daemons", NULL, NULL,
698                             (BYTE *) &numBkgD, &dummyLen);
699     if (code == ERROR_SUCCESS)
700         afsi_log("%d background daemons", numBkgD);
701     else {
702         numBkgD = CM_CONFIGDEFAULT_DAEMONS;
703         afsi_log("Defaulting to %d background daemons", numBkgD);
704     }
705
706     dummyLen = sizeof(numSvThreads);
707     code = RegQueryValueEx(parmKey, "ServerThreads", NULL, NULL,
708                             (BYTE *) &numSvThreads, &dummyLen);
709     if (code == ERROR_SUCCESS)
710         afsi_log("%d server threads", numSvThreads);
711     else {
712         numSvThreads = CM_CONFIGDEFAULT_SVTHREADS;
713         afsi_log("Defaulting to %d server threads", numSvThreads);
714     }
715
716     dummyLen = sizeof(stats);
717     code = RegQueryValueEx(parmKey, "Stats", NULL, NULL,
718                             (BYTE *) &stats, &dummyLen);
719     if (code == ERROR_SUCCESS)
720         afsi_log("Status cache size %d", stats);
721     else {
722         stats = CM_CONFIGDEFAULT_STATS;
723         afsi_log("Default status cache size %d", stats);
724     }
725
726     dummyLen = sizeof(ltt);
727     code = RegQueryValueEx(parmKey, "LogoffTokenTransfer", NULL, NULL,
728                             (BYTE *) &ltt, &dummyLen);
729     if (code == ERROR_SUCCESS)
730         afsi_log("Logoff token transfer %s",  (ltt ? "on" : "off"));
731     else {
732         ltt = 1;
733         afsi_log("Logoff token transfer on by default");
734     }
735     smb_LogoffTokenTransfer = ltt;
736     afsi_log("Logoff token transfer is currently ignored");
737
738     if (ltt) {
739         dummyLen = sizeof(ltto);
740         code = RegQueryValueEx(parmKey, "LogoffTokenTransferTimeout",
741                                 NULL, NULL, (BYTE *) &ltto, &dummyLen);
742         if (code == ERROR_SUCCESS)
743             afsi_log("Logoff token tranfer timeout %d seconds", ltto);
744         else {
745             ltto = 10;
746             afsi_log("Default logoff token transfer timeout 10 seconds");
747         }
748     } else {
749         ltto = 0;
750     }   
751     smb_LogoffTransferTimeout = ltto;
752     afsi_log("Default logoff token is currently ignored");
753
754     dummyLen = sizeof(cm_rootVolumeName);
755     code = RegQueryValueEx(parmKey, "RootVolume", NULL, NULL,
756                             cm_rootVolumeName, &dummyLen);
757     if (code == ERROR_SUCCESS)
758         afsi_log("Root volume %s", cm_rootVolumeName);
759     else {
760         StringCbCopyA(cm_rootVolumeName, sizeof(cm_rootVolumeName), "root.afs");
761         afsi_log("Default root volume name root.afs");
762     }
763
764     cm_mountRootLen = sizeof(cm_mountRoot);
765     code = RegQueryValueEx(parmKey, "MountRoot", NULL, NULL,
766                             cm_mountRoot, &cm_mountRootLen);
767     if (code == ERROR_SUCCESS) {
768         afsi_log("Mount root %s", cm_mountRoot);
769         cm_mountRootLen = (DWORD)strlen(cm_mountRoot);
770     } else {
771         StringCbCopyA(cm_mountRoot, sizeof(cm_mountRoot), "/afs");
772         cm_mountRootLen = 4;
773         /* Don't log */
774     }
775
776     dummyLen = sizeof(buf);
777     code = RegQueryValueEx(parmKey, "CachePath", NULL, &regType,
778                             buf, &dummyLen);
779     if (code == ERROR_SUCCESS && buf[0]) {
780         if (regType == REG_EXPAND_SZ) {
781             dummyLen = ExpandEnvironmentStrings(buf, cm_CachePath, sizeof(cm_CachePath));
782             if (dummyLen > sizeof(cm_CachePath)) {
783                 afsi_log("Cache path [%s] longer than %d after expanding env strings", buf, sizeof(cm_CachePath));
784                 osi_panic("CachePath too long", __FILE__, __LINE__);
785             }
786         } else {
787             StringCbCopyA(cm_CachePath, sizeof(cm_CachePath), buf);
788         }
789         afsi_log("Cache path %s", cm_CachePath);
790     } else {
791         dummyLen = ExpandEnvironmentStrings("%TEMP%\\AFSCache", cm_CachePath, sizeof(cm_CachePath));
792         if (dummyLen > sizeof(cm_CachePath)) {
793             afsi_log("Cache path [%%TEMP%%\\AFSCache] longer than %d after expanding env strings", 
794                      sizeof(cm_CachePath));
795             osi_panic("CachePath too long", __FILE__, __LINE__);
796         }
797         afsi_log("Default cache path %s", cm_CachePath);
798     }
799
800     dummyLen = sizeof(virtualCache);
801     code = RegQueryValueEx(parmKey, "NonPersistentCaching", NULL, NULL,
802                             (LPBYTE)&virtualCache, &dummyLen);
803     afsi_log("Cache type is %s", (virtualCache?"VIRTUAL":"FILE"));
804
805     if (!virtualCache) {
806         dummyLen = sizeof(cm_ValidateCache);
807         code = RegQueryValueEx(parmKey, "ValidateCache", NULL, NULL,
808                                (LPBYTE)&cm_ValidateCache, &dummyLen);
809         if ( cm_ValidateCache < 0 || cm_ValidateCache > 2 )
810             cm_ValidateCache = 1;
811         switch (cm_ValidateCache) {
812         case 0:
813             afsi_log("Cache Validation disabled");
814             break;
815         case 1:
816             afsi_log("Cache Validation on Startup");
817             break;
818         case 2:
819             afsi_log("Cache Validation on Startup and Shutdown");
820             break;
821         }
822     }
823
824     dummyLen = sizeof(traceOnPanic);
825     code = RegQueryValueEx(parmKey, "TrapOnPanic", NULL, NULL,
826                             (BYTE *) &traceOnPanic, &dummyLen);
827     if (code != ERROR_SUCCESS)
828         traceOnPanic = 1;              /* log */
829     afsi_log("Set to %s on panic", traceOnPanic ? "trap" : "not trap");
830
831     dummyLen = sizeof(reportSessionStartups);
832     code = RegQueryValueEx(parmKey, "ReportSessionStartups", NULL, NULL,
833                             (BYTE *) &reportSessionStartups, &dummyLen);
834     if (code == ERROR_SUCCESS)
835         afsi_log("Session startups %s be recorded in the Event Log",
836                   reportSessionStartups ? "will" : "will not");
837     else {
838         reportSessionStartups = 0;
839         /* Don't log */
840     }
841
842     for ( i=0; i < MAXNUMSYSNAMES; i++ ) {
843         cm_sysNameList[i] = osi_Alloc(MAXSYSNAME);
844         cm_sysNameList[i][0] = '\0';
845     }
846     cm_sysName = cm_sysNameList[0];
847
848     dummyLen = sizeof(buf);
849     code = RegQueryValueEx(parmKey, "SysName", NULL, NULL, buf, &dummyLen);
850     if (code != ERROR_SUCCESS || !buf[0]) {
851 #if defined(_IA64_)
852         StringCbCopyA(buf, sizeof(buf), "ia64_win64");
853 #elif defined(_AMD64)
854         StringCbCopyA(buf, sizeof(buf), "amd64_win64");
855 #else /* assume x86 32-bit */
856         StringCbCopyA(buf, sizeof(buf), "x86_win32 i386_w2k i386_nt40");
857 #endif
858     }
859     afsi_log("Sys name %s", buf); 
860
861     /* breakup buf into individual search string entries */
862     for (p = q = buf; p < buf + dummyLen; p++)
863     {
864         if (*p == '\0' || isspace(*p)) {
865             memcpy(cm_sysNameList[cm_sysNameCount],q,p-q);
866             cm_sysNameList[cm_sysNameCount][p-q] = '\0';
867             cm_sysNameCount++;
868
869             do {
870                 if (*p == '\0')
871                     goto done_sysname;
872                 p++;
873             } while (*p == '\0' || isspace(*p));
874             q = p;
875             p--;
876         }
877     }
878   done_sysname:
879     StringCbCopyA(cm_sysName, MAXSYSNAME, cm_sysNameList[0]);
880
881     dummyLen = sizeof(cryptall);
882     code = RegQueryValueEx(parmKey, "SecurityLevel", NULL, NULL,
883                             (BYTE *) &cryptall, &dummyLen);
884     if (code == ERROR_SUCCESS) {
885         afsi_log("SecurityLevel is %s", cryptall?"crypt":"clear");
886     } else {
887         cryptall = 0;
888         afsi_log("Default SecurityLevel is clear");
889     }
890
891 #ifdef AFS_AFSDB_ENV
892     dummyLen = sizeof(cm_dnsEnabled);
893     code = RegQueryValueEx(parmKey, "UseDNS", NULL, NULL,
894                             (BYTE *) &cm_dnsEnabled, &dummyLen);
895     if (code == ERROR_SUCCESS) {
896         afsi_log("DNS %s be used to find AFS cell servers",
897                   cm_dnsEnabled ? "will" : "will not");
898     }       
899     else {
900         cm_dnsEnabled = 1;   /* default on */
901         afsi_log("Default to use DNS to find AFS cell servers");
902     }
903 #else /* AFS_AFSDB_ENV */
904     afsi_log("AFS not built with DNS support to find AFS cell servers");
905 #endif /* AFS_AFSDB_ENV */
906
907 #ifdef AFS_FREELANCE_CLIENT
908     dummyLen = sizeof(cm_freelanceEnabled);
909     code = RegQueryValueEx(parmKey, "FreelanceClient", NULL, NULL,
910                             (BYTE *) &cm_freelanceEnabled, &dummyLen);
911     if (code == ERROR_SUCCESS) {
912         afsi_log("Freelance client feature %s activated",
913                   cm_freelanceEnabled ? "is" : "is not");
914     }       
915     else {
916         cm_freelanceEnabled = 0;  /* default off */
917     }
918 #endif /* AFS_FREELANCE_CLIENT */
919
920 #ifdef COMMENT
921     /* The netbios name is looked up in lana_GetUNCServerNameEx */
922     dummyLen = sizeof(buf);
923     code = RegQueryValueEx(parmKey, "NetbiosName", NULL, NULL,
924                            (BYTE *) &buf, &dummyLen);
925     if (code == ERROR_SUCCESS) {
926         DWORD len = ExpandEnvironmentStrings(buf, cm_NetbiosName, MAX_NB_NAME_LENGTH);
927         if ( len > 0 && len <= MAX_NB_NAME_LENGTH ) {
928             afsi_log("Explicit NetBios name is used %s", cm_NetbiosName);
929         } else {
930             afsi_log("Unable to Expand Explicit NetBios name: %s", buf);
931             cm_NetbiosName[0] = 0;  /* turn it off */
932         }
933     }
934     else {
935         cm_NetbiosName[0] = 0;   /* default off */
936     }
937 #endif
938
939     dummyLen = sizeof(smb_hideDotFiles);
940     code = RegQueryValueEx(parmKey, "HideDotFiles", NULL, NULL,
941                            (BYTE *) &smb_hideDotFiles, &dummyLen);
942     if (code != ERROR_SUCCESS) {
943         smb_hideDotFiles = 1; /* default on */
944     }
945     afsi_log("Dot files/dirs will %sbe marked hidden",
946               smb_hideDotFiles ? "" : "not ");
947
948     dummyLen = sizeof(smb_maxMpxRequests);
949     code = RegQueryValueEx(parmKey, "MaxMpxRequests", NULL, NULL,
950                            (BYTE *) &smb_maxMpxRequests, &dummyLen);
951     if (code != ERROR_SUCCESS) {
952         smb_maxMpxRequests = 50;
953     }
954     afsi_log("Maximum number of multiplexed sessions is %d", smb_maxMpxRequests);
955
956     dummyLen = sizeof(smb_maxVCPerServer);
957     code = RegQueryValueEx(parmKey, "MaxVCPerServer", NULL, NULL,
958                            (BYTE *) &smb_maxVCPerServer, &dummyLen);
959     if (code != ERROR_SUCCESS) {
960         smb_maxVCPerServer = 100;
961     }
962     afsi_log("Maximum number of VCs per server is %d", smb_maxVCPerServer);
963
964     dummyLen = sizeof(smb_authType);
965     code = RegQueryValueEx(parmKey, "SMBAuthType", NULL, NULL,
966                             (BYTE *) &smb_authType, &dummyLen);
967
968     if (code != ERROR_SUCCESS || 
969          (smb_authType != SMB_AUTH_EXTENDED && smb_authType != SMB_AUTH_NTLM && smb_authType != SMB_AUTH_NONE)) {
970         smb_authType = SMB_AUTH_EXTENDED; /* default is to use extended authentication */
971     }
972     afsi_log("SMB authentication type is %s", ((smb_authType == SMB_AUTH_NONE)?"NONE":((smb_authType == SMB_AUTH_EXTENDED)?"EXTENDED":"NTLM")));
973
974     dummyLen = sizeof(rx_nojumbo);
975     code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
976                            (BYTE *) &rx_nojumbo, &dummyLen);
977     if (code != ERROR_SUCCESS) {
978         rx_nojumbo = 0;
979     }
980     if (rx_nojumbo)
981         afsi_log("RX Jumbograms are disabled");
982
983     dummyLen = sizeof(rx_mtu);
984     code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
985                            (BYTE *) &rx_mtu, &dummyLen);
986     if (code != ERROR_SUCCESS || !rx_mtu) {
987         rx_mtu = -1;
988     }
989     if (rx_mtu != -1)
990         afsi_log("RX maximum MTU is %d", rx_mtu);
991
992     dummyLen = sizeof(rx_enable_peer_stats);
993     code = RegQueryValueEx(parmKey, "RxEnablePeerStats", NULL, NULL,
994                            (BYTE *) &rx_enable_peer_stats, &dummyLen);
995     if (code != ERROR_SUCCESS) {
996         rx_enable_peer_stats = 0;
997     }
998     if (rx_enable_peer_stats)
999         afsi_log("RX Peer Statistics gathering is enabled");
1000
1001     dummyLen = sizeof(rx_enable_process_stats);
1002     code = RegQueryValueEx(parmKey, "RxEnableProcessStats", NULL, NULL,
1003                            (BYTE *) &rx_enable_process_stats, &dummyLen);
1004     if (code != ERROR_SUCCESS) {
1005         rx_enable_process_stats = 0;
1006     }
1007     if (rx_enable_process_stats)
1008         afsi_log("RX Process Statistics gathering is enabled");
1009
1010     dummyLen = sizeof(ConnDeadtimeout);
1011     code = RegQueryValueEx(parmKey, "ConnDeadTimeout", NULL, NULL,
1012                            (BYTE *) &ConnDeadtimeout, &dummyLen);
1013     afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
1014
1015     dummyLen = sizeof(HardDeadtimeout);
1016     code = RegQueryValueEx(parmKey, "HardDeadTimeout", NULL, NULL,
1017                            (BYTE *) &HardDeadtimeout, &dummyLen);
1018     afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
1019
1020     RegCloseKey (parmKey);
1021
1022     /* Call lanahelper to get Netbios name, lan adapter number and gateway flag */
1023     if (SUCCEEDED(code = lana_GetUncServerNameEx(cm_NetbiosName, &lanaNum, &isGateway, LANA_NETBIOS_NAME_FULL))) {
1024         LANadapter = (lanaNum == LANA_INVALID)? -1: lanaNum;
1025
1026         if (LANadapter != -1)
1027             afsi_log("LAN adapter number %d", LANadapter);
1028         else
1029             afsi_log("LAN adapter number not determined");
1030
1031         if (isGateway)
1032             afsi_log("Set for gateway service");
1033
1034         afsi_log("Using >%s< as SMB server name", cm_NetbiosName);
1035     } else {
1036         /* something went horribly wrong.  We can't proceed without a netbios name */
1037         StringCbPrintfA(buf,sizeof(buf),"Netbios name could not be determined: %li", code);
1038         osi_panic(buf, __FILE__, __LINE__);
1039     }
1040
1041     cacheBlocks = ((afs_uint64)cacheSize * 1024) / CM_CONFIGDEFAULT_BLOCKSIZE;
1042         
1043     /* get network related info */
1044     cm_noIPAddr = CM_MAXINTERFACE_ADDR;
1045     code = syscfg_GetIFInfo(&cm_noIPAddr,
1046                              cm_IPAddr, cm_SubnetMask,
1047                              cm_NetMtu, cm_NetFlags);
1048
1049     if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
1050         afsi_log("syscfg_GetIFInfo error code %d", code);
1051     else
1052         afsi_log("First Network address %x SubnetMask %x",
1053                   cm_IPAddr[0], cm_SubnetMask[0]);
1054
1055     /*
1056      * Save client configuration for GetCacheConfig requests
1057      */
1058     cm_initParams.nChunkFiles = 0;
1059     cm_initParams.nStatCaches = stats;
1060     cm_initParams.nDataCaches = (afs_uint32)(cacheBlocks > 0xFFFFFFFF ? 0xFFFFFFFF : cacheBlocks);
1061     cm_initParams.nVolumeCaches = stats/2;
1062     cm_initParams.firstChunkSize = cm_chunkSize;
1063     cm_initParams.otherChunkSize = cm_chunkSize;
1064     cm_initParams.cacheSize = cacheSize;
1065     cm_initParams.setTime = 0;
1066     cm_initParams.memCache = 1;
1067
1068     /* Ensure the AFS Netbios Name is registered to allow loopback access */
1069     configureBackConnectionHostNames();
1070
1071     /* init user daemon, and other packages */
1072     cm_InitUser();
1073
1074     cm_InitConn();
1075
1076     cm_InitServer();
1077         
1078     cm_InitIoctl();
1079         
1080     smb_InitIoctl();
1081         
1082     cm_InitCallback();
1083         
1084     code = cm_InitMappedMemory(virtualCache, cm_CachePath, stats, cm_chunkSize, cacheBlocks);
1085     afsi_log("cm_InitMappedMemory code %x", code);
1086     if (code != 0) {
1087         *reasonP = "error initializing cache file";
1088         return -1;
1089     }
1090
1091 #ifdef AFS_AFSDB_ENV
1092 #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
1093     if (cm_InitDNS(cm_dnsEnabled) == -1)
1094         cm_dnsEnabled = 0;  /* init failed, so deactivate */
1095     afsi_log("cm_InitDNS %d", cm_dnsEnabled);
1096 #endif
1097 #endif
1098
1099     /* Set RX parameters before initializing RX */
1100     if ( rx_nojumbo ) {
1101         rx_SetNoJumbo();
1102         afsi_log("rx_SetNoJumbo successful");
1103     }
1104
1105     if ( rx_mtu != -1 ) {
1106         rx_SetMaxMTU(rx_mtu);
1107         afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
1108     }
1109
1110     /* initialize RX, and tell it to listen to port 7001, which is used for
1111      * callback RPC messages.
1112      */
1113     code = rx_Init(htons(7001));
1114     afsi_log("rx_Init code %x", code);
1115     if (code != 0) {
1116         *reasonP = "afsd: failed to init rx client on port 7001";
1117         return -1;
1118     }
1119
1120     /* create an unauthenticated service #1 for callbacks */
1121     nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1122     serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
1123                              RXAFSCB_ExecuteRequest);
1124     afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1125     if (serverp == NULL) {
1126         *reasonP = "unknown error";
1127         return -1;
1128     }
1129
1130     nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1131     serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
1132                              &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
1133     afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1134     if (serverp == NULL) {
1135         *reasonP = "unknown error";
1136         return -1;
1137     }
1138         
1139     /* start server threads, *not* donating this one to the pool */
1140     rx_StartServer(0);
1141     afsi_log("rx_StartServer");
1142
1143     if (rx_enable_peer_stats)
1144         rx_enablePeerRPCStats();
1145
1146     if (rx_enable_process_stats)
1147         rx_enableProcessRPCStats();
1148
1149     code = cm_GetRootCellName(rootCellName);
1150     afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s", 
1151               code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
1152     if (code != 0 && !cm_freelanceEnabled) 
1153     {
1154         *reasonP = "can't find root cell name in afsd.ini";
1155         return -1;
1156     }   
1157     else if (cm_freelanceEnabled)
1158         cm_data.rootCellp = NULL;
1159
1160     if (code == 0 && !cm_freelanceEnabled) 
1161     {
1162         cm_data.rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
1163         afsi_log("cm_GetCell addr %x", PtrToUlong(cm_data.rootCellp));
1164         if (cm_data.rootCellp == NULL) 
1165         {
1166             *reasonP = "can't find root cell in afsdcell.ini";
1167             return -1;
1168         }
1169     }
1170
1171 #ifdef AFS_FREELANCE_CLIENT
1172     if (cm_freelanceEnabled)
1173         cm_InitFreelance();
1174 #endif
1175
1176     /* Initialize the RPC server for session keys */
1177     RpcInit();
1178
1179 #if !defined(DJGPP)
1180     afsd_InitServerPreferences();
1181 #endif
1182     return 0;
1183 }
1184
1185 int afsd_InitDaemons(char **reasonP)
1186 {
1187     long code;
1188     cm_req_t req;
1189
1190     cm_InitReq(&req);
1191
1192     /* this should really be in an init daemon from here on down */
1193
1194     if (!cm_freelanceEnabled) {
1195         osi_Log0(afsd_logp, "Loading Root Volume from cell");
1196         code = cm_GetVolumeByName(cm_data.rootCellp, cm_rootVolumeName, cm_rootUserp,
1197                                   &req, CM_FLAG_CREATE, &cm_data.rootVolumep);
1198         afsi_log("cm_GetVolumeByName code %x root vol %x", code,
1199                  (code ? (cm_volume_t *)-1 : cm_data.rootVolumep));
1200         if (code != 0) {
1201             *reasonP = "can't find root volume in root cell";
1202             return -1;
1203         }
1204     }
1205
1206     /* compute the root fid */
1207     if (!cm_freelanceEnabled) {
1208         cm_data.rootFid.cell = cm_data.rootCellp->cellID;
1209         cm_data.rootFid.volume = cm_GetROVolumeID(cm_data.rootVolumep);
1210         cm_data.rootFid.vnode = 1;
1211         cm_data.rootFid.unique = 1;
1212     }
1213     else
1214         cm_FakeRootFid(&cm_data.rootFid);
1215         
1216     code = cm_GetSCache(&cm_data.rootFid, &cm_data.rootSCachep, cm_rootUserp, &req);
1217     afsi_log("cm_GetSCache code %x scache %x", code,
1218              (code ? (cm_scache_t *)-1 : cm_data.rootSCachep));
1219     if (code != 0) {
1220         *reasonP = "unknown error";
1221         return -1;
1222     }
1223
1224     cm_InitDaemon(numBkgD);
1225     afsi_log("cm_InitDaemon complete");
1226
1227     return 0;
1228 }
1229
1230 int afsd_InitSMB(char **reasonP, void *aMBfunc)
1231 {
1232     HKEY parmKey;
1233     DWORD dummyLen;
1234     DWORD dwValue;
1235     DWORD code;
1236
1237     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1238                          0, KEY_QUERY_VALUE, &parmKey);
1239     if (code == ERROR_SUCCESS) {
1240         dummyLen = sizeof(DWORD);
1241         code = RegQueryValueEx(parmKey, "StoreAnsiFilenames", NULL, NULL,
1242                                 (BYTE *) &dwValue, &dummyLen);
1243         if (code == ERROR_SUCCESS)
1244             smb_StoreAnsiFilenames = dwValue ? 1 : 0;
1245         RegCloseKey (parmKey);
1246     }
1247
1248     /* Do this last so that we don't handle requests before init is done.
1249      * Here we initialize the SMB listener.
1250      */
1251     smb_Init(afsd_logp, cm_NetbiosName, smb_UseV3, LANadapter, numSvThreads, aMBfunc);
1252     afsi_log("smb_Init complete");
1253
1254     return 0;
1255 }
1256
1257 #ifdef ReadOnly
1258 #undef ReadOnly
1259 #endif
1260
1261 #ifdef File
1262 #undef File
1263 #endif
1264
1265 #pragma pack( push, before_imagehlp, 8 )
1266 #include <imagehlp.h>
1267 #pragma pack( pop, before_imagehlp )
1268
1269 #define MAXNAMELEN 1024
1270
1271 void afsd_printStack(HANDLE hThread, CONTEXT *c)
1272 {
1273 #if defined(_X86_)
1274     HANDLE hProcess = GetCurrentProcess();
1275     int frameNum;
1276 #if defined(_AMD64_)
1277     DWORD64 offset;
1278 #elif defined(_X86_)
1279     DWORD offset;
1280 #endif
1281     DWORD symOptions;
1282     char functionName[MAXNAMELEN];
1283   
1284     IMAGEHLP_MODULE Module;
1285     IMAGEHLP_LINE Line;
1286   
1287     STACKFRAME s;
1288     IMAGEHLP_SYMBOL *pSym;
1289   
1290     afsi_log_useTimestamp = 0;
1291   
1292     pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
1293   
1294     memset( &s, '\0', sizeof s );
1295     if (!SymInitialize(hProcess, NULL, 1) )
1296     {
1297         afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
1298       
1299         SymCleanup( hProcess );
1300         GlobalFree(pSym);
1301       
1302         return;
1303     }
1304   
1305     symOptions = SymGetOptions();
1306     symOptions |= SYMOPT_LOAD_LINES;
1307     symOptions &= ~SYMOPT_UNDNAME;
1308     SymSetOptions( symOptions );
1309   
1310     /*
1311      * init STACKFRAME for first call
1312      * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
1313      * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
1314      * and good riddance.
1315      */
1316 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
1317 #error The STACKFRAME initialization in afsd_printStack() for this platform
1318 #error must be properly configured
1319 #elif defined(_AMD64_)
1320     s.AddrPC.Offset = 0;
1321     s.AddrPC.Mode = AddrModeFlat;
1322     s.AddrFrame.Offset = 0;
1323     s.AddrFrame.Mode = AddrModeFlat;
1324 #else
1325     s.AddrPC.Offset = c->Eip;
1326     s.AddrPC.Mode = AddrModeFlat;
1327     s.AddrFrame.Offset = c->Ebp;
1328     s.AddrFrame.Mode = AddrModeFlat;
1329 #endif
1330
1331     memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
1332     pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
1333     pSym->MaxNameLength = MAXNAMELEN;
1334   
1335     memset( &Line, '\0', sizeof Line );
1336     Line.SizeOfStruct = sizeof Line;
1337   
1338     memset( &Module, '\0', sizeof Module );
1339     Module.SizeOfStruct = sizeof Module;
1340   
1341     offset = 0;
1342   
1343     afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
1344   
1345     for ( frameNum = 0; ; ++ frameNum )
1346     {
1347         /*
1348          * get next stack frame (StackWalk(), SymFunctionTableAccess(), 
1349          * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
1350          * ERROR_NOACCESS (998), you can assume that either you are done, or
1351          * that the stack is so hosed that the next deeper frame could not be
1352          * found.
1353          */
1354         if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c, 
1355                           NULL, SymFunctionTableAccess, SymGetModuleBase, 
1356                           NULL ) )
1357             break;
1358       
1359         /* display its contents */
1360         afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
1361                  frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
1362                  s.AddrPC.Offset, s.AddrReturn.Offset,
1363                  s.AddrFrame.Offset, s.AddrStack.Offset );
1364       
1365         if ( s.AddrPC.Offset == 0 )
1366         {
1367             afsi_log("(-nosymbols- PC == 0)" );
1368         }
1369         else
1370         { 
1371             /* show procedure info from a valid PC */
1372             if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
1373             {
1374                 if ( GetLastError() != ERROR_INVALID_ADDRESS )
1375                 {
1376                     afsi_log("SymGetSymFromAddr(): errno = %lu", 
1377                              GetLastError());
1378                 }
1379             }
1380             else
1381             {
1382                 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN, 
1383                                      UNDNAME_NAME_ONLY);
1384                 afsi_log("%s", functionName );
1385
1386                 if ( offset != 0 )
1387                 {
1388                     afsi_log(" %+ld bytes", (long) offset);
1389                 }
1390             }
1391
1392             if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
1393             {
1394                 if (GetLastError() != ERROR_INVALID_ADDRESS)
1395                 {
1396                     afsi_log("Error: SymGetLineFromAddr(): errno = %lu", 
1397                              GetLastError());
1398                 }
1399             }
1400             else
1401             {
1402                 afsi_log("    Line: %s(%lu) %+ld bytes", Line.FileName, 
1403                          Line.LineNumber, offset);
1404             }
1405         }
1406       
1407         /* no return address means no deeper stackframe */
1408         if (s.AddrReturn.Offset == 0)
1409         {
1410             SetLastError(0);
1411             break;
1412         }
1413     }
1414   
1415     if (GetLastError() != 0)
1416     {
1417         afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
1418     }
1419   
1420     SymCleanup(hProcess);
1421     GlobalFree(pSym);
1422 #endif /* _X86_ */
1423 }
1424
1425 #ifdef _DEBUG
1426 static DWORD *afsd_crtDbgBreakCurrent = NULL;
1427 static DWORD afsd_crtDbgBreaks[256];
1428 #endif
1429
1430 static EFaultRepRetVal (WINAPI *pReportFault)(LPEXCEPTION_POINTERS pep, DWORD dwMode) = NULL;
1431 static BOOL (WINAPI *pMiniDumpWriteDump)(HANDLE hProcess,DWORD ProcessId,HANDLE hFile,
1432                                   MINIDUMP_TYPE DumpType,
1433                                   PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
1434                                   PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
1435                                   PMINIDUMP_CALLBACK_INFORMATION CallbackParam) = NULL;
1436
1437
1438 static HANDLE
1439 OpenDumpFile(void)
1440 {
1441     char wd[256];
1442     DWORD code;
1443
1444     code = GetEnvironmentVariable("TEMP", wd, sizeof(wd));
1445     if ( code == 0 || code > sizeof(wd) )
1446     {
1447         if (!GetWindowsDirectory(wd, sizeof(wd)))
1448             return NULL;
1449     }
1450     StringCbCatA(wd, sizeof(wd), "\\afsd.dmp");
1451     return CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1452                             CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
1453 }
1454
1455 void 
1456 GenerateMiniDump(PEXCEPTION_POINTERS ep)
1457 {
1458     if (ep == NULL) 
1459     {
1460         // Generate exception to get proper context in dump
1461         __try 
1462         {
1463             RaiseException(DBG_CONTINUE, 0, 0, NULL);
1464         } 
1465         __except(GenerateMiniDump(GetExceptionInformation()), EXCEPTION_CONTINUE_EXECUTION) 
1466         {
1467         }
1468     } 
1469     else
1470     {
1471         MINIDUMP_EXCEPTION_INFORMATION eInfo;
1472         HANDLE hFile = NULL;
1473         HMODULE hDbgHelp = NULL;
1474
1475         hDbgHelp = LoadLibrary("Dbghelp.dll");
1476         if ( hDbgHelp == NULL )
1477             return;
1478
1479         (FARPROC) pMiniDumpWriteDump = GetProcAddress(hDbgHelp, "MiniDumpWriteDump");
1480         if ( pMiniDumpWriteDump == NULL ) {
1481             FreeLibrary(hDbgHelp);
1482             return;
1483         }
1484
1485         hFile = OpenDumpFile();
1486
1487         if ( hFile ) {
1488             HKEY parmKey;
1489             DWORD dummyLen;
1490             DWORD dwValue;
1491             DWORD code;
1492             DWORD dwMiniDumpType = MiniDumpNormal;
1493
1494             code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1495                                  0, KEY_QUERY_VALUE, &parmKey);
1496             if (code == ERROR_SUCCESS) {
1497                 dummyLen = sizeof(DWORD);
1498                 code = RegQueryValueEx(parmKey, "MiniDumpType", NULL, NULL,
1499                                         (BYTE *) &dwValue, &dummyLen);
1500                 if (code == ERROR_SUCCESS)
1501                     dwMiniDumpType = dwValue ? 1 : 0;
1502                 RegCloseKey (parmKey);
1503             }
1504
1505             eInfo.ThreadId = GetCurrentThreadId();
1506             eInfo.ExceptionPointers = ep;
1507             eInfo.ClientPointers = FALSE;
1508
1509             pMiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(),
1510                                 hFile, dwMiniDumpType, ep ? &eInfo : NULL,
1511                                 NULL, NULL);
1512
1513             CloseHandle(hFile);
1514         }
1515         FreeLibrary(hDbgHelp);
1516     }
1517 }
1518
1519 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
1520 {
1521     CONTEXT context;
1522 #ifdef _DEBUG  
1523     BOOL allocRequestBrk = FALSE;
1524 #endif 
1525     HMODULE hLib = NULL;
1526   
1527     afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n", 
1528              ep->ExceptionRecord->ExceptionCode, 
1529              ep->ExceptionRecord->ExceptionAddress);
1530            
1531 #ifdef _DEBUG
1532     if (afsd_crtDbgBreakCurrent && 
1533         *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
1534     { 
1535         allocRequestBrk = TRUE;
1536         afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
1537     }
1538 #endif
1539            
1540     /* save context if we want to print the stack information */
1541     context = *ep->ContextRecord;
1542            
1543     afsd_printStack(GetCurrentThread(), &context);
1544
1545     GenerateMiniDump(ep);
1546
1547     hLib = LoadLibrary("Faultrep.dll");
1548     if ( hLib ) {
1549         (FARPROC) pReportFault = GetProcAddress(hLib, "ReportFault");
1550         if ( pReportFault )
1551             pReportFault(ep, 0);
1552         FreeLibrary(hLib);
1553     }
1554
1555     if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
1556     {
1557         afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
1558     
1559 #ifdef _DEBUG
1560         if (allocRequestBrk)
1561         {
1562             afsd_crtDbgBreakCurrent++;
1563             _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
1564         }
1565 #endif         
1566 #if defined(_X86)    
1567         ep->ContextRecord->Eip++;
1568 #endif
1569         return EXCEPTION_CONTINUE_EXECUTION;
1570     }
1571     else
1572     {
1573         return EXCEPTION_CONTINUE_SEARCH;
1574     }
1575 }
1576   
1577 void afsd_SetUnhandledExceptionFilter()
1578 {
1579     SetUnhandledExceptionFilter(afsd_ExceptionFilter);
1580 }
1581   
1582 #ifdef _DEBUG
1583 void afsd_DbgBreakAllocInit()
1584 {
1585     memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
1586     afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
1587 }
1588   
1589 void afsd_DbgBreakAdd(DWORD requestNumber)
1590 {
1591     int i;
1592     for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
1593         {
1594         if (afsd_crtDbgBreaks[i] == -1)
1595             {
1596             break;
1597             }
1598         }
1599     afsd_crtDbgBreaks[i] = requestNumber;
1600
1601     _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);
1602 }
1603 #endif