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