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>
27 #include <rx\rx_null.h>
28 #include <WINNT/syscfg.h>
29 #include <WINNT/afsreg.h>
33 #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;
41 extern int cm_enableServerLocks;
45 cm_config_data_t cm_data;
47 char cm_rootVolumeName[VL_MAXNAMELEN];
48 DWORD cm_rootVolumeNameLen;
49 char cm_mountRoot[1024];
50 DWORD cm_mountRootLen;
53 #ifdef AFS_FREELANCE_CLIENT
55 #endif /* freelance */
68 char cm_HostName[200];
70 unsigned short cm_callbackport = CM_DEFAULT_CALLBACKPORT;
72 char cm_NetbiosName[MAX_NB_NAME_LENGTH] = "";
74 char cm_CachePath[MAX_PATH];
75 DWORD cm_CachePathLen;
76 DWORD cm_ValidateCache = 1;
78 BOOL isGateway = FALSE;
80 BOOL reportSessionStartups = FALSE;
82 cm_initparams_v1 cm_initParams;
85 unsigned int cm_sysNameCount = 0;
86 char *cm_sysNameList[MAXNUMSYSNAMES];
88 DWORD TraceOption = 0;
91 * AFSD Initialization Log
93 * This is distinct from the regular debug logging facility.
94 * Log items go directly to a file, not to an array in memory, so that even
95 * if AFSD crashes, the log can be inspected.
101 int cm_dnsEnabled = 1;
105 static int afsi_log_useTimestamp = 1;
108 afsi_log(char *pattern, ...)
110 char s[256], t[100], d[100], u[512];
113 va_start(ap, pattern);
115 StringCbVPrintfA(s, sizeof(s), pattern, ap);
116 if ( afsi_log_useTimestamp ) {
117 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
118 GetDateFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, d, sizeof(d));
119 StringCbPrintfA(u, sizeof(u), "%s %s: %s\r\n", d, t, s);
120 if (afsi_file != INVALID_HANDLE_VALUE)
121 WriteFile(afsi_file, u, (DWORD)strlen(u), &zilch, NULL);
126 if (afsi_file != INVALID_HANDLE_VALUE)
127 WriteFile(afsi_file, s, (DWORD)strlen(s), &zilch, NULL);
131 extern initUpperCaseTable();
132 void afsd_initUpperCaseTable()
134 initUpperCaseTable();
141 char t[100], u[100], *p, *path;
147 DWORD maxLogSize = 100 * 1024;
149 afsi_file = INVALID_HANDLE_VALUE;
150 code = GetEnvironmentVariable("TEMP", wd, sizeof(wd));
151 if ( code == 0 || code > sizeof(wd) )
153 code = GetWindowsDirectory(wd, sizeof(wd));
157 StringCbCatA(wd, sizeof(wd), "\\afsd_init.log");
158 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
159 afsi_file = CreateFile(wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
160 OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
162 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
163 0, KEY_QUERY_VALUE, &parmKey);
164 if (code == ERROR_SUCCESS) {
165 dummyLen = sizeof(maxLogSize);
166 code = RegQueryValueEx(parmKey, "MaxLogSize", NULL, NULL,
167 (BYTE *) &maxLogSize, &dummyLen);
168 RegCloseKey (parmKey);
172 dwLow = GetFileSize( afsi_file, &dwHigh );
173 if ( dwHigh > 0 || dwLow >= maxLogSize ) {
174 CloseHandle(afsi_file);
175 afsi_file = CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
176 CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
180 SetFilePointer(afsi_file, 0, NULL, FILE_END);
181 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, u, sizeof(u));
182 StringCbCatA(t, sizeof(t), ": Create log file\n");
183 StringCbCatA(u, sizeof(u), ": Created log file\n");
184 WriteFile(afsi_file, t, (DWORD)strlen(t), &zilch, NULL);
185 WriteFile(afsi_file, u, (DWORD)strlen(u), &zilch, NULL);
187 code = GetEnvironmentVariable("PATH", NULL, 0);
189 code = GetEnvironmentVariable("PATH", path, code);
190 WriteFile(afsi_file, p, (DWORD)strlen(p), &zilch, NULL);
191 WriteFile(afsi_file, path, (DWORD)strlen(path), &zilch, NULL);
192 WriteFile(afsi_file, "\n", (DWORD)1, &zilch, NULL);
195 /* Initialize C RTL Code Page conversion functions */
196 /* All of the path info obtained from the SMB client is in the OEM code page */
197 afsi_log("OEM Code Page = %d", GetOEMCP());
198 afsi_log("locale = %s", setlocale(LC_ALL,NULL));
200 /* Two things to look into. First, should mbstowcs() be performing
201 * character set translations from OEM to Unicode in smb3.c;
202 * Second, do we need to set this translation in each function
203 * due to multi-threading.
205 afsi_log("locale -> %s", setlocale(LC_ALL, ".OCP"));
206 afsi_log("_setmbcp = %d -> %d", _setmbcp(_MB_CP_OEM), _getmbcp());
211 * Standard AFSD trace
214 void afsd_ForceTrace(BOOL flush)
223 len = GetTempPath(sizeof(buf)-10, buf);
224 StringCbCopyA(&buf[len], sizeof(buf)-len, "/afsd.log");
225 handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
226 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
227 if (handle == INVALID_HANDLE_VALUE) {
229 osi_panic("Cannot create log file", __FILE__, __LINE__);
231 osi_LogPrint(afsd_logp, handle);
233 FlushFileBuffers(handle);
238 configureBackConnectionHostNames(void)
240 /* On Windows XP SP2, Windows 2003 SP1, and all future Windows operating systems
241 * there is a restriction on the use of SMB authentication on loopback connections.
242 * There are two work arounds available:
244 * (1) We can disable the check for matching host names. This does not
246 * [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa]
247 * "DisableLoopbackCheck"=dword:00000001
249 * (2) We can add the AFS SMB/CIFS service name to an approved list. This
250 * does require a reboot:
251 * [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0]
252 * "BackConnectionHostNames"=multi-sz
254 * The algorithm will be:
255 * (1) Check to see if cm_NetbiosName exists in the BackConnectionHostNames list
256 * (2a) If not, add it to the list. (This will not take effect until the next reboot.)
257 * (2b1) and check to see if DisableLoopbackCheck is set.
258 * (2b2) If not set, set the DisableLoopbackCheck value to 0x1
259 * (2b3) and create HKLM\SOFTWARE\OpenAFS\Client UnsetDisableLoopbackCheck
260 * (2c) else If cm_NetbiosName exists in the BackConnectionHostNames list,
261 * check for the UnsetDisableLoopbackCheck value.
262 * If set, set the DisableLoopbackCheck flag to 0x0
263 * and delete the UnsetDisableLoopbackCheck value
265 * Starting in Longhorn Beta 1, an entry in the BackConnectionHostNames value will
266 * force Windows to use the loopback authentication mechanism for the specified
273 DWORD dwSize, dwAllocSize;
275 PBYTE pHostNames = NULL, pName = NULL;
276 BOOL bNameFound = FALSE;
278 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
279 "SYSTEM\\CurrentControlSet\\Control\\Lsa\\MSV1_0",
282 &hkMSV10) == ERROR_SUCCESS )
284 if (RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0,
285 &dwType, NULL, &dwAllocSize) == ERROR_SUCCESS) {
286 dwAllocSize += 1 /* in case the source string is not nul terminated */
287 + strlen(cm_NetbiosName) + 2;
288 pHostNames = malloc(dwAllocSize);
289 dwSize = dwAllocSize;
290 if (RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0, &dwType,
291 pHostNames, &dwSize) == ERROR_SUCCESS) {
292 for (pName = pHostNames;
293 (pName - pHostNames < dwSize) && *pName ;
294 pName += strlen(pName) + 1)
296 if ( !stricmp(pName, cm_NetbiosName) ) {
305 size_t size = strlen(cm_NetbiosName) + 2;
307 pHostNames = malloc(size);
310 StringCbCopyA(pName, size, cm_NetbiosName);
312 *pName = '\0'; /* add a second nul terminator */
314 dwType = REG_MULTI_SZ;
315 dwSize = pName - pHostNames + 1;
316 RegSetValueEx( hkMSV10, "BackConnectionHostNames", 0, dwType, pHostNames, dwSize);
318 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
319 "SYSTEM\\CurrentControlSet\\Control\\Lsa",
322 &hkLsa) == ERROR_SUCCESS )
324 dwSize = sizeof(DWORD);
325 if ( RegQueryValueEx( hkLsa, "DisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) != ERROR_SUCCESS ||
328 dwSize = sizeof(DWORD);
330 RegSetValueEx( hkLsa, "DisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
332 if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
333 AFSREG_CLT_OPENAFS_SUBKEY,
336 REG_OPTION_NON_VOLATILE,
340 NULL) == ERROR_SUCCESS) {
343 dwSize = sizeof(DWORD);
345 RegSetValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
346 RegCloseKey(hkClient);
352 if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
353 AFSREG_CLT_OPENAFS_SUBKEY,
356 REG_OPTION_NON_VOLATILE,
360 NULL) == ERROR_SUCCESS) {
362 dwSize = sizeof(DWORD);
363 if ( RegQueryValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) == ERROR_SUCCESS &&
365 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
366 "SYSTEM\\CurrentControlSet\\Control\\Lsa",
369 &hkLsa) == ERROR_SUCCESS )
371 RegDeleteValue(hkLsa, "DisableLoopbackCheck");
375 RegDeleteValue(hkClient, "RemoveDisableLoopbackCheck");
376 RegCloseKey(hkClient);
379 RegCloseKey(hkMSV10);
387 static void afsd_InitServerPreferences(void)
390 DWORD dwType, dwSize;
394 DWORD dwHostSize = 256;
396 struct sockaddr_in saddr;
399 if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
400 AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\VLDB",
402 KEY_READ|KEY_QUERY_VALUE,
403 &hkPrefs) == ERROR_SUCCESS) {
405 RegQueryInfoKey( hkPrefs,
408 NULL, /* lpReserved */
409 NULL, /* lpcSubKeys */
410 NULL, /* lpcMaxSubKeyLen */
411 NULL, /* lpcMaxClassLen */
412 &dwPrefs, /* lpcValues */
413 NULL, /* lpcMaxValueNameLen */
414 NULL, /* lpcMaxValueLen */
415 NULL, /* lpcbSecurityDescriptor */
416 NULL /* lpftLastWriteTime */
419 for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
421 dwSize = sizeof(DWORD);
424 if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
425 &dwType, (LPBYTE)&dwRank, &dwSize))
427 afsi_log("RegEnumValue(hkPrefs) failed");
431 afsi_log("VLDB Server Preference: %s = %d",szHost, dwRank);
433 if (isdigit(szHost[0]))
435 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
439 if ((pEntry = gethostbyname (szHost)) == NULL)
442 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
444 saddr.sin_family = AF_INET;
445 dwRank += (rand() & 0x000f);
447 tsp = cm_FindServer(&saddr, CM_SERVER_VLDB);
448 if ( tsp ) /* an existing server - ref count increased */
450 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
452 /* set preferences for an existing vlserver */
453 cm_ChangeRankCellVLServer(tsp);
454 cm_PutServer(tsp); /* decrease refcount */
456 else /* add a new server without a cell */
458 tsp = cm_NewServer(&saddr, CM_SERVER_VLDB, NULL); /* refcount = 1 */
459 tsp->ipRank = (USHORT)dwRank;
463 RegCloseKey(hkPrefs);
466 if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
467 AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\File",
469 KEY_READ|KEY_QUERY_VALUE,
470 &hkPrefs) == ERROR_SUCCESS) {
472 RegQueryInfoKey( hkPrefs,
475 NULL, /* lpReserved */
476 NULL, /* lpcSubKeys */
477 NULL, /* lpcMaxSubKeyLen */
478 NULL, /* lpcMaxClassLen */
479 &dwPrefs, /* lpcValues */
480 NULL, /* lpcMaxValueNameLen */
481 NULL, /* lpcMaxValueLen */
482 NULL, /* lpcbSecurityDescriptor */
483 NULL /* lpftLastWriteTime */
486 for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
488 dwSize = sizeof(DWORD);
491 if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
492 &dwType, (LPBYTE)&dwRank, &dwSize))
494 afsi_log("RegEnumValue(hkPrefs) failed");
498 afsi_log("File Server Preference: %s = %d",szHost, dwRank);
500 if (isdigit(szHost[0]))
502 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
506 if ((pEntry = gethostbyname (szHost)) == NULL)
509 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
511 saddr.sin_family = AF_INET;
512 dwRank += (rand() & 0x000f);
514 tsp = cm_FindServer(&saddr, CM_SERVER_FILE);
515 if ( tsp ) /* an existing server - ref count increased */
517 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
519 /* find volumes which might have RO copy
520 /* on server and change the ordering of
523 cm_ChangeRankVolume(tsp);
524 cm_PutServer(tsp); /* decrease refcount */
526 else /* add a new server without a cell */
528 tsp = cm_NewServer(&saddr, CM_SERVER_FILE, NULL); /* refcount = 1 */
529 tsp->ipRank = (USHORT)dwRank;
533 RegCloseKey(hkPrefs);
538 * AFSD Initialization
541 int afsd_InitCM(char **reasonP)
544 afs_uint64 cacheBlocks;
549 DWORD rx_enable_peer_stats = 0;
550 DWORD rx_enable_process_stats = 0;
555 long virtualCache = 0;
556 char rootCellName[256];
557 struct rx_service *serverp;
558 static struct rx_securityClass *nullServerSecurityClassp;
566 /*int freelanceEnabled;*/
568 lana_number_t lanaNum;
571 int cm_noIPAddr; /* number of client network interfaces */
572 int cm_IPAddr[CM_MAXINTERFACE_ADDR]; /* client's IP address in host order */
573 int cm_SubnetMask[CM_MAXINTERFACE_ADDR];/* client's subnet mask in host order*/
574 int cm_NetMtu[CM_MAXINTERFACE_ADDR]; /* client's MTU sizes */
575 int cm_NetFlags[CM_MAXINTERFACE_ADDR]; /* network flags */
577 WSAStartup(0x0101, &WSAjunk);
579 afsd_initUpperCaseTable();
580 init_et_to_sys_error();
582 /* setup osidebug server at RPC slot 1000 */
583 osi_LongToUID(1000, &debugID);
584 code = osi_InitDebug(&debugID);
585 afsi_log("osi_InitDebug code %d", code);
587 // osi_LockTypeSetDefault("stat"); /* comment this out for speed */
589 if (code == RPC_S_NO_PROTSEQS)
590 *reasonP = "No RPC Protocol Sequences registered. Check HKLM\\SOFTWARE\\Microsoft\\RPC\\ClientProtocols";
592 *reasonP = "unknown error";
597 gethostname(cm_HostName, sizeof(cm_HostName));
598 afsi_log("gethostname %s", cm_HostName);
599 thp = gethostbyname(cm_HostName);
600 memcpy(&cm_HostAddr, thp->h_addr_list[0], 4);
602 /* seed random number generator */
603 srand(ntohl(cm_HostAddr));
605 /* Look up configuration parameters in Registry */
606 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
607 0, KEY_QUERY_VALUE, &parmKey);
608 if (code != ERROR_SUCCESS) {
609 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
610 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
611 NULL, code, 0, (LPTSTR)&msgBuf, 0, NULL);
612 StringCbPrintfA(buf, sizeof(buf),
613 "Failure in configuration while opening Registry: %s",
615 osi_panic(buf, __FILE__, __LINE__);
618 dummyLen = sizeof(maxcpus);
619 code = RegQueryValueEx(parmKey, "MaxCPUs", NULL, NULL,
620 (BYTE *) &maxcpus, &dummyLen);
621 if (code == ERROR_SUCCESS) {
623 DWORD_PTR processAffinityMask, systemAffinityMask;
625 hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION,
626 FALSE, GetCurrentProcessId());
627 if ( hProcess != NULL &&
628 GetProcessAffinityMask(hProcess, &processAffinityMask, &systemAffinityMask) )
631 DWORD_PTR mask, newAffinityMask;
638 for ( i=0, n=0, mask=1, newAffinityMask=0; i<bits && n<maxcpus; i++ ) {
639 if ( processAffinityMask & mask ) {
640 newAffinityMask |= mask;
646 SetProcessAffinityMask(hProcess, newAffinityMask);
647 CloseHandle(hProcess);
648 afsi_log("CPU Restrictions set to %d cpu(s); %d cpu(s) available", maxcpus, n);
650 afsi_log("CPU Restrictions set to %d cpu(s); unable to access process information", maxcpus);
654 dummyLen = sizeof(TraceOption);
655 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
656 (BYTE *) &TraceOption, &dummyLen);
657 afsi_log("Trace Options = %lX", TraceOption);
659 dummyLen = sizeof(traceBufSize);
660 code = RegQueryValueEx(parmKey, "TraceBufferSize", NULL, NULL,
661 (BYTE *) &traceBufSize, &dummyLen);
662 if (code == ERROR_SUCCESS)
663 afsi_log("Trace Buffer size %d", traceBufSize);
665 traceBufSize = CM_CONFIGDEFAULT_TRACEBUFSIZE;
666 afsi_log("Default trace buffer size %d", traceBufSize);
669 /* setup and enable debug log */
670 afsd_logp = osi_LogCreate("afsd", traceBufSize);
671 afsi_log("osi_LogCreate log addr %x", PtrToUlong(afsd_logp));
672 if ((TraceOption & 0x8)
677 osi_LogEnable(afsd_logp);
681 osi_Log0(afsd_logp, "Log init");
683 dummyLen = sizeof(cacheSize);
684 code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
685 (BYTE *) &cacheSize, &dummyLen);
686 if (code == ERROR_SUCCESS)
687 afsi_log("Cache size %d", cacheSize);
689 cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
690 afsi_log("Default cache size %d", cacheSize);
693 dummyLen = sizeof(logChunkSize);
694 code = RegQueryValueEx(parmKey, "ChunkSize", NULL, NULL,
695 (BYTE *) &logChunkSize, &dummyLen);
696 if (code == ERROR_SUCCESS) {
697 if (logChunkSize < 12 || logChunkSize > 30) {
698 afsi_log("Invalid chunk size %d, using default",
700 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
702 afsi_log("Chunk size %d", logChunkSize);
704 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
705 afsi_log("Default chunk size %d", logChunkSize);
707 cm_logChunkSize = logChunkSize;
708 cm_chunkSize = 1 << logChunkSize;
710 dummyLen = sizeof(numBkgD);
711 code = RegQueryValueEx(parmKey, "Daemons", NULL, NULL,
712 (BYTE *) &numBkgD, &dummyLen);
713 if (code == ERROR_SUCCESS)
714 afsi_log("%d background daemons", numBkgD);
716 numBkgD = CM_CONFIGDEFAULT_DAEMONS;
717 afsi_log("Defaulting to %d background daemons", numBkgD);
720 dummyLen = sizeof(numSvThreads);
721 code = RegQueryValueEx(parmKey, "ServerThreads", NULL, NULL,
722 (BYTE *) &numSvThreads, &dummyLen);
723 if (code == ERROR_SUCCESS)
724 afsi_log("%d server threads", numSvThreads);
726 numSvThreads = CM_CONFIGDEFAULT_SVTHREADS;
727 afsi_log("Defaulting to %d server threads", numSvThreads);
730 dummyLen = sizeof(stats);
731 code = RegQueryValueEx(parmKey, "Stats", NULL, NULL,
732 (BYTE *) &stats, &dummyLen);
733 if (code == ERROR_SUCCESS)
734 afsi_log("Status cache size %d", stats);
736 stats = CM_CONFIGDEFAULT_STATS;
737 afsi_log("Default status cache size %d", stats);
740 dummyLen = sizeof(ltt);
741 code = RegQueryValueEx(parmKey, "LogoffTokenTransfer", NULL, NULL,
742 (BYTE *) <t, &dummyLen);
743 if (code != ERROR_SUCCESS)
745 smb_LogoffTokenTransfer = ltt;
746 afsi_log("Logoff token transfer %s", (ltt ? "on" : "off"));
749 dummyLen = sizeof(ltto);
750 code = RegQueryValueEx(parmKey, "LogoffTokenTransferTimeout",
751 NULL, NULL, (BYTE *) <to, &dummyLen);
752 if (code != ERROR_SUCCESS)
757 smb_LogoffTransferTimeout = ltto;
758 afsi_log("Logoff token transfer timeout %d seconds", ltto);
760 dummyLen = sizeof(cm_rootVolumeName);
761 code = RegQueryValueEx(parmKey, "RootVolume", NULL, NULL,
762 cm_rootVolumeName, &dummyLen);
763 if (code == ERROR_SUCCESS)
764 afsi_log("Root volume %s", cm_rootVolumeName);
766 StringCbCopyA(cm_rootVolumeName, sizeof(cm_rootVolumeName), "root.afs");
767 afsi_log("Default root volume name root.afs");
770 cm_mountRootLen = sizeof(cm_mountRoot);
771 code = RegQueryValueEx(parmKey, "MountRoot", NULL, NULL,
772 cm_mountRoot, &cm_mountRootLen);
773 if (code == ERROR_SUCCESS) {
774 afsi_log("Mount root %s", cm_mountRoot);
775 cm_mountRootLen = (DWORD)strlen(cm_mountRoot);
777 StringCbCopyA(cm_mountRoot, sizeof(cm_mountRoot), "/afs");
782 dummyLen = sizeof(buf);
783 code = RegQueryValueEx(parmKey, "CachePath", NULL, ®Type,
785 if (code == ERROR_SUCCESS && buf[0]) {
786 if (regType == REG_EXPAND_SZ) {
787 dummyLen = ExpandEnvironmentStrings(buf, cm_CachePath, sizeof(cm_CachePath));
788 if (dummyLen > sizeof(cm_CachePath)) {
789 afsi_log("Cache path [%s] longer than %d after expanding env strings", buf, sizeof(cm_CachePath));
790 osi_panic("CachePath too long", __FILE__, __LINE__);
793 StringCbCopyA(cm_CachePath, sizeof(cm_CachePath), buf);
795 afsi_log("Cache path %s", cm_CachePath);
797 dummyLen = ExpandEnvironmentStrings("%TEMP%\\AFSCache", cm_CachePath, sizeof(cm_CachePath));
798 if (dummyLen > sizeof(cm_CachePath)) {
799 afsi_log("Cache path [%%TEMP%%\\AFSCache] longer than %d after expanding env strings",
800 sizeof(cm_CachePath));
801 osi_panic("CachePath too long", __FILE__, __LINE__);
803 afsi_log("Default cache path %s", cm_CachePath);
806 dummyLen = sizeof(virtualCache);
807 code = RegQueryValueEx(parmKey, "NonPersistentCaching", NULL, NULL,
808 (LPBYTE)&virtualCache, &dummyLen);
809 afsi_log("Cache type is %s", (virtualCache?"VIRTUAL":"FILE"));
812 dummyLen = sizeof(cm_ValidateCache);
813 code = RegQueryValueEx(parmKey, "ValidateCache", NULL, NULL,
814 (LPBYTE)&cm_ValidateCache, &dummyLen);
815 if ( cm_ValidateCache < 0 || cm_ValidateCache > 2 )
816 cm_ValidateCache = 1;
817 switch (cm_ValidateCache) {
819 afsi_log("Cache Validation disabled");
822 afsi_log("Cache Validation on Startup");
825 afsi_log("Cache Validation on Startup and Shutdown");
830 dummyLen = sizeof(traceOnPanic);
831 code = RegQueryValueEx(parmKey, "TrapOnPanic", NULL, NULL,
832 (BYTE *) &traceOnPanic, &dummyLen);
833 if (code != ERROR_SUCCESS)
834 traceOnPanic = 1; /* log */
835 afsi_log("Set to %s on panic", traceOnPanic ? "trap" : "not trap");
837 dummyLen = sizeof(reportSessionStartups);
838 code = RegQueryValueEx(parmKey, "ReportSessionStartups", NULL, NULL,
839 (BYTE *) &reportSessionStartups, &dummyLen);
840 if (code == ERROR_SUCCESS)
841 afsi_log("Session startups %s be recorded in the Event Log",
842 reportSessionStartups ? "will" : "will not");
844 reportSessionStartups = 0;
848 for ( i=0; i < MAXNUMSYSNAMES; i++ ) {
849 cm_sysNameList[i] = osi_Alloc(MAXSYSNAME);
850 cm_sysNameList[i][0] = '\0';
852 cm_sysName = cm_sysNameList[0];
854 dummyLen = sizeof(buf);
855 code = RegQueryValueEx(parmKey, "SysName", NULL, NULL, buf, &dummyLen);
856 if (code != ERROR_SUCCESS || !buf[0]) {
858 StringCbCopyA(buf, sizeof(buf), "ia64_win64");
859 #elif defined(_AMD64_)
860 StringCbCopyA(buf, sizeof(buf), "amd64_win64 x86_win32 i386_w2k");
861 #else /* assume x86 32-bit */
862 StringCbCopyA(buf, sizeof(buf), "x86_win32 i386_w2k i386_nt40");
865 afsi_log("Sys name %s", buf);
867 /* breakup buf into individual search string entries */
868 for (p = q = buf; p < buf + dummyLen; p++)
870 if (*p == '\0' || isspace(*p)) {
871 memcpy(cm_sysNameList[cm_sysNameCount],q,p-q);
872 cm_sysNameList[cm_sysNameCount][p-q] = '\0';
879 } while (*p == '\0' || isspace(*p));
885 StringCbCopyA(cm_sysName, MAXSYSNAME, cm_sysNameList[0]);
887 dummyLen = sizeof(cryptall);
888 code = RegQueryValueEx(parmKey, "SecurityLevel", NULL, NULL,
889 (BYTE *) &cryptall, &dummyLen);
890 if (code == ERROR_SUCCESS) {
891 afsi_log("SecurityLevel is %s", cryptall?"crypt":"clear");
894 afsi_log("Default SecurityLevel is clear");
898 LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_ON);
900 LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_OFF);
903 dummyLen = sizeof(cm_dnsEnabled);
904 code = RegQueryValueEx(parmKey, "UseDNS", NULL, NULL,
905 (BYTE *) &cm_dnsEnabled, &dummyLen);
906 if (code == ERROR_SUCCESS) {
907 afsi_log("DNS %s be used to find AFS cell servers",
908 cm_dnsEnabled ? "will" : "will not");
911 cm_dnsEnabled = 1; /* default on */
912 afsi_log("Default to use DNS to find AFS cell servers");
914 #else /* AFS_AFSDB_ENV */
915 afsi_log("AFS not built with DNS support to find AFS cell servers");
916 #endif /* AFS_AFSDB_ENV */
918 #ifdef AFS_FREELANCE_CLIENT
919 dummyLen = sizeof(cm_freelanceEnabled);
920 code = RegQueryValueEx(parmKey, "FreelanceClient", NULL, NULL,
921 (BYTE *) &cm_freelanceEnabled, &dummyLen);
922 if (code == ERROR_SUCCESS) {
923 afsi_log("Freelance client feature %s activated",
924 cm_freelanceEnabled ? "is" : "is not");
927 cm_freelanceEnabled = 1; /* default on */
929 #endif /* AFS_FREELANCE_CLIENT */
931 dummyLen = sizeof(smb_hideDotFiles);
932 code = RegQueryValueEx(parmKey, "HideDotFiles", NULL, NULL,
933 (BYTE *) &smb_hideDotFiles, &dummyLen);
934 if (code != ERROR_SUCCESS) {
935 smb_hideDotFiles = 1; /* default on */
937 afsi_log("Dot files/dirs will %sbe marked hidden",
938 smb_hideDotFiles ? "" : "not ");
940 dummyLen = sizeof(smb_maxMpxRequests);
941 code = RegQueryValueEx(parmKey, "MaxMpxRequests", NULL, NULL,
942 (BYTE *) &smb_maxMpxRequests, &dummyLen);
943 if (code != ERROR_SUCCESS) {
944 smb_maxMpxRequests = 50;
946 afsi_log("Maximum number of multiplexed sessions is %d", smb_maxMpxRequests);
948 dummyLen = sizeof(smb_maxVCPerServer);
949 code = RegQueryValueEx(parmKey, "MaxVCPerServer", NULL, NULL,
950 (BYTE *) &smb_maxVCPerServer, &dummyLen);
951 if (code != ERROR_SUCCESS) {
952 smb_maxVCPerServer = 100;
954 afsi_log("Maximum number of VCs per server is %d", smb_maxVCPerServer);
956 dummyLen = sizeof(smb_authType);
957 code = RegQueryValueEx(parmKey, "SMBAuthType", NULL, NULL,
958 (BYTE *) &smb_authType, &dummyLen);
960 if (code != ERROR_SUCCESS ||
961 (smb_authType != SMB_AUTH_EXTENDED && smb_authType != SMB_AUTH_NTLM && smb_authType != SMB_AUTH_NONE)) {
962 smb_authType = SMB_AUTH_EXTENDED; /* default is to use extended authentication */
964 afsi_log("SMB authentication type is %s", ((smb_authType == SMB_AUTH_NONE)?"NONE":((smb_authType == SMB_AUTH_EXTENDED)?"EXTENDED":"NTLM")));
966 dummyLen = sizeof(rx_nojumbo);
967 code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
968 (BYTE *) &rx_nojumbo, &dummyLen);
969 if (code != ERROR_SUCCESS) {
973 afsi_log("RX Jumbograms are disabled");
975 dummyLen = sizeof(rx_mtu);
976 code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
977 (BYTE *) &rx_mtu, &dummyLen);
978 if (code != ERROR_SUCCESS || !rx_mtu) {
982 afsi_log("RX maximum MTU is %d", rx_mtu);
984 dummyLen = sizeof(rx_enable_peer_stats);
985 code = RegQueryValueEx(parmKey, "RxEnablePeerStats", NULL, NULL,
986 (BYTE *) &rx_enable_peer_stats, &dummyLen);
987 if (code != ERROR_SUCCESS) {
988 rx_enable_peer_stats = 0;
990 if (rx_enable_peer_stats)
991 afsi_log("RX Peer Statistics gathering is enabled");
993 dummyLen = sizeof(rx_enable_process_stats);
994 code = RegQueryValueEx(parmKey, "RxEnableProcessStats", NULL, NULL,
995 (BYTE *) &rx_enable_process_stats, &dummyLen);
996 if (code != ERROR_SUCCESS) {
997 rx_enable_process_stats = 0;
999 if (rx_enable_process_stats)
1000 afsi_log("RX Process Statistics gathering is enabled");
1002 dummyLen = sizeof(DWORD);
1003 code = RegQueryValueEx(parmKey, "daemonCheckDownInterval", NULL, NULL,
1004 (BYTE *) &dwValue, &dummyLen);
1005 if (code == ERROR_SUCCESS)
1006 cm_daemonCheckDownInterval = dwValue;
1007 afsi_log("daemonCheckDownInterval is %d", cm_daemonCheckDownInterval);
1009 dummyLen = sizeof(DWORD);
1010 code = RegQueryValueEx(parmKey, "daemonCheckUpInterval", NULL, NULL,
1011 (BYTE *) &dwValue, &dummyLen);
1012 if (code == ERROR_SUCCESS)
1013 cm_daemonCheckUpInterval = dwValue;
1014 afsi_log("daemonCheckUpInterval is %d", cm_daemonCheckUpInterval);
1016 dummyLen = sizeof(DWORD);
1017 code = RegQueryValueEx(parmKey, "daemonCheckVolInterval", NULL, NULL,
1018 (BYTE *) &dwValue, &dummyLen);
1019 if (code == ERROR_SUCCESS)
1020 cm_daemonCheckVolInterval = dwValue;
1021 afsi_log("daemonCheckVolInterval is %d", cm_daemonCheckVolInterval);
1023 dummyLen = sizeof(DWORD);
1024 code = RegQueryValueEx(parmKey, "daemonCheckCBInterval", NULL, NULL,
1025 (BYTE *) &dwValue, &dummyLen);
1026 if (code == ERROR_SUCCESS)
1027 cm_daemonCheckCBInterval = dwValue;
1028 afsi_log("daemonCheckCBInterval is %d", cm_daemonCheckCBInterval);
1030 dummyLen = sizeof(DWORD);
1031 code = RegQueryValueEx(parmKey, "daemonCheckLockInterval", NULL, NULL,
1032 (BYTE *) &dwValue, &dummyLen);
1033 if (code == ERROR_SUCCESS)
1034 cm_daemonCheckLockInterval = dwValue;
1035 afsi_log("daemonCheckLockInterval is %d", cm_daemonCheckLockInterval);
1037 dummyLen = sizeof(DWORD);
1038 code = RegQueryValueEx(parmKey, "daemonCheckTokenInterval", NULL, NULL,
1039 (BYTE *) &dwValue, &dummyLen);
1040 if (code == ERROR_SUCCESS)
1041 cm_daemonTokenCheckInterval = dwValue;
1042 afsi_log("daemonCheckTokenInterval is %d", cm_daemonTokenCheckInterval);
1044 dummyLen = sizeof(DWORD);
1045 code = RegQueryValueEx(parmKey, "CallBackPort", NULL, NULL,
1046 (BYTE *) &dwValue, &dummyLen);
1047 if (code == ERROR_SUCCESS) {
1048 cm_callbackport = (unsigned short) dwValue;
1050 afsi_log("CM CallBackPort is %u", cm_callbackport);
1052 dummyLen = sizeof(DWORD);
1053 code = RegQueryValueEx(parmKey, "EnableServerLocks", NULL, NULL,
1054 (BYTE *) &dwValue, &dummyLen);
1055 if (code == ERROR_SUCCESS) {
1056 cm_enableServerLocks = (unsigned short) dwValue;
1058 switch (cm_enableServerLocks) {
1060 afsi_log("EnableServerLocks: never");
1063 afsi_log("EnableServerLocks: always");
1067 afsi_log("EnableServerLocks: server requested");
1070 RegCloseKey (parmKey);
1072 /* Call lanahelper to get Netbios name, lan adapter number and gateway flag */
1073 if (SUCCEEDED(code = lana_GetUncServerNameEx(cm_NetbiosName, &lanaNum, &isGateway, LANA_NETBIOS_NAME_FULL))) {
1074 LANadapter = (lanaNum == LANA_INVALID)? -1: lanaNum;
1076 if (LANadapter != -1)
1077 afsi_log("LAN adapter number %d", LANadapter);
1079 afsi_log("LAN adapter number not determined");
1082 afsi_log("Set for gateway service");
1084 afsi_log("Using >%s< as SMB server name", cm_NetbiosName);
1086 /* something went horribly wrong. We can't proceed without a netbios name */
1087 StringCbPrintfA(buf,sizeof(buf),"Netbios name could not be determined: %li", code);
1088 osi_panic(buf, __FILE__, __LINE__);
1091 cacheBlocks = ((afs_uint64)cacheSize * 1024) / CM_CONFIGDEFAULT_BLOCKSIZE;
1093 /* get network related info */
1094 cm_noIPAddr = CM_MAXINTERFACE_ADDR;
1095 code = syscfg_GetIFInfo(&cm_noIPAddr,
1096 cm_IPAddr, cm_SubnetMask,
1097 cm_NetMtu, cm_NetFlags);
1099 if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
1100 afsi_log("syscfg_GetIFInfo error code %d", code);
1102 afsi_log("First Network address %x SubnetMask %x",
1103 cm_IPAddr[0], cm_SubnetMask[0]);
1106 * Save client configuration for GetCacheConfig requests
1108 cm_initParams.nChunkFiles = 0;
1109 cm_initParams.nStatCaches = stats;
1110 cm_initParams.nDataCaches = (afs_uint32)(cacheBlocks > 0xFFFFFFFF ? 0xFFFFFFFF : cacheBlocks);
1111 cm_initParams.nVolumeCaches = stats/2;
1112 cm_initParams.firstChunkSize = cm_chunkSize;
1113 cm_initParams.otherChunkSize = cm_chunkSize;
1114 cm_initParams.cacheSize = cacheSize;
1115 cm_initParams.setTime = 0;
1116 cm_initParams.memCache = 1;
1118 /* Ensure the AFS Netbios Name is registered to allow loopback access */
1119 configureBackConnectionHostNames();
1121 /* init user daemon, and other packages */
1134 code = cm_InitMappedMemory(virtualCache, cm_CachePath, stats, cm_chunkSize, cacheBlocks);
1135 afsi_log("cm_InitMappedMemory code %x", code);
1137 *reasonP = "error initializing cache file";
1141 #ifdef AFS_AFSDB_ENV
1142 #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
1143 if (cm_InitDNS(cm_dnsEnabled) == -1)
1144 cm_dnsEnabled = 0; /* init failed, so deactivate */
1145 afsi_log("cm_InitDNS %d", cm_dnsEnabled);
1149 /* Set RX parameters before initializing RX */
1152 afsi_log("rx_SetNoJumbo successful");
1155 if ( rx_mtu != -1 ) {
1156 rx_SetMaxMTU(rx_mtu);
1157 afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
1160 /* initialize RX, and tell it to listen to the callbackport,
1161 * which is used for callback RPC messages.
1163 code = rx_Init(htons(cm_callbackport));
1165 afsi_log("rx_Init code %x - retrying with a random port number", code);
1168 afsi_log("rx_Init code %x", code);
1170 *reasonP = "afsd: failed to init rx client";
1174 /* create an unauthenticated service #1 for callbacks */
1175 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1176 serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
1177 RXAFSCB_ExecuteRequest);
1178 afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1179 if (serverp == NULL) {
1180 *reasonP = "unknown error";
1184 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1185 serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
1186 &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
1187 afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1188 if (serverp == NULL) {
1189 *reasonP = "unknown error";
1193 /* start server threads, *not* donating this one to the pool */
1195 afsi_log("rx_StartServer");
1197 if (rx_enable_peer_stats)
1198 rx_enablePeerRPCStats();
1200 if (rx_enable_process_stats)
1201 rx_enableProcessRPCStats();
1203 code = cm_GetRootCellName(rootCellName);
1204 afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s",
1205 code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
1206 if (code != 0 && !cm_freelanceEnabled)
1208 *reasonP = "can't find root cell name in afsd.ini";
1211 else if (cm_freelanceEnabled)
1212 cm_data.rootCellp = NULL;
1214 if (code == 0 && !cm_freelanceEnabled)
1216 cm_data.rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
1217 afsi_log("cm_GetCell addr %x", PtrToUlong(cm_data.rootCellp));
1218 if (cm_data.rootCellp == NULL)
1220 *reasonP = "can't find root cell in afsdcell.ini";
1225 #ifdef AFS_FREELANCE_CLIENT
1226 if (cm_freelanceEnabled)
1230 /* Initialize the RPC server for session keys */
1233 afsd_InitServerPreferences();
1237 int afsd_ShutdownCM(void)
1239 cm_ReleaseSCache(cm_data.rootSCachep);
1244 int afsd_InitDaemons(char **reasonP)
1251 /* this should really be in an init daemon from here on down */
1253 if (!cm_freelanceEnabled) {
1256 osi_Log0(afsd_logp, "Loading Root Volume from cell");
1258 code = cm_GetVolumeByName(cm_data.rootCellp, cm_rootVolumeName, cm_rootUserp,
1259 &req, CM_FLAG_CREATE, &cm_data.rootVolumep);
1260 afsi_log("cm_GetVolumeByName code %x root vol %x", code,
1261 (code ? (cm_volume_t *)-1 : cm_data.rootVolumep));
1262 } while (code && --attempts);
1264 *reasonP = "can't find root volume in root cell";
1269 /* compute the root fid */
1270 if (!cm_freelanceEnabled) {
1271 cm_data.rootFid.cell = cm_data.rootCellp->cellID;
1272 cm_data.rootFid.volume = cm_GetROVolumeID(cm_data.rootVolumep);
1273 cm_data.rootFid.vnode = 1;
1274 cm_data.rootFid.unique = 1;
1277 cm_FakeRootFid(&cm_data.rootFid);
1279 code = cm_GetSCache(&cm_data.rootFid, &cm_data.rootSCachep, cm_rootUserp, &req);
1280 afsi_log("cm_GetSCache code %x scache %x", code,
1281 (code ? (cm_scache_t *)-1 : cm_data.rootSCachep));
1283 *reasonP = "unknown error";
1287 cm_InitDaemon(numBkgD);
1288 afsi_log("cm_InitDaemon complete");
1293 int afsd_InitSMB(char **reasonP, void *aMBfunc)
1300 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1301 0, KEY_QUERY_VALUE, &parmKey);
1302 if (code == ERROR_SUCCESS) {
1303 dummyLen = sizeof(DWORD);
1304 code = RegQueryValueEx(parmKey, "StoreAnsiFilenames", NULL, NULL,
1305 (BYTE *) &dwValue, &dummyLen);
1306 if (code == ERROR_SUCCESS)
1307 smb_StoreAnsiFilenames = dwValue ? 1 : 0;
1308 RegCloseKey (parmKey);
1311 /* Do this last so that we don't handle requests before init is done.
1312 * Here we initialize the SMB listener.
1314 smb_Init(afsd_logp, cm_NetbiosName, smb_UseV3, LANadapter, numSvThreads, aMBfunc);
1315 afsi_log("smb_Init complete");
1328 #pragma pack( push, before_imagehlp, 8 )
1329 #include <imagehlp.h>
1330 #pragma pack( pop, before_imagehlp )
1332 #define MAXNAMELEN 1024
1334 void afsd_printStack(HANDLE hThread, CONTEXT *c)
1337 HANDLE hProcess = GetCurrentProcess();
1339 #if defined(_AMD64_)
1341 #elif defined(_X86_)
1345 char functionName[MAXNAMELEN];
1347 IMAGEHLP_MODULE Module;
1351 IMAGEHLP_SYMBOL *pSym;
1353 afsi_log_useTimestamp = 0;
1355 pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
1357 memset( &s, '\0', sizeof s );
1358 if (!SymInitialize(hProcess, NULL, 1) )
1360 afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
1362 SymCleanup( hProcess );
1368 symOptions = SymGetOptions();
1369 symOptions |= SYMOPT_LOAD_LINES;
1370 symOptions &= ~SYMOPT_UNDNAME;
1371 SymSetOptions( symOptions );
1374 * init STACKFRAME for first call
1375 * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
1376 * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
1377 * and good riddance.
1379 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
1380 #error The STACKFRAME initialization in afsd_printStack() for this platform
1381 #error must be properly configured
1382 #elif defined(_AMD64_)
1383 s.AddrPC.Offset = 0;
1384 s.AddrPC.Mode = AddrModeFlat;
1385 s.AddrFrame.Offset = 0;
1386 s.AddrFrame.Mode = AddrModeFlat;
1388 s.AddrPC.Offset = c->Eip;
1389 s.AddrPC.Mode = AddrModeFlat;
1390 s.AddrFrame.Offset = c->Ebp;
1391 s.AddrFrame.Mode = AddrModeFlat;
1394 memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
1395 pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
1396 pSym->MaxNameLength = MAXNAMELEN;
1398 memset( &Line, '\0', sizeof Line );
1399 Line.SizeOfStruct = sizeof Line;
1401 memset( &Module, '\0', sizeof Module );
1402 Module.SizeOfStruct = sizeof Module;
1406 afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
1408 for ( frameNum = 0; ; ++ frameNum )
1411 * get next stack frame (StackWalk(), SymFunctionTableAccess(),
1412 * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
1413 * ERROR_NOACCESS (998), you can assume that either you are done, or
1414 * that the stack is so hosed that the next deeper frame could not be
1417 if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c,
1418 NULL, SymFunctionTableAccess, SymGetModuleBase,
1422 /* display its contents */
1423 afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
1424 frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
1425 s.AddrPC.Offset, s.AddrReturn.Offset,
1426 s.AddrFrame.Offset, s.AddrStack.Offset );
1428 if ( s.AddrPC.Offset == 0 )
1430 afsi_log("(-nosymbols- PC == 0)" );
1434 /* show procedure info from a valid PC */
1435 if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
1437 if ( GetLastError() != ERROR_INVALID_ADDRESS )
1439 afsi_log("SymGetSymFromAddr(): errno = %lu",
1445 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN,
1447 afsi_log("%s", functionName );
1451 afsi_log(" %+ld bytes", (long) offset);
1455 if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
1457 if (GetLastError() != ERROR_INVALID_ADDRESS)
1459 afsi_log("Error: SymGetLineFromAddr(): errno = %lu",
1465 afsi_log(" Line: %s(%lu) %+ld bytes", Line.FileName,
1466 Line.LineNumber, offset);
1470 /* no return address means no deeper stackframe */
1471 if (s.AddrReturn.Offset == 0)
1478 if (GetLastError() != 0)
1480 afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
1483 SymCleanup(hProcess);
1489 static DWORD *afsd_crtDbgBreakCurrent = NULL;
1490 static DWORD afsd_crtDbgBreaks[256];
1493 static EFaultRepRetVal (WINAPI *pReportFault)(LPEXCEPTION_POINTERS pep, DWORD dwMode) = NULL;
1494 static BOOL (WINAPI *pMiniDumpWriteDump)(HANDLE hProcess,DWORD ProcessId,HANDLE hFile,
1495 MINIDUMP_TYPE DumpType,
1496 PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
1497 PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
1498 PMINIDUMP_CALLBACK_INFORMATION CallbackParam) = NULL;
1507 code = GetEnvironmentVariable("TEMP", wd, sizeof(wd));
1508 if ( code == 0 || code > sizeof(wd) )
1510 if (!GetWindowsDirectory(wd, sizeof(wd)))
1513 StringCbCatA(wd, sizeof(wd), "\\afsd.dmp");
1514 return CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1515 CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
1519 GenerateMiniDump(PEXCEPTION_POINTERS ep)
1523 // Generate exception to get proper context in dump
1526 RaiseException(DBG_CONTINUE, 0, 0, NULL);
1528 __except(GenerateMiniDump(GetExceptionInformation()), EXCEPTION_CONTINUE_EXECUTION)
1534 MINIDUMP_EXCEPTION_INFORMATION eInfo;
1535 HANDLE hFile = NULL;
1536 HMODULE hDbgHelp = NULL;
1538 hDbgHelp = LoadLibrary("Dbghelp.dll");
1539 if ( hDbgHelp == NULL )
1542 (FARPROC) pMiniDumpWriteDump = GetProcAddress(hDbgHelp, "MiniDumpWriteDump");
1543 if ( pMiniDumpWriteDump == NULL ) {
1544 FreeLibrary(hDbgHelp);
1548 hFile = OpenDumpFile();
1555 DWORD dwMiniDumpType = MiniDumpWithDataSegs;
1557 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1558 0, KEY_QUERY_VALUE, &parmKey);
1559 if (code == ERROR_SUCCESS) {
1560 dummyLen = sizeof(DWORD);
1561 code = RegQueryValueEx(parmKey, "MiniDumpType", NULL, NULL,
1562 (BYTE *) &dwValue, &dummyLen);
1563 if (code == ERROR_SUCCESS)
1564 dwMiniDumpType = dwValue;
1565 RegCloseKey (parmKey);
1568 eInfo.ThreadId = GetCurrentThreadId();
1569 eInfo.ExceptionPointers = ep;
1570 eInfo.ClientPointers = FALSE;
1572 pMiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(),
1573 hFile, dwMiniDumpType, ep ? &eInfo : NULL,
1578 FreeLibrary(hDbgHelp);
1582 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
1586 BOOL allocRequestBrk = FALSE;
1588 HMODULE hLib = NULL;
1590 afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n",
1591 ep->ExceptionRecord->ExceptionCode,
1592 ep->ExceptionRecord->ExceptionAddress);
1595 if (afsd_crtDbgBreakCurrent &&
1596 *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
1598 allocRequestBrk = TRUE;
1599 afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
1603 /* save context if we want to print the stack information */
1604 context = *ep->ContextRecord;
1606 afsd_printStack(GetCurrentThread(), &context);
1608 GenerateMiniDump(ep);
1610 hLib = LoadLibrary("Faultrep.dll");
1612 (FARPROC) pReportFault = GetProcAddress(hLib, "ReportFault");
1614 pReportFault(ep, 0);
1618 if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
1620 afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
1623 if (allocRequestBrk)
1625 afsd_crtDbgBreakCurrent++;
1626 _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
1630 ep->ContextRecord->Eip++;
1632 return EXCEPTION_CONTINUE_EXECUTION;
1636 return EXCEPTION_CONTINUE_SEARCH;
1640 void afsd_SetUnhandledExceptionFilter()
1642 SetUnhandledExceptionFilter(afsd_ExceptionFilter);
1646 void afsd_DbgBreakAllocInit()
1648 memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
1649 afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
1652 void afsd_DbgBreakAdd(DWORD requestNumber)
1655 for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
1657 if (afsd_crtDbgBreaks[i] == -1)
1662 afsd_crtDbgBreaks[i] = requestNumber;
1664 _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);