windows-init-20060306
[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 #if !defined(DJGPP)
384 static void afsd_InitServerPreferences(void)
385 {
386     HKEY hkPrefs = 0;
387     DWORD dwType, dwSize;
388     DWORD dwPrefs = 0;
389     DWORD dwIndex;
390     TCHAR szHost[256];
391     DWORD dwHostSize = 256;
392     DWORD dwRank;
393     struct sockaddr_in  saddr;
394     cm_server_t       *tsp;
395
396     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
397                       AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\VLDB",
398                       0,
399                       KEY_READ|KEY_QUERY_VALUE,
400                       &hkPrefs) == ERROR_SUCCESS) {
401
402         RegQueryInfoKey( hkPrefs,
403                          NULL,  /* lpClass */
404                          NULL,  /* lpcClass */
405                          NULL,  /* lpReserved */
406                          NULL,  /* lpcSubKeys */
407                          NULL,  /* lpcMaxSubKeyLen */
408                          NULL,  /* lpcMaxClassLen */
409                          &dwPrefs, /* lpcValues */
410                          NULL,  /* lpcMaxValueNameLen */
411                          NULL,  /* lpcMaxValueLen */
412                          NULL,  /* lpcbSecurityDescriptor */
413                          NULL   /* lpftLastWriteTime */
414                          );
415
416         for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
417
418             dwSize = sizeof(DWORD);
419             dwHostSize = 256;
420
421             if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
422                               &dwType, (LPBYTE)&dwRank, &dwSize))
423             {
424                 afsi_log("RegEnumValue(hkPrefs) failed");
425                 continue;
426             }
427
428             afsi_log("VLDB Server Preference: %s = %d",szHost, dwRank);
429
430             if (isdigit(szHost[0]))
431             {
432                 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
433                     continue;
434             } else {
435                 HOSTENT *pEntry;
436                 if ((pEntry = gethostbyname (szHost)) == NULL)
437                     continue;
438
439                 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
440             }
441             saddr.sin_family = AF_INET;
442             dwRank += (rand() & 0x000f);
443
444             tsp = cm_FindServer(&saddr, CM_SERVER_VLDB);
445             if ( tsp )          /* an existing server - ref count increased */
446             {
447                 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
448
449                 /* set preferences for an existing vlserver */
450                 cm_ChangeRankCellVLServer(tsp);
451                 cm_PutServer(tsp);  /* decrease refcount */
452             }
453             else        /* add a new server without a cell */
454             {
455                 tsp = cm_NewServer(&saddr, CM_SERVER_VLDB, NULL); /* refcount = 1 */
456                 tsp->ipRank = (USHORT)dwRank;
457             }
458         }
459
460         RegCloseKey(hkPrefs);
461     }
462
463     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
464                       AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\File",
465                       0,
466                       KEY_READ|KEY_QUERY_VALUE,
467                       &hkPrefs) == ERROR_SUCCESS) {
468
469         RegQueryInfoKey( hkPrefs,
470                          NULL,  /* lpClass */
471                          NULL,  /* lpcClass */
472                          NULL,  /* lpReserved */
473                          NULL,  /* lpcSubKeys */
474                          NULL,  /* lpcMaxSubKeyLen */
475                          NULL,  /* lpcMaxClassLen */
476                          &dwPrefs, /* lpcValues */
477                          NULL,  /* lpcMaxValueNameLen */
478                          NULL,  /* lpcMaxValueLen */
479                          NULL,  /* lpcbSecurityDescriptor */
480                          NULL   /* lpftLastWriteTime */
481                          );
482
483         for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
484
485             dwSize = sizeof(DWORD);
486             dwHostSize = 256;
487
488             if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
489                               &dwType, (LPBYTE)&dwRank, &dwSize))
490             {
491                 afsi_log("RegEnumValue(hkPrefs) failed");
492                 continue;
493             }
494
495             afsi_log("File Server Preference: %s = %d",szHost, dwRank);
496
497             if (isdigit(szHost[0]))
498             {
499                 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
500                     continue;
501             } else {
502                 HOSTENT *pEntry;
503                 if ((pEntry = gethostbyname (szHost)) == NULL)
504                     continue;
505
506                 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
507             }
508             saddr.sin_family = AF_INET;
509             dwRank += (rand() & 0x000f);
510
511             tsp = cm_FindServer(&saddr, CM_SERVER_FILE);
512             if ( tsp )          /* an existing server - ref count increased */
513             {
514                 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
515
516                 /* find volumes which might have RO copy 
517                 /* on server and change the ordering of 
518                  * their RO list 
519                  */
520                 cm_ChangeRankVolume(tsp);
521                 cm_PutServer(tsp);  /* decrease refcount */
522             }
523             else        /* add a new server without a cell */
524             {
525                 tsp = cm_NewServer(&saddr, CM_SERVER_FILE, NULL); /* refcount = 1 */
526                 tsp->ipRank = (USHORT)dwRank;
527             }
528         }
529
530         RegCloseKey(hkPrefs);
531     }
532 }
533 #endif /* DJGPP */
534
535 /*
536  * AFSD Initialization
537  */
538
539 int afsd_InitCM(char **reasonP)
540 {
541     osi_uid_t debugID;
542     afs_uint64 cacheBlocks;
543     DWORD cacheSize;
544     long logChunkSize;
545     DWORD stats;
546     DWORD dwValue;
547     DWORD rx_enable_peer_stats = 0;
548     DWORD rx_enable_process_stats = 0;
549     long traceBufSize;
550     long maxcpus;
551     long ltt, ltto;
552     long rx_nojumbo;
553     long virtualCache = 0;
554     char rootCellName[256];
555     struct rx_service *serverp;
556     static struct rx_securityClass *nullServerSecurityClassp;
557     struct hostent *thp;
558     char *msgBuf;
559     char buf[1024];
560     HKEY parmKey;
561     DWORD dummyLen;
562     DWORD regType;
563     long code;
564     /*int freelanceEnabled;*/
565     WSADATA WSAjunk;
566     lana_number_t lanaNum;
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(ConnDeadtimeout);
1001     code = RegQueryValueEx(parmKey, "ConnDeadTimeout", NULL, NULL,
1002                            (BYTE *) &ConnDeadtimeout, &dummyLen);
1003     afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
1004
1005     dummyLen = sizeof(HardDeadtimeout);
1006     code = RegQueryValueEx(parmKey, "HardDeadTimeout", NULL, NULL,
1007                            (BYTE *) &HardDeadtimeout, &dummyLen);
1008     afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
1009
1010     dummyLen = sizeof(DWORD);
1011     code = RegQueryValueEx(parmKey, "daemonCheckDownInterval", NULL, NULL,
1012                             (BYTE *) &dwValue, &dummyLen);
1013     if (code == ERROR_SUCCESS)
1014         cm_daemonCheckDownInterval = dwValue;
1015     afsi_log("daemonCheckDownInterval is %d", cm_daemonCheckDownInterval);
1016
1017     dummyLen = sizeof(DWORD);
1018     code = RegQueryValueEx(parmKey, "daemonCheckUpInterval", NULL, NULL,
1019                             (BYTE *) &dwValue, &dummyLen);
1020     if (code == ERROR_SUCCESS)
1021         cm_daemonCheckUpInterval = dwValue;
1022     afsi_log("daemonCheckUpInterval is %d", cm_daemonCheckUpInterval);
1023
1024     dummyLen = sizeof(DWORD);
1025     code = RegQueryValueEx(parmKey, "daemonCheckVolInterval", NULL, NULL,
1026                             (BYTE *) &dwValue, &dummyLen);
1027     if (code == ERROR_SUCCESS)
1028         cm_daemonCheckVolInterval = dwValue;
1029     afsi_log("daemonCheckVolInterval is %d", cm_daemonCheckVolInterval);
1030
1031     dummyLen = sizeof(DWORD);
1032     code = RegQueryValueEx(parmKey, "daemonCheckCBInterval", NULL, NULL,
1033                             (BYTE *) &dwValue, &dummyLen);
1034     if (code == ERROR_SUCCESS)
1035         cm_daemonCheckCBInterval = dwValue;
1036     afsi_log("daemonCheckCBInterval is %d", cm_daemonCheckCBInterval);
1037
1038     dummyLen = sizeof(DWORD);
1039     code = RegQueryValueEx(parmKey, "daemonCheckLockInterval", NULL, NULL,
1040                             (BYTE *) &dwValue, &dummyLen);
1041     if (code == ERROR_SUCCESS)
1042         cm_daemonCheckLockInterval = dwValue;
1043     afsi_log("daemonCheckLockInterval is %d", cm_daemonCheckLockInterval);
1044
1045     dummyLen = sizeof(DWORD);
1046     code = RegQueryValueEx(parmKey, "daemonCheckTokenInterval", NULL, NULL,
1047                             (BYTE *) &dwValue, &dummyLen);
1048     if (code == ERROR_SUCCESS)
1049         cm_daemonTokenCheckInterval = dwValue;
1050     afsi_log("daemonCheckTokenInterval is %d", cm_daemonTokenCheckInterval);
1051
1052     dummyLen = sizeof(DWORD);
1053     code = RegQueryValueEx(parmKey, "CallBackPort", NULL, NULL,
1054                            (BYTE *) &dwValue, &dummyLen);
1055     if (code == ERROR_SUCCESS) {
1056         cm_callbackport = (unsigned short) dwValue;
1057     }
1058     afsi_log("CM CallBackPort is %u", cm_callbackport);
1059
1060     dummyLen = sizeof(DWORD);
1061     code = RegQueryValueEx(parmKey, "EnableServerLocks", NULL, NULL,
1062                            (BYTE *) &dwValue, &dummyLen);
1063     if (code == ERROR_SUCCESS) {
1064         cm_enableServerLocks = (unsigned short) dwValue;
1065     } 
1066     switch (cm_enableServerLocks) {
1067     case 0:
1068         afsi_log("EnableServerLocks: never");
1069         break;
1070     case 2:
1071         afsi_log("EnableServerLocks: always");
1072         break;
1073     case 1:
1074     default:
1075         afsi_log("EnableServerLocks: server requested");
1076         break;
1077     }
1078     RegCloseKey (parmKey);
1079
1080     /* Call lanahelper to get Netbios name, lan adapter number and gateway flag */
1081     if (SUCCEEDED(code = lana_GetUncServerNameEx(cm_NetbiosName, &lanaNum, &isGateway, LANA_NETBIOS_NAME_FULL))) {
1082         LANadapter = (lanaNum == LANA_INVALID)? -1: lanaNum;
1083
1084         if (LANadapter != -1)
1085             afsi_log("LAN adapter number %d", LANadapter);
1086         else
1087             afsi_log("LAN adapter number not determined");
1088
1089         if (isGateway)
1090             afsi_log("Set for gateway service");
1091
1092         afsi_log("Using >%s< as SMB server name", cm_NetbiosName);
1093     } else {
1094         /* something went horribly wrong.  We can't proceed without a netbios name */
1095         StringCbPrintfA(buf,sizeof(buf),"Netbios name could not be determined: %li", code);
1096         osi_panic(buf, __FILE__, __LINE__);
1097     }
1098
1099     cacheBlocks = ((afs_uint64)cacheSize * 1024) / CM_CONFIGDEFAULT_BLOCKSIZE;
1100         
1101     /* get network related info */
1102     cm_noIPAddr = CM_MAXINTERFACE_ADDR;
1103     code = syscfg_GetIFInfo(&cm_noIPAddr,
1104                              cm_IPAddr, cm_SubnetMask,
1105                              cm_NetMtu, cm_NetFlags);
1106
1107     if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
1108         afsi_log("syscfg_GetIFInfo error code %d", code);
1109     else
1110         afsi_log("First Network address %x SubnetMask %x",
1111                   cm_IPAddr[0], cm_SubnetMask[0]);
1112
1113     /*
1114      * Save client configuration for GetCacheConfig requests
1115      */
1116     cm_initParams.nChunkFiles = 0;
1117     cm_initParams.nStatCaches = stats;
1118     cm_initParams.nDataCaches = (afs_uint32)(cacheBlocks > 0xFFFFFFFF ? 0xFFFFFFFF : cacheBlocks);
1119     cm_initParams.nVolumeCaches = stats/2;
1120     cm_initParams.firstChunkSize = cm_chunkSize;
1121     cm_initParams.otherChunkSize = cm_chunkSize;
1122     cm_initParams.cacheSize = cacheSize;
1123     cm_initParams.setTime = 0;
1124     cm_initParams.memCache = 1;
1125
1126     /* Ensure the AFS Netbios Name is registered to allow loopback access */
1127     configureBackConnectionHostNames();
1128
1129     /* init user daemon, and other packages */
1130     cm_InitUser();
1131
1132     cm_InitConn();
1133
1134     cm_InitServer();
1135         
1136     cm_InitIoctl();
1137         
1138     smb_InitIoctl();
1139         
1140     cm_InitCallback();
1141         
1142     code = cm_InitMappedMemory(virtualCache, cm_CachePath, stats, cm_chunkSize, cacheBlocks);
1143     afsi_log("cm_InitMappedMemory code %x", code);
1144     if (code != 0) {
1145         *reasonP = "error initializing cache file";
1146         return -1;
1147     }
1148
1149 #ifdef AFS_AFSDB_ENV
1150 #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
1151     if (cm_InitDNS(cm_dnsEnabled) == -1)
1152         cm_dnsEnabled = 0;  /* init failed, so deactivate */
1153     afsi_log("cm_InitDNS %d", cm_dnsEnabled);
1154 #endif
1155 #endif
1156
1157     /* Set RX parameters before initializing RX */
1158     if ( rx_nojumbo ) {
1159         rx_SetNoJumbo();
1160         afsi_log("rx_SetNoJumbo successful");
1161     }
1162
1163     if ( rx_mtu != -1 ) {
1164         rx_SetMaxMTU(rx_mtu);
1165         afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
1166     }
1167
1168     /* initialize RX, and tell it to listen to the callbackport, 
1169      * which is used for callback RPC messages.
1170      */
1171     code = rx_Init(htons(cm_callbackport));
1172     afsi_log("rx_Init code %x", code);
1173     if (code != 0) {
1174         *reasonP = "afsd: failed to init rx client on port 7001";
1175         return -1;
1176     }
1177
1178     /* create an unauthenticated service #1 for callbacks */
1179     nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1180     serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
1181                              RXAFSCB_ExecuteRequest);
1182     afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1183     if (serverp == NULL) {
1184         *reasonP = "unknown error";
1185         return -1;
1186     }
1187
1188     nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1189     serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
1190                              &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
1191     afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1192     if (serverp == NULL) {
1193         *reasonP = "unknown error";
1194         return -1;
1195     }
1196         
1197     /* start server threads, *not* donating this one to the pool */
1198     rx_StartServer(0);
1199     afsi_log("rx_StartServer");
1200
1201     if (rx_enable_peer_stats)
1202         rx_enablePeerRPCStats();
1203
1204     if (rx_enable_process_stats)
1205         rx_enableProcessRPCStats();
1206
1207     code = cm_GetRootCellName(rootCellName);
1208     afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s", 
1209               code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
1210     if (code != 0 && !cm_freelanceEnabled) 
1211     {
1212         *reasonP = "can't find root cell name in afsd.ini";
1213         return -1;
1214     }   
1215     else if (cm_freelanceEnabled)
1216         cm_data.rootCellp = NULL;
1217
1218     if (code == 0 && !cm_freelanceEnabled) 
1219     {
1220         cm_data.rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
1221         afsi_log("cm_GetCell addr %x", PtrToUlong(cm_data.rootCellp));
1222         if (cm_data.rootCellp == NULL) 
1223         {
1224             *reasonP = "can't find root cell in afsdcell.ini";
1225             return -1;
1226         }
1227     }
1228
1229 #ifdef AFS_FREELANCE_CLIENT
1230     if (cm_freelanceEnabled)
1231         cm_InitFreelance();
1232 #endif
1233
1234     /* Initialize the RPC server for session keys */
1235     RpcInit();
1236
1237 #if !defined(DJGPP)
1238     afsd_InitServerPreferences();
1239 #endif
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         osi_Log0(afsd_logp, "Loading Root Volume from cell");
1254         code = cm_GetVolumeByName(cm_data.rootCellp, cm_rootVolumeName, cm_rootUserp,
1255                                   &req, CM_FLAG_CREATE, &cm_data.rootVolumep);
1256         afsi_log("cm_GetVolumeByName code %x root vol %x", code,
1257                  (code ? (cm_volume_t *)-1 : cm_data.rootVolumep));
1258         if (code != 0) {
1259             *reasonP = "can't find root volume in root cell";
1260             return -1;
1261         }
1262     }
1263
1264     /* compute the root fid */
1265     if (!cm_freelanceEnabled) {
1266         cm_data.rootFid.cell = cm_data.rootCellp->cellID;
1267         cm_data.rootFid.volume = cm_GetROVolumeID(cm_data.rootVolumep);
1268         cm_data.rootFid.vnode = 1;
1269         cm_data.rootFid.unique = 1;
1270     }
1271     else
1272         cm_FakeRootFid(&cm_data.rootFid);
1273         
1274     code = cm_GetSCache(&cm_data.rootFid, &cm_data.rootSCachep, cm_rootUserp, &req);
1275     afsi_log("cm_GetSCache code %x scache %x", code,
1276              (code ? (cm_scache_t *)-1 : cm_data.rootSCachep));
1277     if (code != 0) {
1278         *reasonP = "unknown error";
1279         return -1;
1280     }
1281
1282     cm_InitDaemon(numBkgD);
1283     afsi_log("cm_InitDaemon complete");
1284
1285     return 0;
1286 }
1287
1288 int afsd_InitSMB(char **reasonP, void *aMBfunc)
1289 {
1290     HKEY parmKey;
1291     DWORD dummyLen;
1292     DWORD dwValue;
1293     DWORD code;
1294
1295     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1296                          0, KEY_QUERY_VALUE, &parmKey);
1297     if (code == ERROR_SUCCESS) {
1298         dummyLen = sizeof(DWORD);
1299         code = RegQueryValueEx(parmKey, "StoreAnsiFilenames", NULL, NULL,
1300                                 (BYTE *) &dwValue, &dummyLen);
1301         if (code == ERROR_SUCCESS)
1302             smb_StoreAnsiFilenames = dwValue ? 1 : 0;
1303         RegCloseKey (parmKey);
1304     }
1305
1306     /* Do this last so that we don't handle requests before init is done.
1307      * Here we initialize the SMB listener.
1308      */
1309     smb_Init(afsd_logp, cm_NetbiosName, smb_UseV3, LANadapter, numSvThreads, aMBfunc);
1310     afsi_log("smb_Init complete");
1311
1312     return 0;
1313 }
1314
1315 #ifdef ReadOnly
1316 #undef ReadOnly
1317 #endif
1318
1319 #ifdef File
1320 #undef File
1321 #endif
1322
1323 #pragma pack( push, before_imagehlp, 8 )
1324 #include <imagehlp.h>
1325 #pragma pack( pop, before_imagehlp )
1326
1327 #define MAXNAMELEN 1024
1328
1329 void afsd_printStack(HANDLE hThread, CONTEXT *c)
1330 {
1331 #if defined(_X86_)
1332     HANDLE hProcess = GetCurrentProcess();
1333     int frameNum;
1334 #if defined(_AMD64_)
1335     DWORD64 offset;
1336 #elif defined(_X86_)
1337     DWORD offset;
1338 #endif
1339     DWORD symOptions;
1340     char functionName[MAXNAMELEN];
1341   
1342     IMAGEHLP_MODULE Module;
1343     IMAGEHLP_LINE Line;
1344   
1345     STACKFRAME s;
1346     IMAGEHLP_SYMBOL *pSym;
1347   
1348     afsi_log_useTimestamp = 0;
1349   
1350     pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
1351   
1352     memset( &s, '\0', sizeof s );
1353     if (!SymInitialize(hProcess, NULL, 1) )
1354     {
1355         afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
1356       
1357         SymCleanup( hProcess );
1358         GlobalFree(pSym);
1359       
1360         return;
1361     }
1362   
1363     symOptions = SymGetOptions();
1364     symOptions |= SYMOPT_LOAD_LINES;
1365     symOptions &= ~SYMOPT_UNDNAME;
1366     SymSetOptions( symOptions );
1367   
1368     /*
1369      * init STACKFRAME for first call
1370      * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
1371      * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
1372      * and good riddance.
1373      */
1374 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
1375 #error The STACKFRAME initialization in afsd_printStack() for this platform
1376 #error must be properly configured
1377 #elif defined(_AMD64_)
1378     s.AddrPC.Offset = 0;
1379     s.AddrPC.Mode = AddrModeFlat;
1380     s.AddrFrame.Offset = 0;
1381     s.AddrFrame.Mode = AddrModeFlat;
1382 #else
1383     s.AddrPC.Offset = c->Eip;
1384     s.AddrPC.Mode = AddrModeFlat;
1385     s.AddrFrame.Offset = c->Ebp;
1386     s.AddrFrame.Mode = AddrModeFlat;
1387 #endif
1388
1389     memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
1390     pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
1391     pSym->MaxNameLength = MAXNAMELEN;
1392   
1393     memset( &Line, '\0', sizeof Line );
1394     Line.SizeOfStruct = sizeof Line;
1395   
1396     memset( &Module, '\0', sizeof Module );
1397     Module.SizeOfStruct = sizeof Module;
1398   
1399     offset = 0;
1400   
1401     afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
1402   
1403     for ( frameNum = 0; ; ++ frameNum )
1404     {
1405         /*
1406          * get next stack frame (StackWalk(), SymFunctionTableAccess(), 
1407          * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
1408          * ERROR_NOACCESS (998), you can assume that either you are done, or
1409          * that the stack is so hosed that the next deeper frame could not be
1410          * found.
1411          */
1412         if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c, 
1413                           NULL, SymFunctionTableAccess, SymGetModuleBase, 
1414                           NULL ) )
1415             break;
1416       
1417         /* display its contents */
1418         afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
1419                  frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
1420                  s.AddrPC.Offset, s.AddrReturn.Offset,
1421                  s.AddrFrame.Offset, s.AddrStack.Offset );
1422       
1423         if ( s.AddrPC.Offset == 0 )
1424         {
1425             afsi_log("(-nosymbols- PC == 0)" );
1426         }
1427         else
1428         { 
1429             /* show procedure info from a valid PC */
1430             if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
1431             {
1432                 if ( GetLastError() != ERROR_INVALID_ADDRESS )
1433                 {
1434                     afsi_log("SymGetSymFromAddr(): errno = %lu", 
1435                              GetLastError());
1436                 }
1437             }
1438             else
1439             {
1440                 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN, 
1441                                      UNDNAME_NAME_ONLY);
1442                 afsi_log("%s", functionName );
1443
1444                 if ( offset != 0 )
1445                 {
1446                     afsi_log(" %+ld bytes", (long) offset);
1447                 }
1448             }
1449
1450             if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
1451             {
1452                 if (GetLastError() != ERROR_INVALID_ADDRESS)
1453                 {
1454                     afsi_log("Error: SymGetLineFromAddr(): errno = %lu", 
1455                              GetLastError());
1456                 }
1457             }
1458             else
1459             {
1460                 afsi_log("    Line: %s(%lu) %+ld bytes", Line.FileName, 
1461                          Line.LineNumber, offset);
1462             }
1463         }
1464       
1465         /* no return address means no deeper stackframe */
1466         if (s.AddrReturn.Offset == 0)
1467         {
1468             SetLastError(0);
1469             break;
1470         }
1471     }
1472   
1473     if (GetLastError() != 0)
1474     {
1475         afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
1476     }
1477   
1478     SymCleanup(hProcess);
1479     GlobalFree(pSym);
1480 #endif /* _X86_ */
1481 }
1482
1483 #ifdef _DEBUG
1484 static DWORD *afsd_crtDbgBreakCurrent = NULL;
1485 static DWORD afsd_crtDbgBreaks[256];
1486 #endif
1487
1488 static EFaultRepRetVal (WINAPI *pReportFault)(LPEXCEPTION_POINTERS pep, DWORD dwMode) = NULL;
1489 static BOOL (WINAPI *pMiniDumpWriteDump)(HANDLE hProcess,DWORD ProcessId,HANDLE hFile,
1490                                   MINIDUMP_TYPE DumpType,
1491                                   PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
1492                                   PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
1493                                   PMINIDUMP_CALLBACK_INFORMATION CallbackParam) = NULL;
1494
1495
1496 static HANDLE
1497 OpenDumpFile(void)
1498 {
1499     char wd[256];
1500     DWORD code;
1501
1502     code = GetEnvironmentVariable("TEMP", wd, sizeof(wd));
1503     if ( code == 0 || code > sizeof(wd) )
1504     {
1505         if (!GetWindowsDirectory(wd, sizeof(wd)))
1506             return NULL;
1507     }
1508     StringCbCatA(wd, sizeof(wd), "\\afsd.dmp");
1509     return CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1510                             CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
1511 }
1512
1513 void 
1514 GenerateMiniDump(PEXCEPTION_POINTERS ep)
1515 {
1516     if (ep == NULL) 
1517     {
1518         // Generate exception to get proper context in dump
1519         __try 
1520         {
1521             RaiseException(DBG_CONTINUE, 0, 0, NULL);
1522         } 
1523         __except(GenerateMiniDump(GetExceptionInformation()), EXCEPTION_CONTINUE_EXECUTION) 
1524         {
1525         }
1526     } 
1527     else
1528     {
1529         MINIDUMP_EXCEPTION_INFORMATION eInfo;
1530         HANDLE hFile = NULL;
1531         HMODULE hDbgHelp = NULL;
1532
1533         hDbgHelp = LoadLibrary("Dbghelp.dll");
1534         if ( hDbgHelp == NULL )
1535             return;
1536
1537         (FARPROC) pMiniDumpWriteDump = GetProcAddress(hDbgHelp, "MiniDumpWriteDump");
1538         if ( pMiniDumpWriteDump == NULL ) {
1539             FreeLibrary(hDbgHelp);
1540             return;
1541         }
1542
1543         hFile = OpenDumpFile();
1544
1545         if ( hFile ) {
1546             HKEY parmKey;
1547             DWORD dummyLen;
1548             DWORD dwValue;
1549             DWORD code;
1550             DWORD dwMiniDumpType = MiniDumpNormal;
1551
1552             code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1553                                  0, KEY_QUERY_VALUE, &parmKey);
1554             if (code == ERROR_SUCCESS) {
1555                 dummyLen = sizeof(DWORD);
1556                 code = RegQueryValueEx(parmKey, "MiniDumpType", NULL, NULL,
1557                                         (BYTE *) &dwValue, &dummyLen);
1558                 if (code == ERROR_SUCCESS)
1559                     dwMiniDumpType = dwValue ? 1 : 0;
1560                 RegCloseKey (parmKey);
1561             }
1562
1563             eInfo.ThreadId = GetCurrentThreadId();
1564             eInfo.ExceptionPointers = ep;
1565             eInfo.ClientPointers = FALSE;
1566
1567             pMiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(),
1568                                 hFile, dwMiniDumpType, ep ? &eInfo : NULL,
1569                                 NULL, NULL);
1570
1571             CloseHandle(hFile);
1572         }
1573         FreeLibrary(hDbgHelp);
1574     }
1575 }
1576
1577 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
1578 {
1579     CONTEXT context;
1580 #ifdef _DEBUG  
1581     BOOL allocRequestBrk = FALSE;
1582 #endif 
1583     HMODULE hLib = NULL;
1584   
1585     afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n", 
1586              ep->ExceptionRecord->ExceptionCode, 
1587              ep->ExceptionRecord->ExceptionAddress);
1588            
1589 #ifdef _DEBUG
1590     if (afsd_crtDbgBreakCurrent && 
1591         *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
1592     { 
1593         allocRequestBrk = TRUE;
1594         afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
1595     }
1596 #endif
1597            
1598     /* save context if we want to print the stack information */
1599     context = *ep->ContextRecord;
1600            
1601     afsd_printStack(GetCurrentThread(), &context);
1602
1603     GenerateMiniDump(ep);
1604
1605     hLib = LoadLibrary("Faultrep.dll");
1606     if ( hLib ) {
1607         (FARPROC) pReportFault = GetProcAddress(hLib, "ReportFault");
1608         if ( pReportFault )
1609             pReportFault(ep, 0);
1610         FreeLibrary(hLib);
1611     }
1612
1613     if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
1614     {
1615         afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
1616     
1617 #ifdef _DEBUG
1618         if (allocRequestBrk)
1619         {
1620             afsd_crtDbgBreakCurrent++;
1621             _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
1622         }
1623 #endif         
1624 #if defined(_X86)    
1625         ep->ContextRecord->Eip++;
1626 #endif
1627         return EXCEPTION_CONTINUE_EXECUTION;
1628     }
1629     else
1630     {
1631         return EXCEPTION_CONTINUE_SEARCH;
1632     }
1633 }
1634   
1635 void afsd_SetUnhandledExceptionFilter()
1636 {
1637     SetUnhandledExceptionFilter(afsd_ExceptionFilter);
1638 }
1639   
1640 #ifdef _DEBUG
1641 void afsd_DbgBreakAllocInit()
1642 {
1643     memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
1644     afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
1645 }
1646   
1647 void afsd_DbgBreakAdd(DWORD requestNumber)
1648 {
1649     int i;
1650     for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
1651         {
1652         if (afsd_crtDbgBreaks[i] == -1)
1653             {
1654             break;
1655             }
1656         }
1657     afsd_crtDbgBreaks[i] = requestNumber;
1658
1659     _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);
1660 }
1661 #endif