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