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