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