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