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