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