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