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