2 * Copyright 2000, International Business Machines Corporation and others.
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
10 #include <afs/param.h>
12 #include <afs/afs_args.h>
26 #include <rx\rx_null.h>
27 #include <WINNT/syscfg.h>
28 #include <WINNT/afsreg.h>
32 #include "lanahelper.h"
35 #include "cm_memmap.h"
37 extern int RXAFSCB_ExecuteRequest(struct rx_call *z_call);
38 extern int RXSTATS_ExecuteRequest(struct rx_call *z_call);
40 extern afs_int32 cryptall;
44 cm_config_data_t cm_data;
46 char cm_rootVolumeName[VL_MAXNAMELEN];
47 DWORD cm_rootVolumeNameLen;
48 char cm_mountRoot[1024];
49 DWORD cm_mountRootLen;
52 #ifdef AFS_FREELANCE_CLIENT
54 #endif /* freelance */
67 char cm_HostName[200];
70 char cm_NetbiosName[MAX_NB_NAME_LENGTH] = "";
72 char cm_CachePath[MAX_PATH];
73 DWORD cm_CachePathLen;
74 DWORD cm_ValidateCache = 1;
76 BOOL isGateway = FALSE;
78 BOOL reportSessionStartups = FALSE;
80 cm_initparams_v1 cm_initParams;
83 unsigned int cm_sysNameCount = 0;
84 char *cm_sysNameList[MAXNUMSYSNAMES];
86 DWORD TraceOption = 0;
89 * AFSD Initialization Log
91 * This is distinct from the regular debug logging facility.
92 * Log items go directly to a file, not to an array in memory, so that even
93 * if AFSD crashes, the log can be inspected.
99 int cm_dnsEnabled = 1;
103 static int afsi_log_useTimestamp = 1;
106 afsi_log(char *pattern, ...)
108 char s[256], t[100], d[100], u[512];
111 va_start(ap, pattern);
113 StringCbVPrintfA(s, sizeof(s), pattern, ap);
114 if ( afsi_log_useTimestamp ) {
115 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
116 GetDateFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, d, sizeof(d));
117 StringCbPrintfA(u, sizeof(u), "%s %s: %s\n", d, t, s);
118 if (afsi_file != INVALID_HANDLE_VALUE)
119 WriteFile(afsi_file, u, strlen(u), &zilch, NULL);
124 if (afsi_file != INVALID_HANDLE_VALUE)
125 WriteFile(afsi_file, s, strlen(s), &zilch, NULL);
129 extern initUpperCaseTable();
130 void afsd_initUpperCaseTable()
132 initUpperCaseTable();
139 char t[100], u[100], *p, *path;
145 DWORD maxLogSize = 100 * 1024;
147 afsi_file = INVALID_HANDLE_VALUE;
150 StringCbCopyA(wd, sizeof(wd), getenv("TEMP"));
154 code = GetWindowsDirectory(wd, sizeof(wd));
158 StringCbCatA(wd, sizeof(wd), "\\afsd_init.log");
159 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
160 afsi_file = CreateFile(wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
161 OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
163 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
164 0, KEY_QUERY_VALUE, &parmKey);
165 if (code == ERROR_SUCCESS) {
166 dummyLen = sizeof(maxLogSize);
167 code = RegQueryValueEx(parmKey, "MaxLogSize", NULL, NULL,
168 (BYTE *) &maxLogSize, &dummyLen);
169 RegCloseKey (parmKey);
173 dwLow = GetFileSize( afsi_file, &dwHigh );
174 if ( dwHigh > 0 || dwLow >= maxLogSize ) {
175 CloseHandle(afsi_file);
176 afsi_file = CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
177 CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
181 SetFilePointer(afsi_file, 0, NULL, FILE_END);
182 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, u, sizeof(u));
183 StringCbCatA(t, sizeof(t), ": Create log file\n");
184 StringCbCatA(u, sizeof(u), ": Created log file\n");
185 WriteFile(afsi_file, t, strlen(t), &zilch, NULL);
186 WriteFile(afsi_file, u, strlen(u), &zilch, NULL);
188 path = getenv("PATH");
189 WriteFile(afsi_file, p, strlen(p), &zilch, NULL);
190 WriteFile(afsi_file, path, strlen(path), &zilch, NULL);
191 WriteFile(afsi_file, "\n", 1, &zilch, NULL);
193 /* Initialize C RTL Code Page conversion functions */
194 /* All of the path info obtained from the SMB client is in the OEM code page */
195 afsi_log("OEM Code Page = %d", GetOEMCP());
196 afsi_log("locale = %s", setlocale(LC_ALL,NULL));
198 /* Two things to look into. First, should mbstowcs() be performing
199 * character set translations from OEM to Unicode in smb3.c;
200 * Second, do we need to set this translation in each function
201 * due to multi-threading.
203 afsi_log("locale -> %s", setlocale(LC_ALL, ".OCP"));
204 afsi_log("_setmbcp = %d -> %d", _setmbcp(_MB_CP_OEM), _getmbcp());
209 * Standard AFSD trace
212 void afsd_ForceTrace(BOOL flush)
221 len = GetTempPath(sizeof(buf)-10, buf);
222 StringCbCopyA(&buf[len], sizeof(buf)-len, "/afsd.log");
223 handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
224 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
225 if (handle == INVALID_HANDLE_VALUE) {
227 osi_panic("Cannot create log file", __FILE__, __LINE__);
229 osi_LogPrint(afsd_logp, handle);
231 FlushFileBuffers(handle);
236 configureBackConnectionHostNames(void)
238 /* On Windows XP SP2, Windows 2003 SP1, and all future Windows operating systems
239 * there is a restriction on the use of SMB authentication on loopback connections.
240 * There are two work arounds available:
242 * (1) We can disable the check for matching host names. This does not
244 * [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa]
245 * "DisableLoopbackCheck"=dword:00000001
247 * (2) We can add the AFS SMB/CIFS service name to an approved list. This
248 * does require a reboot:
249 * [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0]
250 * "BackConnectionHostNames"=multi-sz
252 * The algorithm will be:
253 * (1) Check to see if cm_NetbiosName exists in the BackConnectionHostNames list
254 * (2a) If not, add it to the list. (This will not take effect until the next reboot.)
255 * (2b1) and check to see if DisableLoopbackCheck is set.
256 * (2b2) If not set, set the DisableLoopbackCheck value to 0x1
257 * (2b3) and create HKLM\SOFTWARE\OpenAFS\Client UnsetDisableLoopbackCheck
258 * (2c) else If cm_NetbiosName exists in the BackConnectionHostNames list,
259 * check for the UnsetDisableLoopbackCheck value.
260 * If set, set the DisableLoopbackCheck flag to 0x0
261 * and delete the UnsetDisableLoopbackCheck value
263 * Starting in Longhorn Beta 1, an entry in the BackConnectionHostNames value will
264 * force Windows to use the loopback authentication mechanism for the specified
273 PBYTE pHostNames = NULL, pName = NULL;
274 BOOL bNameFound = FALSE;
276 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
277 "SYSTEM\\CurrentControlSet\\Control\\Lsa\\MSV1_0",
280 &hkMSV10) == ERROR_SUCCESS )
282 if (RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0, &dwType, NULL, &dwSize) == ERROR_SUCCESS) {
283 pHostNames = malloc(dwSize + strlen(cm_NetbiosName) + 1);
284 RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0, &dwType, pHostNames, &dwSize);
286 for (pName = pHostNames; *pName ; pName += strlen(pName) + 1)
288 if ( !stricmp(pName, cm_NetbiosName) ) {
296 int size = strlen(cm_NetbiosName) + 2;
298 pHostNames = malloc(size);
302 StringCbCopyA(pName, size, cm_NetbiosName);
304 *pName = '\0'; /* add a second nul terminator */
306 dwType = REG_MULTI_SZ;
307 dwSize += strlen(cm_NetbiosName) + 1;
308 RegSetValueEx( hkMSV10, "BackConnectionHostNames", 0, dwType, pHostNames, dwSize);
310 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
311 "SYSTEM\\CurrentControlSet\\Control\\Lsa",
314 &hkLsa) == ERROR_SUCCESS )
316 dwSize = sizeof(DWORD);
317 if ( RegQueryValueEx( hkLsa, "DisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) != ERROR_SUCCESS ||
320 dwSize = sizeof(DWORD);
322 RegSetValueEx( hkLsa, "DisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
324 if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
325 AFSREG_CLT_OPENAFS_SUBKEY,
328 REG_OPTION_NON_VOLATILE,
332 NULL) == ERROR_SUCCESS) {
335 dwSize = sizeof(DWORD);
337 RegSetValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
338 RegCloseKey(hkClient);
344 if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
345 AFSREG_CLT_OPENAFS_SUBKEY,
348 REG_OPTION_NON_VOLATILE,
352 NULL) == ERROR_SUCCESS) {
354 dwSize = sizeof(DWORD);
355 if ( RegQueryValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) == ERROR_SUCCESS &&
357 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
358 "SYSTEM\\CurrentControlSet\\Control\\Lsa",
361 &hkLsa) == ERROR_SUCCESS )
363 RegDeleteValue(hkLsa, "DisableLoopbackCheck");
367 RegDeleteValue(hkClient, "RemoveDisableLoopbackCheck");
368 RegCloseKey(hkClient);
371 RegCloseKey(hkMSV10);
376 static void afsd_InitServerPreferences(void)
379 DWORD dwType, dwSize;
383 DWORD dwHostSize = 256;
385 struct sockaddr_in saddr;
388 if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
389 AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\VLDB",
391 KEY_READ|KEY_QUERY_VALUE,
392 &hkPrefs) == ERROR_SUCCESS) {
394 RegQueryInfoKey( hkPrefs,
397 NULL, /* lpReserved */
398 NULL, /* lpcSubKeys */
399 NULL, /* lpcMaxSubKeyLen */
400 NULL, /* lpcMaxClassLen */
401 &dwPrefs, /* lpcValues */
402 NULL, /* lpcMaxValueNameLen */
403 NULL, /* lpcMaxValueLen */
404 NULL, /* lpcbSecurityDescriptor */
405 NULL /* lpftLastWriteTime */
408 for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
410 dwSize = sizeof(DWORD);
413 if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
414 &dwType, (LPBYTE)&dwRank, &dwSize))
416 afsi_log("RegEnumValue(hkPrefs) failed");
420 afsi_log("VLDB Server Preference: %s = %d",szHost, dwRank);
422 if (isdigit(szHost[0]))
424 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
428 if ((pEntry = gethostbyname (szHost)) == NULL)
431 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
433 saddr.sin_family = AF_INET;
434 dwRank += (rand() & 0x000f);
436 tsp = cm_FindServer(&saddr, CM_SERVER_VLDB);
437 if ( tsp ) /* an existing server - ref count increased */
439 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
441 /* set preferences for an existing vlserver */
442 cm_ChangeRankCellVLServer(tsp);
443 cm_PutServer(tsp); /* decrease refcount */
445 else /* add a new server without a cell */
447 tsp = cm_NewServer(&saddr, CM_SERVER_VLDB, NULL); /* refcount = 1 */
448 tsp->ipRank = (USHORT)dwRank;
452 RegCloseKey(hkPrefs);
455 if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
456 AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\File",
458 KEY_READ|KEY_QUERY_VALUE,
459 &hkPrefs) == ERROR_SUCCESS) {
461 RegQueryInfoKey( hkPrefs,
464 NULL, /* lpReserved */
465 NULL, /* lpcSubKeys */
466 NULL, /* lpcMaxSubKeyLen */
467 NULL, /* lpcMaxClassLen */
468 &dwPrefs, /* lpcValues */
469 NULL, /* lpcMaxValueNameLen */
470 NULL, /* lpcMaxValueLen */
471 NULL, /* lpcbSecurityDescriptor */
472 NULL /* lpftLastWriteTime */
475 for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
477 dwSize = sizeof(DWORD);
480 if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
481 &dwType, (LPBYTE)&dwRank, &dwSize))
483 afsi_log("RegEnumValue(hkPrefs) failed");
487 afsi_log("File Server Preference: %s = %d",szHost, dwRank);
489 if (isdigit(szHost[0]))
491 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
495 if ((pEntry = gethostbyname (szHost)) == NULL)
498 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
500 saddr.sin_family = AF_INET;
501 dwRank += (rand() & 0x000f);
503 tsp = cm_FindServer(&saddr, CM_SERVER_FILE);
504 if ( tsp ) /* an existing server - ref count increased */
506 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
508 /* find volumes which might have RO copy
509 /* on server and change the ordering of
512 cm_ChangeRankVolume(tsp);
513 cm_PutServer(tsp); /* decrease refcount */
515 else /* add a new server without a cell */
517 tsp = cm_NewServer(&saddr, CM_SERVER_FILE, NULL); /* refcount = 1 */
518 tsp->ipRank = (USHORT)dwRank;
522 RegCloseKey(hkPrefs);
528 * AFSD Initialization
531 int afsd_InitCM(char **reasonP)
542 long virtualCache = 0;
543 char rootCellName[256];
544 struct rx_service *serverp;
545 static struct rx_securityClass *nullServerSecurityClassp;
553 /*int freelanceEnabled;*/
555 lana_number_t lanaNum;
558 int cm_noIPAddr; /* number of client network interfaces */
559 int cm_IPAddr[CM_MAXINTERFACE_ADDR]; /* client's IP address in host order */
560 int cm_SubnetMask[CM_MAXINTERFACE_ADDR];/* client's subnet mask in host order*/
561 int cm_NetMtu[CM_MAXINTERFACE_ADDR]; /* client's MTU sizes */
562 int cm_NetFlags[CM_MAXINTERFACE_ADDR]; /* network flags */
564 WSAStartup(0x0101, &WSAjunk);
566 afsd_initUpperCaseTable();
568 /* setup osidebug server at RPC slot 1000 */
569 osi_LongToUID(1000, &debugID);
570 code = osi_InitDebug(&debugID);
571 afsi_log("osi_InitDebug code %d", code);
573 // osi_LockTypeSetDefault("stat"); /* comment this out for speed *
575 *reasonP = "unknown error";
580 gethostname(cm_HostName, sizeof(cm_HostName));
581 afsi_log("gethostname %s", cm_HostName);
582 thp = gethostbyname(cm_HostName);
583 memcpy(&cm_HostAddr, thp->h_addr_list[0], 4);
585 /* seed random number generator */
586 srand(ntohl(cm_HostAddr));
588 /* Look up configuration parameters in Registry */
589 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
590 0, KEY_QUERY_VALUE, &parmKey);
591 if (code != ERROR_SUCCESS) {
592 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
593 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
594 NULL, code, 0, (LPTSTR)&msgBuf, 0, NULL);
595 StringCbPrintfA(buf, sizeof(buf),
596 "Failure in configuration while opening Registry: %s",
598 osi_panic(buf, __FILE__, __LINE__);
601 dummyLen = sizeof(maxcpus);
602 code = RegQueryValueEx(parmKey, "MaxCPUs", NULL, NULL,
603 (BYTE *) &maxcpus, &dummyLen);
604 if (code == ERROR_SUCCESS) {
606 DWORD_PTR processAffinityMask, systemAffinityMask;
608 hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION,
609 FALSE, GetCurrentProcessId());
610 if ( hProcess != NULL &&
611 GetProcessAffinityMask(hProcess, &processAffinityMask, &systemAffinityMask) )
614 DWORD_PTR mask, newAffinityMask;
621 for ( i=0, n=0, mask=1, newAffinityMask=0; i<bits && n<maxcpus; i++ ) {
622 if ( processAffinityMask & mask ) {
623 newAffinityMask |= mask;
629 SetProcessAffinityMask(hProcess, newAffinityMask);
630 CloseHandle(hProcess);
631 afsi_log("CPU Restrictions set to %d cpu(s); %d cpu(s) available", maxcpus, n);
633 afsi_log("CPU Restrictions set to %d cpu(s); unable to access process information", maxcpus);
637 dummyLen = sizeof(TraceOption);
638 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
639 (BYTE *) &TraceOption, &dummyLen);
640 afsi_log("Event Log Tracing = %lX", TraceOption);
642 dummyLen = sizeof(traceBufSize);
643 code = RegQueryValueEx(parmKey, "TraceBufferSize", NULL, NULL,
644 (BYTE *) &traceBufSize, &dummyLen);
645 if (code == ERROR_SUCCESS)
646 afsi_log("Trace Buffer size %d", traceBufSize);
648 traceBufSize = CM_CONFIGDEFAULT_TRACEBUFSIZE;
649 afsi_log("Default trace buffer size %d", traceBufSize);
652 /* setup and enable debug log */
653 afsd_logp = osi_LogCreate("afsd", traceBufSize);
654 afsi_log("osi_LogCreate log addr %x", (int)afsd_logp);
655 osi_LogEnable(afsd_logp);
658 osi_Log0(afsd_logp, "Log init");
660 dummyLen = sizeof(cacheSize);
661 code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
662 (BYTE *) &cacheSize, &dummyLen);
663 if (code == ERROR_SUCCESS)
664 afsi_log("Cache size %d", cacheSize);
666 cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
667 afsi_log("Default cache size %d", cacheSize);
670 dummyLen = sizeof(logChunkSize);
671 code = RegQueryValueEx(parmKey, "ChunkSize", NULL, NULL,
672 (BYTE *) &logChunkSize, &dummyLen);
673 if (code == ERROR_SUCCESS) {
674 if (logChunkSize < 12 || logChunkSize > 30) {
675 afsi_log("Invalid chunk size %d, using default",
677 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
679 afsi_log("Chunk size %d", logChunkSize);
681 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
682 afsi_log("Default chunk size %d", logChunkSize);
684 cm_logChunkSize = logChunkSize;
685 cm_chunkSize = 1 << logChunkSize;
687 dummyLen = sizeof(numBkgD);
688 code = RegQueryValueEx(parmKey, "Daemons", NULL, NULL,
689 (BYTE *) &numBkgD, &dummyLen);
690 if (code == ERROR_SUCCESS)
691 afsi_log("%d background daemons", numBkgD);
693 numBkgD = CM_CONFIGDEFAULT_DAEMONS;
694 afsi_log("Defaulting to %d background daemons", numBkgD);
697 dummyLen = sizeof(numSvThreads);
698 code = RegQueryValueEx(parmKey, "ServerThreads", NULL, NULL,
699 (BYTE *) &numSvThreads, &dummyLen);
700 if (code == ERROR_SUCCESS)
701 afsi_log("%d server threads", numSvThreads);
703 numSvThreads = CM_CONFIGDEFAULT_SVTHREADS;
704 afsi_log("Defaulting to %d server threads", numSvThreads);
707 dummyLen = sizeof(stats);
708 code = RegQueryValueEx(parmKey, "Stats", NULL, NULL,
709 (BYTE *) &stats, &dummyLen);
710 if (code == ERROR_SUCCESS)
711 afsi_log("Status cache size %d", stats);
713 stats = CM_CONFIGDEFAULT_STATS;
714 afsi_log("Default status cache size %d", stats);
717 dummyLen = sizeof(ltt);
718 code = RegQueryValueEx(parmKey, "LogoffTokenTransfer", NULL, NULL,
719 (BYTE *) <t, &dummyLen);
720 if (code == ERROR_SUCCESS)
721 afsi_log("Logoff token transfer %s", (ltt ? "on" : "off"));
724 afsi_log("Logoff token transfer on by default");
726 smb_LogoffTokenTransfer = ltt;
727 afsi_log("Logoff token transfer is currently ignored");
730 dummyLen = sizeof(ltto);
731 code = RegQueryValueEx(parmKey, "LogoffTokenTransferTimeout",
732 NULL, NULL, (BYTE *) <to, &dummyLen);
733 if (code == ERROR_SUCCESS)
734 afsi_log("Logoff token tranfer timeout %d seconds", ltto);
737 afsi_log("Default logoff token transfer timeout 10 seconds");
742 smb_LogoffTransferTimeout = ltto;
743 afsi_log("Default logoff token is currently ignored");
745 dummyLen = sizeof(cm_rootVolumeName);
746 code = RegQueryValueEx(parmKey, "RootVolume", NULL, NULL,
747 cm_rootVolumeName, &dummyLen);
748 if (code == ERROR_SUCCESS)
749 afsi_log("Root volume %s", cm_rootVolumeName);
751 StringCbCopyA(cm_rootVolumeName, sizeof(cm_rootVolumeName), "root.afs");
752 afsi_log("Default root volume name root.afs");
755 cm_mountRootLen = sizeof(cm_mountRoot);
756 code = RegQueryValueEx(parmKey, "MountRoot", NULL, NULL,
757 cm_mountRoot, &cm_mountRootLen);
758 if (code == ERROR_SUCCESS) {
759 afsi_log("Mount root %s", cm_mountRoot);
760 cm_mountRootLen = strlen(cm_mountRoot);
762 StringCbCopyA(cm_mountRoot, sizeof(cm_mountRoot), "/afs");
767 dummyLen = sizeof(buf);
768 code = RegQueryValueEx(parmKey, "CachePath", NULL, ®Type,
770 if (code == ERROR_SUCCESS && buf[0]) {
771 if (regType == REG_EXPAND_SZ) {
772 dummyLen = ExpandEnvironmentStrings(buf, cm_CachePath, sizeof(cm_CachePath));
773 if (dummyLen > sizeof(cm_CachePath)) {
774 afsi_log("Cache path [%s] longer than %d after expanding env strings", buf, sizeof(cm_CachePath));
775 osi_panic("CachePath too long", __FILE__, __LINE__);
778 StringCbCopyA(cm_CachePath, sizeof(cm_CachePath), buf);
780 afsi_log("Cache path %s", cm_CachePath);
782 dummyLen = ExpandEnvironmentStrings("%TEMP%\\AFSCache", cm_CachePath, sizeof(cm_CachePath));
783 if (dummyLen > sizeof(cm_CachePath)) {
784 afsi_log("Cache path [%%TEMP%%\\AFSCache] longer than %d after expanding env strings",
785 sizeof(cm_CachePath));
786 osi_panic("CachePath too long", __FILE__, __LINE__);
788 afsi_log("Default cache path %s", cm_CachePath);
791 dummyLen = sizeof(virtualCache);
792 code = RegQueryValueEx(parmKey, "NonPersistentCaching", NULL, NULL,
793 (LPBYTE)&virtualCache, &dummyLen);
794 afsi_log("Cache type is %s", (virtualCache?"VIRTUAL":"FILE"));
797 dummyLen = sizeof(cm_ValidateCache);
798 code = RegQueryValueEx(parmKey, "ValidateCache", NULL, NULL,
799 (LPBYTE)&cm_ValidateCache, &dummyLen);
800 if ( cm_ValidateCache < 0 || cm_ValidateCache > 2 )
801 cm_ValidateCache = 1;
802 switch (cm_ValidateCache) {
804 afsi_log("Cache Validation disabled");
807 afsi_log("Cache Validation on Startup");
810 afsi_log("Cache Validation on Startup and Shutdown");
815 dummyLen = sizeof(traceOnPanic);
816 code = RegQueryValueEx(parmKey, "TrapOnPanic", NULL, NULL,
817 (BYTE *) &traceOnPanic, &dummyLen);
818 if (code == ERROR_SUCCESS)
819 afsi_log("Set to %s on panic",
820 traceOnPanic ? "trap" : "not trap");
826 dummyLen = sizeof(reportSessionStartups);
827 code = RegQueryValueEx(parmKey, "ReportSessionStartups", NULL, NULL,
828 (BYTE *) &reportSessionStartups, &dummyLen);
829 if (code == ERROR_SUCCESS)
830 afsi_log("Session startups %s be recorded in the Event Log",
831 reportSessionStartups ? "will" : "will not");
833 reportSessionStartups = 0;
837 for ( i=0; i < MAXNUMSYSNAMES; i++ ) {
838 cm_sysNameList[i] = osi_Alloc(MAXSYSNAME);
839 cm_sysNameList[i][0] = '\0';
841 cm_sysName = cm_sysNameList[0];
843 dummyLen = sizeof(buf);
844 code = RegQueryValueEx(parmKey, "SysName", NULL, NULL, buf, &dummyLen);
845 if (code != ERROR_SUCCESS || !buf[0]) {
847 StringCbCopyA(buf, sizeof(buf), "ia64_win64");
848 #elif defined(_AMD64)
849 StringCbCopyA(buf, sizeof(buf), "amd64_win64");
850 #else /* assume x86 32-bit */
851 StringCbCopyA(buf, sizeof(buf), "x86_win32 i386_w2k i386_nt40");
854 afsi_log("Sys name %s", buf);
856 /* breakup buf into individual search string entries */
857 for (p = q = buf; p < buf + dummyLen; p++)
859 if (*p == '\0' || isspace(*p)) {
860 memcpy(cm_sysNameList[cm_sysNameCount],q,p-q);
861 cm_sysNameList[cm_sysNameCount][p-q] = '\0';
868 } while (*p == '\0' || isspace(*p));
874 StringCbCopyA(cm_sysName, MAXSYSNAME, cm_sysNameList[0]);
876 dummyLen = sizeof(cryptall);
877 code = RegQueryValueEx(parmKey, "SecurityLevel", NULL, NULL,
878 (BYTE *) &cryptall, &dummyLen);
879 if (code == ERROR_SUCCESS) {
880 afsi_log("SecurityLevel is %s", cryptall?"crypt":"clear");
883 afsi_log("Default SecurityLevel is clear");
887 dummyLen = sizeof(cm_dnsEnabled);
888 code = RegQueryValueEx(parmKey, "UseDNS", NULL, NULL,
889 (BYTE *) &cm_dnsEnabled, &dummyLen);
890 if (code == ERROR_SUCCESS) {
891 afsi_log("DNS %s be used to find AFS cell servers",
892 cm_dnsEnabled ? "will" : "will not");
895 cm_dnsEnabled = 1; /* default on */
896 afsi_log("Default to use DNS to find AFS cell servers");
898 #else /* AFS_AFSDB_ENV */
899 afsi_log("AFS not built with DNS support to find AFS cell servers");
900 #endif /* AFS_AFSDB_ENV */
902 #ifdef AFS_FREELANCE_CLIENT
903 dummyLen = sizeof(cm_freelanceEnabled);
904 code = RegQueryValueEx(parmKey, "FreelanceClient", NULL, NULL,
905 (BYTE *) &cm_freelanceEnabled, &dummyLen);
906 if (code == ERROR_SUCCESS) {
907 afsi_log("Freelance client feature %s activated",
908 cm_freelanceEnabled ? "is" : "is not");
911 cm_freelanceEnabled = 0; /* default off */
913 #endif /* AFS_FREELANCE_CLIENT */
916 /* The netbios name is looked up in lana_GetUNCServerNameEx */
917 dummyLen = sizeof(buf);
918 code = RegQueryValueEx(parmKey, "NetbiosName", NULL, NULL,
919 (BYTE *) &buf, &dummyLen);
920 if (code == ERROR_SUCCESS) {
921 DWORD len = ExpandEnvironmentStrings(buf, cm_NetbiosName, MAX_NB_NAME_LENGTH);
922 if ( len > 0 && len <= MAX_NB_NAME_LENGTH ) {
923 afsi_log("Explicit NetBios name is used %s", cm_NetbiosName);
925 afsi_log("Unable to Expand Explicit NetBios name: %s", buf);
926 cm_NetbiosName[0] = 0; /* turn it off */
930 cm_NetbiosName[0] = 0; /* default off */
934 dummyLen = sizeof(smb_hideDotFiles);
935 code = RegQueryValueEx(parmKey, "HideDotFiles", NULL, NULL,
936 (BYTE *) &smb_hideDotFiles, &dummyLen);
937 if (code != ERROR_SUCCESS) {
938 smb_hideDotFiles = 1; /* default on */
940 afsi_log("Dot files/dirs will %sbe marked hidden",
941 smb_hideDotFiles ? "" : "not ");
943 dummyLen = sizeof(smb_maxMpxRequests);
944 code = RegQueryValueEx(parmKey, "MaxMpxRequests", NULL, NULL,
945 (BYTE *) &smb_maxMpxRequests, &dummyLen);
946 if (code != ERROR_SUCCESS) {
947 smb_maxMpxRequests = 50;
949 afsi_log("Maximum number of multiplexed sessions is %d", smb_maxMpxRequests);
951 dummyLen = sizeof(smb_maxVCPerServer);
952 code = RegQueryValueEx(parmKey, "MaxVCPerServer", NULL, NULL,
953 (BYTE *) &smb_maxVCPerServer, &dummyLen);
954 if (code != ERROR_SUCCESS) {
955 smb_maxVCPerServer = 100;
957 afsi_log("Maximum number of VCs per server is %d", smb_maxVCPerServer);
959 dummyLen = sizeof(smb_authType);
960 code = RegQueryValueEx(parmKey, "SMBAuthType", NULL, NULL,
961 (BYTE *) &smb_authType, &dummyLen);
963 if (code != ERROR_SUCCESS ||
964 (smb_authType != SMB_AUTH_EXTENDED && smb_authType != SMB_AUTH_NTLM && smb_authType != SMB_AUTH_NONE)) {
965 smb_authType = SMB_AUTH_EXTENDED; /* default is to use extended authentication */
967 afsi_log("SMB authentication type is %s", ((smb_authType == SMB_AUTH_NONE)?"NONE":((smb_authType == SMB_AUTH_EXTENDED)?"EXTENDED":"NTLM")));
969 dummyLen = sizeof(rx_nojumbo);
970 code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
971 (BYTE *) &rx_nojumbo, &dummyLen);
972 if (code != ERROR_SUCCESS) {
976 afsi_log("RX Jumbograms are disabled");
978 dummyLen = sizeof(rx_mtu);
979 code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
980 (BYTE *) &rx_mtu, &dummyLen);
981 if (code != ERROR_SUCCESS || !rx_mtu) {
985 afsi_log("RX maximum MTU is %d", rx_mtu);
987 dummyLen = sizeof(ConnDeadtimeout);
988 code = RegQueryValueEx(parmKey, "ConnDeadTimeout", NULL, NULL,
989 (BYTE *) &ConnDeadtimeout, &dummyLen);
990 afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
992 dummyLen = sizeof(HardDeadtimeout);
993 code = RegQueryValueEx(parmKey, "HardDeadTimeout", NULL, NULL,
994 (BYTE *) &HardDeadtimeout, &dummyLen);
995 afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
997 RegCloseKey (parmKey);
999 /* Call lanahelper to get Netbios name, lan adapter number and gateway flag */
1000 if (SUCCEEDED(code = lana_GetUncServerNameEx(cm_NetbiosName, &lanaNum, &isGateway, LANA_NETBIOS_NAME_FULL))) {
1001 LANadapter = (lanaNum == LANA_INVALID)? -1: lanaNum;
1003 if (LANadapter != -1)
1004 afsi_log("LAN adapter number %d", LANadapter);
1006 afsi_log("LAN adapter number not determined");
1009 afsi_log("Set for gateway service");
1011 afsi_log("Using >%s< as SMB server name", cm_NetbiosName);
1013 /* something went horribly wrong. We can't proceed without a netbios name */
1014 StringCbPrintfA(buf,sizeof(buf),"Netbios name could not be determined: %li", code);
1015 osi_panic(buf, __FILE__, __LINE__);
1018 cacheBlocks = (cacheSize * 1024) / CM_CONFIGDEFAULT_BLOCKSIZE;
1020 /* get network related info */
1021 cm_noIPAddr = CM_MAXINTERFACE_ADDR;
1022 code = syscfg_GetIFInfo(&cm_noIPAddr,
1023 cm_IPAddr, cm_SubnetMask,
1024 cm_NetMtu, cm_NetFlags);
1026 if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
1027 afsi_log("syscfg_GetIFInfo error code %d", code);
1029 afsi_log("First Network address %x SubnetMask %x",
1030 cm_IPAddr[0], cm_SubnetMask[0]);
1033 * Save client configuration for GetCacheConfig requests
1035 cm_initParams.nChunkFiles = 0;
1036 cm_initParams.nStatCaches = stats;
1037 cm_initParams.nDataCaches = cacheBlocks;
1038 cm_initParams.nVolumeCaches = stats/2;
1039 cm_initParams.firstChunkSize = cm_chunkSize;
1040 cm_initParams.otherChunkSize = cm_chunkSize;
1041 cm_initParams.cacheSize = cacheSize;
1042 cm_initParams.setTime = 0;
1043 cm_initParams.memCache = 1;
1045 /* Set RX parameters before initializing RX */
1048 afsi_log("rx_SetNoJumbo successful");
1051 if ( rx_mtu != -1 ) {
1052 rx_SetMaxMTU(rx_mtu);
1053 afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
1056 /* Open Microsoft Firewall to allow in port 7001 */
1057 icf_CheckAndAddAFSPorts(AFS_PORTSET_CLIENT);
1059 /* Ensure the AFS Netbios Name is registered to allow loopback access */
1060 configureBackConnectionHostNames();
1062 /* init user daemon, and other packages */
1075 code = cm_InitMappedMemory(virtualCache, cm_CachePath, stats, cm_chunkSize, cacheBlocks);
1076 afsi_log("cm_InitMappedMemory code %x", code);
1078 *reasonP = "error initializing cache file";
1082 #ifdef AFS_AFSDB_ENV
1083 #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
1084 if (cm_InitDNS(cm_dnsEnabled) == -1)
1085 cm_dnsEnabled = 0; /* init failed, so deactivate */
1086 afsi_log("cm_InitDNS %d", cm_dnsEnabled);
1090 /* initialize RX, and tell it to listen to port 7001, which is used for
1091 * callback RPC messages.
1093 code = rx_Init(htons(7001));
1094 afsi_log("rx_Init code %x", code);
1096 *reasonP = "afsd: failed to init rx client on port 7001";
1100 /* create an unauthenticated service #1 for callbacks */
1101 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1102 serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
1103 RXAFSCB_ExecuteRequest);
1104 afsi_log("rx_NewService addr %x", (int)serverp);
1105 if (serverp == NULL) {
1106 *reasonP = "unknown error";
1110 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1111 serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
1112 &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
1113 afsi_log("rx_NewService addr %x", (int)serverp);
1114 if (serverp == NULL) {
1115 *reasonP = "unknown error";
1119 /* start server threads, *not* donating this one to the pool */
1121 afsi_log("rx_StartServer");
1123 code = cm_GetRootCellName(rootCellName);
1124 afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s",
1125 code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
1126 if (code != 0 && !cm_freelanceEnabled)
1128 *reasonP = "can't find root cell name in afsd.ini";
1131 else if (cm_freelanceEnabled)
1132 cm_data.rootCellp = NULL;
1134 if (code == 0 && !cm_freelanceEnabled)
1136 cm_data.rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
1137 afsi_log("cm_GetCell addr %x", (int)cm_data.rootCellp);
1138 if (cm_data.rootCellp == NULL)
1140 *reasonP = "can't find root cell in afsdcell.ini";
1145 #ifdef AFS_FREELANCE_CLIENT
1146 if (cm_freelanceEnabled)
1150 /* Initialize the RPC server for session keys */
1154 afsd_InitServerPreferences();
1159 int afsd_InitDaemons(char **reasonP)
1166 /* this should really be in an init daemon from here on down */
1168 if (!cm_freelanceEnabled) {
1169 osi_Log0(afsd_logp, "Loading Root Volume from cell");
1170 code = cm_GetVolumeByName(cm_data.rootCellp, cm_rootVolumeName, cm_rootUserp,
1171 &req, CM_FLAG_CREATE, &cm_data.rootVolumep);
1172 afsi_log("cm_GetVolumeByName code %x root vol %x", code,
1173 (code ? (cm_volume_t *)-1 : cm_data.rootVolumep));
1175 *reasonP = "can't find root volume in root cell";
1180 /* compute the root fid */
1181 if (!cm_freelanceEnabled) {
1182 cm_data.rootFid.cell = cm_data.rootCellp->cellID;
1183 cm_data.rootFid.volume = cm_GetROVolumeID(cm_data.rootVolumep);
1184 cm_data.rootFid.vnode = 1;
1185 cm_data.rootFid.unique = 1;
1188 cm_FakeRootFid(&cm_data.rootFid);
1190 code = cm_GetSCache(&cm_data.rootFid, &cm_data.rootSCachep, cm_rootUserp, &req);
1191 afsi_log("cm_GetSCache code %x scache %x", code,
1192 (code ? (cm_scache_t *)-1 : cm_data.rootSCachep));
1194 *reasonP = "unknown error";
1198 cm_InitDaemon(numBkgD);
1199 afsi_log("cm_InitDaemon complete");
1204 int afsd_InitSMB(char **reasonP, void *aMBfunc)
1211 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1212 0, KEY_QUERY_VALUE, &parmKey);
1213 if (code == ERROR_SUCCESS) {
1214 dummyLen = sizeof(DWORD);
1215 code = RegQueryValueEx(parmKey, "StoreAnsiFilenames", NULL, NULL,
1216 (BYTE *) &dwValue, &dummyLen);
1217 if (code == ERROR_SUCCESS)
1218 smb_StoreAnsiFilenames = dwValue ? 1 : 0;
1219 RegCloseKey (parmKey);
1222 /* Do this last so that we don't handle requests before init is done.
1223 * Here we initialize the SMB listener.
1225 smb_Init(afsd_logp, cm_NetbiosName, smb_UseV3, LANadapter, numSvThreads, aMBfunc);
1226 afsi_log("smb_Init complete");
1239 #pragma pack( push, before_imagehlp, 8 )
1240 #include <imagehlp.h>
1241 #pragma pack( pop, before_imagehlp )
1243 #define MAXNAMELEN 1024
1245 void afsd_printStack(HANDLE hThread, CONTEXT *c)
1247 HANDLE hProcess = GetCurrentProcess();
1251 char functionName[MAXNAMELEN];
1253 IMAGEHLP_MODULE Module;
1257 IMAGEHLP_SYMBOL *pSym;
1259 afsi_log_useTimestamp = 0;
1261 pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
1263 memset( &s, '\0', sizeof s );
1264 if (!SymInitialize(hProcess, NULL, 1) )
1266 afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
1268 SymCleanup( hProcess );
1274 symOptions = SymGetOptions();
1275 symOptions |= SYMOPT_LOAD_LINES;
1276 symOptions &= ~SYMOPT_UNDNAME;
1277 SymSetOptions( symOptions );
1280 * init STACKFRAME for first call
1281 * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
1282 * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
1283 * and good riddance.
1285 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
1286 #error The STACKFRAME initialization in afsd_printStack() for this platform
1287 #error must be properly configured
1289 s.AddrPC.Offset = c->Eip;
1290 s.AddrPC.Mode = AddrModeFlat;
1291 s.AddrFrame.Offset = c->Ebp;
1292 s.AddrFrame.Mode = AddrModeFlat;
1295 memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
1296 pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
1297 pSym->MaxNameLength = MAXNAMELEN;
1299 memset( &Line, '\0', sizeof Line );
1300 Line.SizeOfStruct = sizeof Line;
1302 memset( &Module, '\0', sizeof Module );
1303 Module.SizeOfStruct = sizeof Module;
1307 afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
1309 for ( frameNum = 0; ; ++ frameNum )
1312 * get next stack frame (StackWalk(), SymFunctionTableAccess(),
1313 * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
1314 * ERROR_NOACCESS (998), you can assume that either you are done, or
1315 * that the stack is so hosed that the next deeper frame could not be
1318 if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c,
1319 NULL, SymFunctionTableAccess, SymGetModuleBase,
1323 /* display its contents */
1324 afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
1325 frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
1326 s.AddrPC.Offset, s.AddrReturn.Offset,
1327 s.AddrFrame.Offset, s.AddrStack.Offset );
1329 if ( s.AddrPC.Offset == 0 )
1331 afsi_log("(-nosymbols- PC == 0)" );
1335 /* show procedure info from a valid PC */
1336 if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
1338 if ( GetLastError() != ERROR_INVALID_ADDRESS )
1340 afsi_log("SymGetSymFromAddr(): errno = %lu",
1346 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN,
1348 afsi_log("%s", functionName );
1352 afsi_log(" %+ld bytes", (long) offset);
1356 if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
1358 if (GetLastError() != ERROR_INVALID_ADDRESS)
1360 afsi_log("Error: SymGetLineFromAddr(): errno = %lu",
1366 afsi_log(" Line: %s(%lu) %+ld bytes", Line.FileName,
1367 Line.LineNumber, offset);
1371 /* no return address means no deeper stackframe */
1372 if (s.AddrReturn.Offset == 0)
1379 if (GetLastError() != 0)
1381 afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
1384 SymCleanup(hProcess);
1389 static DWORD *afsd_crtDbgBreakCurrent = NULL;
1390 static DWORD afsd_crtDbgBreaks[256];
1393 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
1397 BOOL allocRequestBrk = FALSE;
1400 afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n",
1401 ep->ExceptionRecord->ExceptionCode,
1402 ep->ExceptionRecord->ExceptionAddress);
1405 if (afsd_crtDbgBreakCurrent &&
1406 *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
1408 allocRequestBrk = TRUE;
1409 afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
1413 /* save context if we want to print the stack information */
1414 context = *ep->ContextRecord;
1416 afsd_printStack(GetCurrentThread(), &context);
1418 if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
1420 afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
1423 if (allocRequestBrk)
1425 afsd_crtDbgBreakCurrent++;
1426 _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
1430 ep->ContextRecord->Eip++;
1431 return EXCEPTION_CONTINUE_EXECUTION;
1435 return EXCEPTION_CONTINUE_SEARCH;
1439 void afsd_SetUnhandledExceptionFilter()
1441 SetUnhandledExceptionFilter(afsd_ExceptionFilter);
1445 void afsd_DbgBreakAllocInit()
1447 memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
1448 afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
1451 void afsd_DbgBreakAdd(DWORD requestNumber)
1454 for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
1456 if (afsd_crtDbgBreaks[i] == -1)
1461 afsd_crtDbgBreaks[i] = requestNumber;
1463 _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);