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