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