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