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