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