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