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