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