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