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