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