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