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