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
269 PBYTE pHostNames = NULL, pName = NULL;
270 BOOL bNameFound = FALSE;
272 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
273 "SYSTEM\\CurrentControlSet\\Control\\Lsa\\MSV1_0",
276 &hkMSV10) == ERROR_SUCCESS )
278 if (RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0, &dwType, NULL, &dwSize) == ERROR_SUCCESS) {
279 pHostNames = malloc(dwSize + strlen(cm_NetbiosName) + 1);
280 RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0, &dwType, pHostNames, &dwSize);
282 for (pName = pHostNames; *pName ; pName += strlen(pName) + 1)
284 if ( !stricmp(pName, cm_NetbiosName) ) {
292 int size = strlen(cm_NetbiosName) + 2;
294 pHostNames = malloc(size);
298 StringCbCopyA(pName, size, cm_NetbiosName);
300 *pName = '\0'; /* add a second nul terminator */
302 dwType = REG_MULTI_SZ;
303 dwSize += strlen(cm_NetbiosName) + 1;
304 RegSetValueEx( hkMSV10, "BackConnectionHostNames", 0, dwType, pHostNames, dwSize);
306 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
307 "SYSTEM\\CurrentControlSet\\Control\\Lsa",
310 &hkLsa) == ERROR_SUCCESS )
312 dwSize = sizeof(DWORD);
313 if ( RegQueryValueEx( hkLsa, "DisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) != ERROR_SUCCESS ||
316 dwSize = sizeof(DWORD);
318 RegSetValueEx( hkLsa, "DisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
320 if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
321 AFSREG_CLT_OPENAFS_SUBKEY,
324 REG_OPTION_NON_VOLATILE,
328 NULL) == ERROR_SUCCESS) {
331 dwSize = sizeof(DWORD);
333 RegSetValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
334 RegCloseKey(hkClient);
340 if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
341 AFSREG_CLT_OPENAFS_SUBKEY,
344 REG_OPTION_NON_VOLATILE,
348 NULL) == ERROR_SUCCESS) {
350 dwSize = sizeof(DWORD);
351 if ( RegQueryValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) == ERROR_SUCCESS &&
353 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
354 "SYSTEM\\CurrentControlSet\\Control\\Lsa",
357 &hkLsa) == ERROR_SUCCESS )
359 RegDeleteValue(hkLsa, "DisableLoopbackCheck");
363 RegDeleteValue(hkClient, "RemoveDisableLoopbackCheck");
364 RegCloseKey(hkClient);
367 RegCloseKey(hkMSV10);
372 static void afsd_InitServerPreferences(void)
375 DWORD dwType, dwSize;
379 DWORD dwHostSize = 256;
381 struct sockaddr_in saddr;
384 if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
385 AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\VLDB",
387 KEY_READ|KEY_QUERY_VALUE,
388 &hkPrefs) == ERROR_SUCCESS) {
390 RegQueryInfoKey( hkPrefs,
393 NULL, /* lpReserved */
394 NULL, /* lpcSubKeys */
395 NULL, /* lpcMaxSubKeyLen */
396 NULL, /* lpcMaxClassLen */
397 &dwPrefs, /* lpcValues */
398 NULL, /* lpcMaxValueNameLen */
399 NULL, /* lpcMaxValueLen */
400 NULL, /* lpcbSecurityDescriptor */
401 NULL /* lpftLastWriteTime */
404 for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
406 dwSize = sizeof(DWORD);
409 if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
410 &dwType, (LPBYTE)&dwRank, &dwSize))
412 afsi_log("RegEnumValue(hkPrefs) failed");
416 afsi_log("VLDB Server Preference: %s = %d",szHost, dwRank);
418 if (isdigit(szHost[0]))
420 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
424 if ((pEntry = gethostbyname (szHost)) == NULL)
427 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
429 saddr.sin_family = AF_INET;
430 dwRank += (rand() & 0x000f);
432 tsp = cm_FindServer(&saddr, CM_SERVER_VLDB);
433 if ( tsp ) /* an existing server - ref count increased */
435 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
437 /* set preferences for an existing vlserver */
438 cm_ChangeRankCellVLServer(tsp);
439 cm_PutServer(tsp); /* decrease refcount */
441 else /* add a new server without a cell */
443 tsp = cm_NewServer(&saddr, CM_SERVER_VLDB, NULL); /* refcount = 1 */
444 tsp->ipRank = (USHORT)dwRank;
448 RegCloseKey(hkPrefs);
451 if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
452 AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\File",
454 KEY_READ|KEY_QUERY_VALUE,
455 &hkPrefs) == ERROR_SUCCESS) {
457 RegQueryInfoKey( hkPrefs,
460 NULL, /* lpReserved */
461 NULL, /* lpcSubKeys */
462 NULL, /* lpcMaxSubKeyLen */
463 NULL, /* lpcMaxClassLen */
464 &dwPrefs, /* lpcValues */
465 NULL, /* lpcMaxValueNameLen */
466 NULL, /* lpcMaxValueLen */
467 NULL, /* lpcbSecurityDescriptor */
468 NULL /* lpftLastWriteTime */
471 for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
473 dwSize = sizeof(DWORD);
476 if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
477 &dwType, (LPBYTE)&dwRank, &dwSize))
479 afsi_log("RegEnumValue(hkPrefs) failed");
483 afsi_log("File Server Preference: %s = %d",szHost, dwRank);
485 if (isdigit(szHost[0]))
487 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
491 if ((pEntry = gethostbyname (szHost)) == NULL)
494 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
496 saddr.sin_family = AF_INET;
497 dwRank += (rand() & 0x000f);
499 tsp = cm_FindServer(&saddr, CM_SERVER_FILE);
500 if ( tsp ) /* an existing server - ref count increased */
502 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
504 /* find volumes which might have RO copy
505 /* on server and change the ordering of
508 cm_ChangeRankVolume(tsp);
509 cm_PutServer(tsp); /* decrease refcount */
511 else /* add a new server without a cell */
513 tsp = cm_NewServer(&saddr, CM_SERVER_FILE, NULL); /* refcount = 1 */
514 tsp->ipRank = (USHORT)dwRank;
518 RegCloseKey(hkPrefs);
524 * AFSD Initialization
527 int afsd_InitCM(char **reasonP)
537 long rx_mtu, rx_nojumbo;
538 long virtualCache = 0;
539 char rootCellName[256];
540 struct rx_service *serverp;
541 static struct rx_securityClass *nullServerSecurityClassp;
549 /*int freelanceEnabled;*/
551 lana_number_t lanaNum;
554 int cm_noIPAddr; /* number of client network interfaces */
555 int cm_IPAddr[CM_MAXINTERFACE_ADDR]; /* client's IP address in host order */
556 int cm_SubnetMask[CM_MAXINTERFACE_ADDR];/* client's subnet mask in host order*/
557 int cm_NetMtu[CM_MAXINTERFACE_ADDR]; /* client's MTU sizes */
558 int cm_NetFlags[CM_MAXINTERFACE_ADDR]; /* network flags */
560 WSAStartup(0x0101, &WSAjunk);
562 afsd_initUpperCaseTable();
564 /* setup osidebug server at RPC slot 1000 */
565 osi_LongToUID(1000, &debugID);
566 code = osi_InitDebug(&debugID);
567 afsi_log("osi_InitDebug code %d", code);
569 // osi_LockTypeSetDefault("stat"); /* comment this out for speed *
571 *reasonP = "unknown error";
576 gethostname(cm_HostName, sizeof(cm_HostName));
577 afsi_log("gethostname %s", cm_HostName);
578 thp = gethostbyname(cm_HostName);
579 memcpy(&cm_HostAddr, thp->h_addr_list[0], 4);
581 /* seed random number generator */
582 srand(ntohl(cm_HostAddr));
584 /* Look up configuration parameters in Registry */
585 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
586 0, KEY_QUERY_VALUE, &parmKey);
587 if (code != ERROR_SUCCESS) {
588 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
589 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
590 NULL, code, 0, (LPTSTR)&msgBuf, 0, NULL);
591 StringCbPrintfA(buf, sizeof(buf),
592 "Failure in configuration while opening Registry: %s",
594 osi_panic(buf, __FILE__, __LINE__);
597 dummyLen = sizeof(maxcpus);
598 code = RegQueryValueEx(parmKey, "MaxCPUs", NULL, NULL,
599 (BYTE *) &maxcpus, &dummyLen);
600 if (code == ERROR_SUCCESS) {
602 DWORD_PTR processAffinityMask, systemAffinityMask;
604 hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION,
605 FALSE, GetCurrentProcessId());
606 if ( hProcess != NULL &&
607 GetProcessAffinityMask(hProcess, &processAffinityMask, &systemAffinityMask) )
610 DWORD_PTR mask, newAffinityMask;
617 for ( i=0, n=0, mask=1, newAffinityMask=0; i<bits && n<maxcpus; i++ ) {
618 if ( processAffinityMask & mask ) {
619 newAffinityMask |= mask;
625 SetProcessAffinityMask(hProcess, newAffinityMask);
626 CloseHandle(hProcess);
627 afsi_log("CPU Restrictions set to %d cpu(s); %d cpu(s) available", maxcpus, n);
629 afsi_log("CPU Restrictions set to %d cpu(s); unable to access process information", maxcpus);
633 dummyLen = sizeof(TraceOption);
634 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
635 (BYTE *) &TraceOption, &dummyLen);
636 afsi_log("Event Log Tracing = %lX", TraceOption);
638 dummyLen = sizeof(traceBufSize);
639 code = RegQueryValueEx(parmKey, "TraceBufferSize", NULL, NULL,
640 (BYTE *) &traceBufSize, &dummyLen);
641 if (code == ERROR_SUCCESS)
642 afsi_log("Trace Buffer size %d", traceBufSize);
644 traceBufSize = CM_CONFIGDEFAULT_TRACEBUFSIZE;
645 afsi_log("Default trace buffer size %d", traceBufSize);
648 /* setup and enable debug log */
649 afsd_logp = osi_LogCreate("afsd", traceBufSize);
650 afsi_log("osi_LogCreate log addr %x", (int)afsd_logp);
651 osi_LogEnable(afsd_logp);
654 osi_Log0(afsd_logp, "Log init");
656 dummyLen = sizeof(cacheSize);
657 code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
658 (BYTE *) &cacheSize, &dummyLen);
659 if (code == ERROR_SUCCESS)
660 afsi_log("Cache size %d", cacheSize);
662 cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
663 afsi_log("Default cache size %d", cacheSize);
666 dummyLen = sizeof(logChunkSize);
667 code = RegQueryValueEx(parmKey, "ChunkSize", NULL, NULL,
668 (BYTE *) &logChunkSize, &dummyLen);
669 if (code == ERROR_SUCCESS) {
670 if (logChunkSize < 12 || logChunkSize > 30) {
671 afsi_log("Invalid chunk size %d, using default",
673 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
675 afsi_log("Chunk size %d", logChunkSize);
677 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
678 afsi_log("Default chunk size %d", logChunkSize);
680 cm_logChunkSize = logChunkSize;
681 cm_chunkSize = 1 << logChunkSize;
683 dummyLen = sizeof(numBkgD);
684 code = RegQueryValueEx(parmKey, "Daemons", NULL, NULL,
685 (BYTE *) &numBkgD, &dummyLen);
686 if (code == ERROR_SUCCESS)
687 afsi_log("%d background daemons", numBkgD);
689 numBkgD = CM_CONFIGDEFAULT_DAEMONS;
690 afsi_log("Defaulting to %d background daemons", numBkgD);
693 dummyLen = sizeof(numSvThreads);
694 code = RegQueryValueEx(parmKey, "ServerThreads", NULL, NULL,
695 (BYTE *) &numSvThreads, &dummyLen);
696 if (code == ERROR_SUCCESS)
697 afsi_log("%d server threads", numSvThreads);
699 numSvThreads = CM_CONFIGDEFAULT_SVTHREADS;
700 afsi_log("Defaulting to %d server threads", numSvThreads);
703 dummyLen = sizeof(stats);
704 code = RegQueryValueEx(parmKey, "Stats", NULL, NULL,
705 (BYTE *) &stats, &dummyLen);
706 if (code == ERROR_SUCCESS)
707 afsi_log("Status cache size %d", stats);
709 stats = CM_CONFIGDEFAULT_STATS;
710 afsi_log("Default status cache size %d", stats);
713 dummyLen = sizeof(ltt);
714 code = RegQueryValueEx(parmKey, "LogoffTokenTransfer", NULL, NULL,
715 (BYTE *) <t, &dummyLen);
716 if (code == ERROR_SUCCESS)
717 afsi_log("Logoff token transfer %s", (ltt ? "on" : "off"));
720 afsi_log("Logoff token transfer on by default");
722 smb_LogoffTokenTransfer = ltt;
723 afsi_log("Logoff token transfer is currently ignored");
726 dummyLen = sizeof(ltto);
727 code = RegQueryValueEx(parmKey, "LogoffTokenTransferTimeout",
728 NULL, NULL, (BYTE *) <to, &dummyLen);
729 if (code == ERROR_SUCCESS)
730 afsi_log("Logoff token tranfer timeout %d seconds", ltto);
733 afsi_log("Default logoff token transfer timeout 10 seconds");
738 smb_LogoffTransferTimeout = ltto;
739 afsi_log("Default logoff token is currently ignored");
741 dummyLen = sizeof(cm_rootVolumeName);
742 code = RegQueryValueEx(parmKey, "RootVolume", NULL, NULL,
743 cm_rootVolumeName, &dummyLen);
744 if (code == ERROR_SUCCESS)
745 afsi_log("Root volume %s", cm_rootVolumeName);
747 StringCbCopyA(cm_rootVolumeName, sizeof(cm_rootVolumeName), "root.afs");
748 afsi_log("Default root volume name root.afs");
751 cm_mountRootLen = sizeof(cm_mountRoot);
752 code = RegQueryValueEx(parmKey, "MountRoot", NULL, NULL,
753 cm_mountRoot, &cm_mountRootLen);
754 if (code == ERROR_SUCCESS) {
755 afsi_log("Mount root %s", cm_mountRoot);
756 cm_mountRootLen = strlen(cm_mountRoot);
758 StringCbCopyA(cm_mountRoot, sizeof(cm_mountRoot), "/afs");
763 dummyLen = sizeof(buf);
764 code = RegQueryValueEx(parmKey, "CachePath", NULL, ®Type,
766 if (code == ERROR_SUCCESS && buf[0]) {
767 if (regType == REG_EXPAND_SZ) {
768 dummyLen = ExpandEnvironmentStrings(buf, cm_CachePath, sizeof(cm_CachePath));
769 if (dummyLen > sizeof(cm_CachePath)) {
770 afsi_log("Cache path [%s] longer than %d after expanding env strings", buf, sizeof(cm_CachePath));
771 osi_panic("CachePath too long", __FILE__, __LINE__);
774 StringCbCopyA(cm_CachePath, sizeof(cm_CachePath), buf);
776 afsi_log("Cache path %s", cm_CachePath);
778 dummyLen = ExpandEnvironmentStrings("%TEMP%\\AFSCache", cm_CachePath, sizeof(cm_CachePath));
779 if (dummyLen > sizeof(cm_CachePath)) {
780 afsi_log("Cache path [%%TEMP%%\\AFSCache] longer than %d after expanding env strings",
781 sizeof(cm_CachePath));
782 osi_panic("CachePath too long", __FILE__, __LINE__);
784 afsi_log("Default cache path %s", cm_CachePath);
787 dummyLen = sizeof(virtualCache);
788 code = RegQueryValueEx(parmKey, "NonPersistentCaching", NULL, NULL,
789 (LPBYTE)&virtualCache, &dummyLen);
790 afsi_log("Cache type is %s", (virtualCache?"VIRTUAL":"FILE"));
793 dummyLen = sizeof(cm_ValidateCache);
794 code = RegQueryValueEx(parmKey, "ValidateCache", NULL, NULL,
795 (LPBYTE)&cm_ValidateCache, &dummyLen);
796 if ( cm_ValidateCache < 0 || cm_ValidateCache > 2 )
797 cm_ValidateCache = 1;
798 switch (cm_ValidateCache) {
800 afsi_log("Cache Validation disabled");
803 afsi_log("Cache Validation on Startup");
806 afsi_log("Cache Validation on Startup and Shutdown");
811 dummyLen = sizeof(traceOnPanic);
812 code = RegQueryValueEx(parmKey, "TrapOnPanic", NULL, NULL,
813 (BYTE *) &traceOnPanic, &dummyLen);
814 if (code == ERROR_SUCCESS)
815 afsi_log("Set to %s on panic",
816 traceOnPanic ? "trap" : "not trap");
822 dummyLen = sizeof(reportSessionStartups);
823 code = RegQueryValueEx(parmKey, "ReportSessionStartups", NULL, NULL,
824 (BYTE *) &reportSessionStartups, &dummyLen);
825 if (code == ERROR_SUCCESS)
826 afsi_log("Session startups %s be recorded in the Event Log",
827 reportSessionStartups ? "will" : "will not");
829 reportSessionStartups = 0;
833 for ( i=0; i < MAXNUMSYSNAMES; i++ ) {
834 cm_sysNameList[i] = osi_Alloc(MAXSYSNAME);
835 cm_sysNameList[i][0] = '\0';
837 cm_sysName = cm_sysNameList[0];
839 dummyLen = sizeof(buf);
840 code = RegQueryValueEx(parmKey, "SysName", NULL, NULL, buf, &dummyLen);
841 if (code != ERROR_SUCCESS || !buf[0]) {
843 StringCbCopyA(buf, sizeof(buf), "ia64_win64");
844 #elif defined(_AMD64)
845 StringCbCopyA(buf, sizeof(buf), "amd64_win64");
846 #else /* assume x86 32-bit */
847 StringCbCopyA(buf, sizeof(buf), "x86_win32 i386_w2k i386_nt40");
850 afsi_log("Sys name %s", buf);
852 /* breakup buf into individual search string entries */
853 for (p = q = buf; p < buf + dummyLen; p++)
855 if (*p == '\0' || isspace(*p)) {
856 memcpy(cm_sysNameList[cm_sysNameCount],q,p-q);
857 cm_sysNameList[cm_sysNameCount][p-q] = '\0';
864 } while (*p == '\0' || isspace(*p));
870 StringCbCopyA(cm_sysName, MAXSYSNAME, cm_sysNameList[0]);
872 dummyLen = sizeof(cryptall);
873 code = RegQueryValueEx(parmKey, "SecurityLevel", NULL, NULL,
874 (BYTE *) &cryptall, &dummyLen);
875 if (code == ERROR_SUCCESS) {
876 afsi_log("SecurityLevel is %s", cryptall?"crypt":"clear");
879 afsi_log("Default SecurityLevel is clear");
883 dummyLen = sizeof(cm_dnsEnabled);
884 code = RegQueryValueEx(parmKey, "UseDNS", NULL, NULL,
885 (BYTE *) &cm_dnsEnabled, &dummyLen);
886 if (code == ERROR_SUCCESS) {
887 afsi_log("DNS %s be used to find AFS cell servers",
888 cm_dnsEnabled ? "will" : "will not");
891 cm_dnsEnabled = 1; /* default on */
892 afsi_log("Default to use DNS to find AFS cell servers");
894 #else /* AFS_AFSDB_ENV */
895 afsi_log("AFS not built with DNS support to find AFS cell servers");
896 #endif /* AFS_AFSDB_ENV */
898 #ifdef AFS_FREELANCE_CLIENT
899 dummyLen = sizeof(cm_freelanceEnabled);
900 code = RegQueryValueEx(parmKey, "FreelanceClient", NULL, NULL,
901 (BYTE *) &cm_freelanceEnabled, &dummyLen);
902 if (code == ERROR_SUCCESS) {
903 afsi_log("Freelance client feature %s activated",
904 cm_freelanceEnabled ? "is" : "is not");
907 cm_freelanceEnabled = 0; /* default off */
909 #endif /* AFS_FREELANCE_CLIENT */
912 /* The netbios name is looked up in lana_GetUNCServerNameEx */
913 dummyLen = sizeof(buf);
914 code = RegQueryValueEx(parmKey, "NetbiosName", NULL, NULL,
915 (BYTE *) &buf, &dummyLen);
916 if (code == ERROR_SUCCESS) {
917 DWORD len = ExpandEnvironmentStrings(buf, cm_NetbiosName, MAX_NB_NAME_LENGTH);
918 if ( len > 0 && len <= MAX_NB_NAME_LENGTH ) {
919 afsi_log("Explicit NetBios name is used %s", cm_NetbiosName);
921 afsi_log("Unable to Expand Explicit NetBios name: %s", buf);
922 cm_NetbiosName[0] = 0; /* turn it off */
926 cm_NetbiosName[0] = 0; /* default off */
930 dummyLen = sizeof(smb_hideDotFiles);
931 code = RegQueryValueEx(parmKey, "HideDotFiles", NULL, NULL,
932 (BYTE *) &smb_hideDotFiles, &dummyLen);
933 if (code != ERROR_SUCCESS) {
934 smb_hideDotFiles = 1; /* default on */
936 afsi_log("Dot files/dirs will %sbe marked hidden",
937 smb_hideDotFiles ? "" : "not ");
939 dummyLen = sizeof(smb_maxMpxRequests);
940 code = RegQueryValueEx(parmKey, "MaxMpxRequests", NULL, NULL,
941 (BYTE *) &smb_maxMpxRequests, &dummyLen);
942 if (code != ERROR_SUCCESS) {
943 smb_maxMpxRequests = 50;
945 afsi_log("Maximum number of multiplexed sessions is %d", smb_maxMpxRequests);
947 dummyLen = sizeof(smb_maxVCPerServer);
948 code = RegQueryValueEx(parmKey, "MaxVCPerServer", NULL, NULL,
949 (BYTE *) &smb_maxVCPerServer, &dummyLen);
950 if (code != ERROR_SUCCESS) {
951 smb_maxVCPerServer = 100;
953 afsi_log("Maximum number of VCs per server is %d", smb_maxVCPerServer);
955 dummyLen = sizeof(smb_authType);
956 code = RegQueryValueEx(parmKey, "SMBAuthType", NULL, NULL,
957 (BYTE *) &smb_authType, &dummyLen);
959 if (code != ERROR_SUCCESS ||
960 (smb_authType != SMB_AUTH_EXTENDED && smb_authType != SMB_AUTH_NTLM && smb_authType != SMB_AUTH_NONE)) {
961 smb_authType = SMB_AUTH_EXTENDED; /* default is to use extended authentication */
963 afsi_log("SMB authentication type is %s", ((smb_authType == SMB_AUTH_NONE)?"NONE":((smb_authType == SMB_AUTH_EXTENDED)?"EXTENDED":"NTLM")));
965 dummyLen = sizeof(rx_nojumbo);
966 code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
967 (BYTE *) &rx_nojumbo, &dummyLen);
968 if (code != ERROR_SUCCESS) {
972 afsi_log("RX Jumbograms are disabled");
974 dummyLen = sizeof(rx_mtu);
975 code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
976 (BYTE *) &rx_mtu, &dummyLen);
977 if (code != ERROR_SUCCESS || !rx_mtu) {
981 afsi_log("RX maximum MTU is %d", rx_mtu);
983 dummyLen = sizeof(ConnDeadtimeout);
984 code = RegQueryValueEx(parmKey, "ConnDeadTimeout", NULL, NULL,
985 (BYTE *) &ConnDeadtimeout, &dummyLen);
986 afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
988 dummyLen = sizeof(HardDeadtimeout);
989 code = RegQueryValueEx(parmKey, "HardDeadTimeout", NULL, NULL,
990 (BYTE *) &HardDeadtimeout, &dummyLen);
991 afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
993 RegCloseKey (parmKey);
995 /* Call lanahelper to get Netbios name, lan adapter number and gateway flag */
996 if (SUCCEEDED(code = lana_GetUncServerNameEx(cm_NetbiosName, &lanaNum, &isGateway, LANA_NETBIOS_NAME_FULL))) {
997 LANadapter = (lanaNum == LANA_INVALID)? -1: lanaNum;
999 if (LANadapter != -1)
1000 afsi_log("LAN adapter number %d", LANadapter);
1002 afsi_log("LAN adapter number not determined");
1005 afsi_log("Set for gateway service");
1007 afsi_log("Using >%s< as SMB server name", cm_NetbiosName);
1009 /* something went horribly wrong. We can't proceed without a netbios name */
1010 StringCbPrintfA(buf,sizeof(buf),"Netbios name could not be determined: %li", code);
1011 osi_panic(buf, __FILE__, __LINE__);
1014 cacheBlocks = (cacheSize * 1024) / CM_CONFIGDEFAULT_BLOCKSIZE;
1016 /* get network related info */
1017 cm_noIPAddr = CM_MAXINTERFACE_ADDR;
1018 code = syscfg_GetIFInfo(&cm_noIPAddr,
1019 cm_IPAddr, cm_SubnetMask,
1020 cm_NetMtu, cm_NetFlags);
1022 if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
1023 afsi_log("syscfg_GetIFInfo error code %d", code);
1025 afsi_log("First Network address %x SubnetMask %x",
1026 cm_IPAddr[0], cm_SubnetMask[0]);
1029 * Save client configuration for GetCacheConfig requests
1031 cm_initParams.nChunkFiles = 0;
1032 cm_initParams.nStatCaches = stats;
1033 cm_initParams.nDataCaches = cacheBlocks;
1034 cm_initParams.nVolumeCaches = stats/2;
1035 cm_initParams.firstChunkSize = cm_chunkSize;
1036 cm_initParams.otherChunkSize = cm_chunkSize;
1037 cm_initParams.cacheSize = cacheSize;
1038 cm_initParams.setTime = 0;
1039 cm_initParams.memCache = 1;
1041 /* Set RX parameters before initializing RX */
1044 afsi_log("rx_SetNoJumbo successful");
1047 if ( rx_mtu != -1 ) {
1048 rx_SetMaxMTU(rx_mtu);
1049 afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
1052 /* Open Microsoft Firewall to allow in port 7001 */
1053 icf_CheckAndAddAFSPorts(AFS_PORTSET_CLIENT);
1055 /* Ensure the AFS Netbios Name is registered to allow loopback access */
1056 configureBackConnectionHostNames();
1058 /* init user daemon, and other packages */
1071 code = cm_InitMappedMemory(virtualCache, cm_CachePath, stats, cm_chunkSize, cacheBlocks);
1072 afsi_log("cm_InitMappedMemory code %x", code);
1074 *reasonP = "error initializing cache file";
1078 #ifdef AFS_AFSDB_ENV
1079 #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
1080 if (cm_InitDNS(cm_dnsEnabled) == -1)
1081 cm_dnsEnabled = 0; /* init failed, so deactivate */
1082 afsi_log("cm_InitDNS %d", cm_dnsEnabled);
1086 /* initialize RX, and tell it to listen to port 7001, which is used for
1087 * callback RPC messages.
1089 code = rx_Init(htons(7001));
1090 afsi_log("rx_Init code %x", code);
1092 *reasonP = "afsd: failed to init rx client on port 7001";
1096 /* create an unauthenticated service #1 for callbacks */
1097 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1098 serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
1099 RXAFSCB_ExecuteRequest);
1100 afsi_log("rx_NewService addr %x", (int)serverp);
1101 if (serverp == NULL) {
1102 *reasonP = "unknown error";
1106 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1107 serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
1108 &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
1109 afsi_log("rx_NewService addr %x", (int)serverp);
1110 if (serverp == NULL) {
1111 *reasonP = "unknown error";
1115 /* start server threads, *not* donating this one to the pool */
1117 afsi_log("rx_StartServer");
1119 code = cm_GetRootCellName(rootCellName);
1120 afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s",
1121 code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
1122 if (code != 0 && !cm_freelanceEnabled)
1124 *reasonP = "can't find root cell name in afsd.ini";
1127 else if (cm_freelanceEnabled)
1128 cm_data.rootCellp = NULL;
1130 if (code == 0 && !cm_freelanceEnabled)
1132 cm_data.rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
1133 afsi_log("cm_GetCell addr %x", (int)cm_data.rootCellp);
1134 if (cm_data.rootCellp == NULL)
1136 *reasonP = "can't find root cell in afsdcell.ini";
1141 #ifdef AFS_FREELANCE_CLIENT
1142 if (cm_freelanceEnabled)
1146 /* Initialize the RPC server for session keys */
1150 afsd_InitServerPreferences();
1155 int afsd_InitDaemons(char **reasonP)
1162 /* this should really be in an init daemon from here on down */
1164 if (!cm_freelanceEnabled) {
1165 osi_Log0(afsd_logp, "Loading Root Volume from cell");
1166 code = cm_GetVolumeByName(cm_data.rootCellp, cm_rootVolumeName, cm_rootUserp,
1167 &req, CM_FLAG_CREATE, &cm_data.rootVolumep);
1168 afsi_log("cm_GetVolumeByName code %x root vol %x", code,
1169 (code ? (cm_volume_t *)-1 : cm_data.rootVolumep));
1171 *reasonP = "can't find root volume in root cell";
1176 /* compute the root fid */
1177 if (!cm_freelanceEnabled) {
1178 cm_data.rootFid.cell = cm_data.rootCellp->cellID;
1179 cm_data.rootFid.volume = cm_GetROVolumeID(cm_data.rootVolumep);
1180 cm_data.rootFid.vnode = 1;
1181 cm_data.rootFid.unique = 1;
1184 cm_FakeRootFid(&cm_data.rootFid);
1186 code = cm_GetSCache(&cm_data.rootFid, &cm_data.rootSCachep, cm_rootUserp, &req);
1187 afsi_log("cm_GetSCache code %x scache %x", code,
1188 (code ? (cm_scache_t *)-1 : cm_data.rootSCachep));
1190 *reasonP = "unknown error";
1194 cm_InitDaemon(numBkgD);
1195 afsi_log("cm_InitDaemon complete");
1200 int afsd_InitSMB(char **reasonP, void *aMBfunc)
1207 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1208 0, KEY_QUERY_VALUE, &parmKey);
1209 if (code == ERROR_SUCCESS) {
1210 dummyLen = sizeof(DWORD);
1211 code = RegQueryValueEx(parmKey, "StoreAnsiFilenames", NULL, NULL,
1212 (BYTE *) &dwValue, &dummyLen);
1213 if (code == ERROR_SUCCESS)
1214 smb_StoreAnsiFilenames = dwValue ? 1 : 0;
1215 RegCloseKey (parmKey);
1218 /* Do this last so that we don't handle requests before init is done.
1219 * Here we initialize the SMB listener.
1221 smb_Init(afsd_logp, cm_NetbiosName, smb_UseV3, LANadapter, numSvThreads, aMBfunc);
1222 afsi_log("smb_Init complete");
1235 #pragma pack( push, before_imagehlp, 8 )
1236 #include <imagehlp.h>
1237 #pragma pack( pop, before_imagehlp )
1239 #define MAXNAMELEN 1024
1241 void afsd_printStack(HANDLE hThread, CONTEXT *c)
1243 HANDLE hProcess = GetCurrentProcess();
1247 char functionName[MAXNAMELEN];
1249 IMAGEHLP_MODULE Module;
1253 IMAGEHLP_SYMBOL *pSym;
1255 afsi_log_useTimestamp = 0;
1257 pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
1259 memset( &s, '\0', sizeof s );
1260 if (!SymInitialize(hProcess, NULL, 1) )
1262 afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
1264 SymCleanup( hProcess );
1270 symOptions = SymGetOptions();
1271 symOptions |= SYMOPT_LOAD_LINES;
1272 symOptions &= ~SYMOPT_UNDNAME;
1273 SymSetOptions( symOptions );
1276 * init STACKFRAME for first call
1277 * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
1278 * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
1279 * and good riddance.
1281 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
1282 #error The STACKFRAME initialization in afsd_printStack() for this platform
1283 #error must be properly configured
1285 s.AddrPC.Offset = c->Eip;
1286 s.AddrPC.Mode = AddrModeFlat;
1287 s.AddrFrame.Offset = c->Ebp;
1288 s.AddrFrame.Mode = AddrModeFlat;
1291 memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
1292 pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
1293 pSym->MaxNameLength = MAXNAMELEN;
1295 memset( &Line, '\0', sizeof Line );
1296 Line.SizeOfStruct = sizeof Line;
1298 memset( &Module, '\0', sizeof Module );
1299 Module.SizeOfStruct = sizeof Module;
1303 afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
1305 for ( frameNum = 0; ; ++ frameNum )
1308 * get next stack frame (StackWalk(), SymFunctionTableAccess(),
1309 * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
1310 * ERROR_NOACCESS (998), you can assume that either you are done, or
1311 * that the stack is so hosed that the next deeper frame could not be
1314 if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c,
1315 NULL, SymFunctionTableAccess, SymGetModuleBase,
1319 /* display its contents */
1320 afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
1321 frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
1322 s.AddrPC.Offset, s.AddrReturn.Offset,
1323 s.AddrFrame.Offset, s.AddrStack.Offset );
1325 if ( s.AddrPC.Offset == 0 )
1327 afsi_log("(-nosymbols- PC == 0)" );
1331 /* show procedure info from a valid PC */
1332 if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
1334 if ( GetLastError() != ERROR_INVALID_ADDRESS )
1336 afsi_log("SymGetSymFromAddr(): errno = %lu",
1342 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN,
1344 afsi_log("%s", functionName );
1348 afsi_log(" %+ld bytes", (long) offset);
1352 if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
1354 if (GetLastError() != ERROR_INVALID_ADDRESS)
1356 afsi_log("Error: SymGetLineFromAddr(): errno = %lu",
1362 afsi_log(" Line: %s(%lu) %+ld bytes", Line.FileName,
1363 Line.LineNumber, offset);
1367 /* no return address means no deeper stackframe */
1368 if (s.AddrReturn.Offset == 0)
1375 if (GetLastError() != 0)
1377 afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
1380 SymCleanup(hProcess);
1385 static DWORD *afsd_crtDbgBreakCurrent = NULL;
1386 static DWORD afsd_crtDbgBreaks[256];
1389 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
1393 BOOL allocRequestBrk = FALSE;
1396 afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n",
1397 ep->ExceptionRecord->ExceptionCode,
1398 ep->ExceptionRecord->ExceptionAddress);
1401 if (afsd_crtDbgBreakCurrent &&
1402 *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
1404 allocRequestBrk = TRUE;
1405 afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
1409 /* save context if we want to print the stack information */
1410 context = *ep->ContextRecord;
1412 afsd_printStack(GetCurrentThread(), &context);
1414 if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
1416 afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
1419 if (allocRequestBrk)
1421 afsd_crtDbgBreakCurrent++;
1422 _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
1426 ep->ContextRecord->Eip++;
1427 return EXCEPTION_CONTINUE_EXECUTION;
1431 return EXCEPTION_CONTINUE_SEARCH;
1435 void afsd_SetUnhandledExceptionFilter()
1437 SetUnhandledExceptionFilter(afsd_ExceptionFilter);
1441 void afsd_DbgBreakAllocInit()
1443 memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
1444 afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
1447 void afsd_DbgBreakAdd(DWORD requestNumber)
1450 for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
1452 if (afsd_crtDbgBreaks[i] == -1)
1457 afsd_crtDbgBreaks[i] = requestNumber;
1459 _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);