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