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>
30 #include <rx\rx_null.h>
31 #include <WINNT/syscfg.h>
32 #include <WINNT/afsreg.h>
36 #include "lanahelper.h"
38 #include "cm_memmap.h"
40 extern int RXAFSCB_ExecuteRequest(struct rx_call *z_call);
41 extern int RXSTATS_ExecuteRequest(struct rx_call *z_call);
43 extern afs_int32 cryptall;
44 extern int cm_enableServerLocks;
45 extern int cm_deleteReadOnly;
47 extern afs_int32 cm_BPlusTrees;
49 extern afs_int32 cm_OfflineROIsValid;
50 extern afs_int32 cm_giveUpAllCBs;
51 extern const char **smb_ExecutableExtensions;
55 cm_config_data_t cm_data;
57 char cm_rootVolumeName[VL_MAXNAMELEN];
58 DWORD cm_rootVolumeNameLen;
59 char cm_mountRoot[1024];
60 DWORD cm_mountRootLen;
63 #ifdef AFS_FREELANCE_CLIENT
65 #endif /* freelance */
78 char cm_HostName[200];
80 unsigned short cm_callbackport = CM_DEFAULT_CALLBACKPORT;
82 char cm_NetbiosName[MAX_NB_NAME_LENGTH] = "";
84 char cm_CachePath[MAX_PATH];
85 DWORD cm_CachePathLen;
86 DWORD cm_ValidateCache = 1;
88 BOOL reportSessionStartups = FALSE;
90 cm_initparams_v1 cm_initParams;
93 unsigned int cm_sysNameCount = 0;
94 char *cm_sysNameList[MAXNUMSYSNAMES];
96 DWORD TraceOption = 0;
99 * AFSD Initialization Log
101 * This is distinct from the regular debug logging facility.
102 * Log items go directly to a file, not to an array in memory, so that even
103 * if AFSD crashes, the log can be inspected.
109 int cm_dnsEnabled = 1;
113 static int afsi_log_useTimestamp = 1;
116 afsi_log(char *pattern, ...)
118 char s[256], t[100], d[100], u[512];
121 va_start(ap, pattern);
123 StringCbVPrintfA(s, sizeof(s), pattern, ap);
124 if ( afsi_log_useTimestamp ) {
125 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
126 GetDateFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, d, sizeof(d));
127 StringCbPrintfA(u, sizeof(u), "%s %s: %s\r\n", d, t, s);
128 if (afsi_file != INVALID_HANDLE_VALUE)
129 WriteFile(afsi_file, u, (DWORD)strlen(u), &zilch, NULL);
134 if (afsi_file != INVALID_HANDLE_VALUE)
135 WriteFile(afsi_file, s, (DWORD)strlen(s), &zilch, NULL);
139 extern initUpperCaseTable();
140 void afsd_initUpperCaseTable()
142 initUpperCaseTable();
149 char t[100], u[100], *p, *path;
155 DWORD maxLogSize = 100 * 1024;
157 afsi_file = INVALID_HANDLE_VALUE;
158 code = GetTempPath(sizeof(wd)-15, wd);
159 if ( code == 0 || code > (sizeof(wd)-15) )
160 return; /* unable to create a log */
162 StringCbCatA(wd, sizeof(wd), "\\afsd_init.log");
163 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
164 afsi_file = CreateFile(wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
165 OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
167 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
168 0, KEY_QUERY_VALUE, &parmKey);
169 if (code == ERROR_SUCCESS) {
170 dummyLen = sizeof(maxLogSize);
171 code = RegQueryValueEx(parmKey, "MaxLogSize", NULL, NULL,
172 (BYTE *) &maxLogSize, &dummyLen);
173 RegCloseKey (parmKey);
177 dwLow = GetFileSize( afsi_file, &dwHigh );
178 if ( dwHigh > 0 || dwLow >= maxLogSize ) {
179 CloseHandle(afsi_file);
180 afsi_file = CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
181 CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
185 SetFilePointer(afsi_file, 0, NULL, FILE_END);
186 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, u, sizeof(u));
187 StringCbCatA(t, sizeof(t), ": Create log file\r\n");
188 StringCbCatA(u, sizeof(u), ": Created log file\r\n");
189 WriteFile(afsi_file, t, (DWORD)strlen(t), &zilch, NULL);
190 WriteFile(afsi_file, u, (DWORD)strlen(u), &zilch, NULL);
192 code = GetEnvironmentVariable("PATH", NULL, 0);
194 code = GetEnvironmentVariable("PATH", path, code);
195 WriteFile(afsi_file, p, (DWORD)strlen(p), &zilch, NULL);
196 WriteFile(afsi_file, path, (DWORD)strlen(path), &zilch, NULL);
197 WriteFile(afsi_file, "\r\n", (DWORD)1, &zilch, NULL);
200 /* Initialize C RTL Code Page conversion functions */
201 /* All of the path info obtained from the SMB client is in the OEM code page */
202 afsi_log("OEM Code Page = %d", GetOEMCP());
203 afsi_log("locale = %s", setlocale(LC_ALL,NULL));
205 /* Two things to look into. First, should mbstowcs() be performing
206 * character set translations from OEM to Unicode in smb3.c;
207 * Second, do we need to set this translation in each function
208 * due to multi-threading.
210 afsi_log("locale -> %s", setlocale(LC_ALL, ".OCP"));
211 afsi_log("_setmbcp = %d -> %d", _setmbcp(_MB_CP_OEM), _getmbcp());
216 * Standard AFSD trace
219 void afsd_ForceTrace(BOOL flush)
228 len = GetTempPath(sizeof(buf)-10, buf);
229 StringCbCopyA(&buf[len], sizeof(buf)-len, "/afsd.log");
230 handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
231 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
232 if (handle == INVALID_HANDLE_VALUE) {
234 osi_panic("Cannot create log file", __FILE__, __LINE__);
236 osi_LogPrint(afsd_logp, handle);
238 FlushFileBuffers(handle);
243 configureBackConnectionHostNames(void)
245 /* On Windows XP SP2, Windows 2003 SP1, and all future Windows operating systems
246 * there is a restriction on the use of SMB authentication on loopback connections.
247 * There are two work arounds available:
249 * (1) We can disable the check for matching host names. This does not
251 * [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa]
252 * "DisableLoopbackCheck"=dword:00000001
254 * (2) We can add the AFS SMB/CIFS service name to an approved list. This
255 * does require a reboot:
256 * [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0]
257 * "BackConnectionHostNames"=multi-sz
259 * The algorithm will be:
260 * (1) Check to see if cm_NetbiosName exists in the BackConnectionHostNames list
261 * (2a) If not, add it to the list. (This will not take effect until the next reboot.)
262 * (2b1) and check to see if DisableLoopbackCheck is set.
263 * (2b2) If not set, set the DisableLoopbackCheck value to 0x1
264 * (2b3) and create HKLM\SOFTWARE\OpenAFS\Client UnsetDisableLoopbackCheck
265 * (2c) else If cm_NetbiosName exists in the BackConnectionHostNames list,
266 * check for the UnsetDisableLoopbackCheck value.
267 * If set, set the DisableLoopbackCheck flag to 0x0
268 * and delete the UnsetDisableLoopbackCheck value
270 * Starting in Longhorn Beta 1, an entry in the BackConnectionHostNames value will
271 * force Windows to use the loopback authentication mechanism for the specified
278 DWORD dwSize, dwAllocSize;
280 PBYTE pHostNames = NULL, pName = NULL;
281 BOOL bNameFound = FALSE;
283 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
284 "SYSTEM\\CurrentControlSet\\Control\\Lsa\\MSV1_0",
287 &hkMSV10) == ERROR_SUCCESS )
289 if ((RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0,
290 &dwType, NULL, &dwAllocSize) == ERROR_SUCCESS) &&
291 (dwType == REG_MULTI_SZ))
293 dwAllocSize += 1 /* in case the source string is not nul terminated */
294 + strlen(cm_NetbiosName) + 2;
295 pHostNames = malloc(dwAllocSize);
296 dwSize = dwAllocSize;
297 if (RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0, &dwType,
298 pHostNames, &dwSize) == ERROR_SUCCESS)
300 for (pName = pHostNames;
301 (pName - pHostNames < dwSize) && *pName ;
302 pName += strlen(pName) + 1)
304 if ( !stricmp(pName, cm_NetbiosName) ) {
313 size_t size = strlen(cm_NetbiosName) + 2;
315 pHostNames = malloc(size);
318 StringCbCopyA(pName, size, cm_NetbiosName);
320 *pName = '\0'; /* add a second nul terminator */
322 dwType = REG_MULTI_SZ;
323 dwSize = pName - pHostNames + 1;
324 RegSetValueEx( hkMSV10, "BackConnectionHostNames", 0, dwType, pHostNames, dwSize);
326 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
327 "SYSTEM\\CurrentControlSet\\Control\\Lsa",
330 &hkLsa) == ERROR_SUCCESS )
332 dwSize = sizeof(DWORD);
333 if ( RegQueryValueEx( hkLsa, "DisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) != ERROR_SUCCESS ||
336 dwSize = sizeof(DWORD);
338 RegSetValueEx( hkLsa, "DisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
340 if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
341 AFSREG_CLT_OPENAFS_SUBKEY,
344 REG_OPTION_NON_VOLATILE,
348 NULL) == ERROR_SUCCESS) {
351 dwSize = sizeof(DWORD);
353 RegSetValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
354 RegCloseKey(hkClient);
360 if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
361 AFSREG_CLT_OPENAFS_SUBKEY,
364 REG_OPTION_NON_VOLATILE,
368 NULL) == ERROR_SUCCESS) {
370 dwSize = sizeof(DWORD);
371 if ( RegQueryValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) == ERROR_SUCCESS &&
373 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
374 "SYSTEM\\CurrentControlSet\\Control\\Lsa",
377 &hkLsa) == ERROR_SUCCESS )
379 RegDeleteValue(hkLsa, "DisableLoopbackCheck");
383 RegDeleteValue(hkClient, "RemoveDisableLoopbackCheck");
384 RegCloseKey(hkClient);
387 RegCloseKey(hkMSV10);
395 static void afsd_InitServerPreferences(void)
398 DWORD dwType, dwSize;
402 DWORD dwHostSize = 256;
404 struct sockaddr_in saddr;
407 if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
408 AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\VLDB",
410 KEY_READ|KEY_QUERY_VALUE,
411 &hkPrefs) == ERROR_SUCCESS) {
413 RegQueryInfoKey( hkPrefs,
416 NULL, /* lpReserved */
417 NULL, /* lpcSubKeys */
418 NULL, /* lpcMaxSubKeyLen */
419 NULL, /* lpcMaxClassLen */
420 &dwPrefs, /* lpcValues */
421 NULL, /* lpcMaxValueNameLen */
422 NULL, /* lpcMaxValueLen */
423 NULL, /* lpcbSecurityDescriptor */
424 NULL /* lpftLastWriteTime */
427 for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
429 dwSize = sizeof(DWORD);
432 if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
433 &dwType, (LPBYTE)&dwRank, &dwSize))
435 afsi_log("RegEnumValue(hkPrefs) failed");
439 afsi_log("VLDB Server Preference: %s = %d",szHost, dwRank);
441 if (isdigit(szHost[0]))
443 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
447 if ((pEntry = gethostbyname (szHost)) == NULL)
450 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
452 saddr.sin_family = AF_INET;
453 dwRank += (rand() & 0x000f);
455 tsp = cm_FindServer(&saddr, CM_SERVER_VLDB);
456 if ( tsp ) /* an existing server - ref count increased */
458 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
460 /* set preferences for an existing vlserver */
461 cm_ChangeRankCellVLServer(tsp);
462 cm_PutServer(tsp); /* decrease refcount */
464 else /* add a new server without a cell */
466 tsp = cm_NewServer(&saddr, CM_SERVER_VLDB, NULL); /* refcount = 1 */
467 tsp->ipRank = (USHORT)dwRank;
471 RegCloseKey(hkPrefs);
474 if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
475 AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\File",
477 KEY_READ|KEY_QUERY_VALUE,
478 &hkPrefs) == ERROR_SUCCESS) {
480 RegQueryInfoKey( hkPrefs,
483 NULL, /* lpReserved */
484 NULL, /* lpcSubKeys */
485 NULL, /* lpcMaxSubKeyLen */
486 NULL, /* lpcMaxClassLen */
487 &dwPrefs, /* lpcValues */
488 NULL, /* lpcMaxValueNameLen */
489 NULL, /* lpcMaxValueLen */
490 NULL, /* lpcbSecurityDescriptor */
491 NULL /* lpftLastWriteTime */
494 for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
496 dwSize = sizeof(DWORD);
499 if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
500 &dwType, (LPBYTE)&dwRank, &dwSize))
502 afsi_log("RegEnumValue(hkPrefs) failed");
506 afsi_log("File Server Preference: %s = %d",szHost, dwRank);
508 if (isdigit(szHost[0]))
510 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
514 if ((pEntry = gethostbyname (szHost)) == NULL)
517 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
519 saddr.sin_family = AF_INET;
520 dwRank += (rand() & 0x000f);
522 tsp = cm_FindServer(&saddr, CM_SERVER_FILE);
523 if ( tsp ) /* an existing server - ref count increased */
525 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
527 /* find volumes which might have RO copy
528 /* on server and change the ordering of
531 cm_ChangeRankVolume(tsp);
532 cm_PutServer(tsp); /* decrease refcount */
534 else /* add a new server without a cell */
536 tsp = cm_NewServer(&saddr, CM_SERVER_FILE, NULL); /* refcount = 1 */
537 tsp->ipRank = (USHORT)dwRank;
541 RegCloseKey(hkPrefs);
546 * AFSD Initialization
549 int afsd_InitCM(char **reasonP)
552 afs_uint64 cacheBlocks;
558 DWORD rx_enable_peer_stats = 0;
559 DWORD rx_enable_process_stats = 0;
564 long virtualCache = 0;
565 char rootCellName[256];
566 struct rx_service *serverp;
567 static struct rx_securityClass *nullServerSecurityClassp;
575 /*int freelanceEnabled;*/
579 int cm_noIPAddr; /* number of client network interfaces */
580 int cm_IPAddr[CM_MAXINTERFACE_ADDR]; /* client's IP address in host order */
581 int cm_SubnetMask[CM_MAXINTERFACE_ADDR];/* client's subnet mask in host order*/
582 int cm_NetMtu[CM_MAXINTERFACE_ADDR]; /* client's MTU sizes */
583 int cm_NetFlags[CM_MAXINTERFACE_ADDR]; /* network flags */
585 WSAStartup(0x0101, &WSAjunk);
587 afsd_initUpperCaseTable();
588 init_et_to_sys_error();
590 /* setup osidebug server at RPC slot 1000 */
591 osi_LongToUID(1000, &debugID);
592 code = osi_InitDebug(&debugID);
593 afsi_log("osi_InitDebug code %d", code);
595 // osi_LockTypeSetDefault("stat"); /* comment this out for speed */
597 if (code == RPC_S_NO_PROTSEQS)
598 *reasonP = "No RPC Protocol Sequences registered. Check HKLM\\SOFTWARE\\Microsoft\\RPC\\ClientProtocols";
600 *reasonP = "unknown error";
605 gethostname(cm_HostName, sizeof(cm_HostName));
606 afsi_log("gethostname %s", cm_HostName);
607 thp = gethostbyname(cm_HostName);
608 memcpy(&cm_HostAddr, thp->h_addr_list[0], 4);
610 /* seed random number generator */
611 srand(ntohl(cm_HostAddr));
613 /* Look up configuration parameters in Registry */
614 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
615 0, KEY_QUERY_VALUE, &parmKey);
616 if (code != ERROR_SUCCESS) {
617 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
618 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
619 NULL, code, 0, (LPTSTR)&msgBuf, 0, NULL);
620 StringCbPrintfA(buf, sizeof(buf),
621 "Failure in configuration while opening Registry: %s",
623 osi_panic(buf, __FILE__, __LINE__);
626 dummyLen = sizeof(maxcpus);
627 code = RegQueryValueEx(parmKey, "MaxCPUs", NULL, NULL,
628 (BYTE *) &maxcpus, &dummyLen);
629 if (code == ERROR_SUCCESS) {
631 DWORD_PTR processAffinityMask, systemAffinityMask;
633 hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION,
634 FALSE, GetCurrentProcessId());
635 if ( hProcess != NULL &&
636 GetProcessAffinityMask(hProcess, &processAffinityMask, &systemAffinityMask) )
639 DWORD_PTR mask, newAffinityMask;
646 for ( i=0, n=0, mask=1, newAffinityMask=0; i<bits && n<maxcpus; i++ ) {
647 if ( processAffinityMask & mask ) {
648 newAffinityMask |= mask;
654 SetProcessAffinityMask(hProcess, newAffinityMask);
655 CloseHandle(hProcess);
656 afsi_log("CPU Restrictions set to %d cpu(s); %d cpu(s) available", maxcpus, n);
658 afsi_log("CPU Restrictions set to %d cpu(s); unable to access process information", maxcpus);
662 dummyLen = sizeof(TraceOption);
663 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
664 (BYTE *) &TraceOption, &dummyLen);
665 afsi_log("Trace Options = %lX", TraceOption);
667 dummyLen = sizeof(traceBufSize);
668 code = RegQueryValueEx(parmKey, "TraceBufferSize", NULL, NULL,
669 (BYTE *) &traceBufSize, &dummyLen);
670 if (code == ERROR_SUCCESS)
671 afsi_log("Trace Buffer size %d", traceBufSize);
673 traceBufSize = CM_CONFIGDEFAULT_TRACEBUFSIZE;
674 afsi_log("Default trace buffer size %d", traceBufSize);
677 /* setup and enable debug log */
678 afsd_logp = osi_LogCreate("afsd", traceBufSize);
679 afsi_log("osi_LogCreate log addr %x", PtrToUlong(afsd_logp));
680 if ((TraceOption & 0x8)
685 osi_LogEnable(afsd_logp);
689 osi_Log0(afsd_logp, "Log init");
691 dummyLen = sizeof(cacheSize);
692 code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
693 (BYTE *) &cacheSize, &dummyLen);
694 if (code == ERROR_SUCCESS)
695 afsi_log("Cache size %d", cacheSize);
697 cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
698 afsi_log("Default cache size %d", cacheSize);
701 dummyLen = sizeof(logChunkSize);
702 code = RegQueryValueEx(parmKey, "ChunkSize", NULL, NULL,
703 (BYTE *) &logChunkSize, &dummyLen);
704 if (code == ERROR_SUCCESS) {
705 if (logChunkSize < 12 || logChunkSize > 30) {
706 afsi_log("Invalid chunk size %d, using default",
708 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
711 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
713 cm_logChunkSize = logChunkSize;
714 cm_chunkSize = 1 << logChunkSize;
715 afsi_log("Chunk size %u (%d)", cm_chunkSize, cm_logChunkSize);
717 dummyLen = sizeof(blockSize);
718 code = RegQueryValueEx(parmKey, "blockSize", NULL, NULL,
719 (BYTE *) &blockSize, &dummyLen);
720 if (code == ERROR_SUCCESS) {
722 (blockSize > 1024 && (blockSize % CM_CONFIGDEFAULT_BLOCKSIZE != 0)))
724 afsi_log("Invalid block size %u specified, using default", blockSize);
725 blockSize = CM_CONFIGDEFAULT_BLOCKSIZE;
728 * if the blockSize is less than 1024 we permit the blockSize to be
729 * specified in multiples of the default blocksize
731 if (blockSize <= 1024)
732 blockSize *= CM_CONFIGDEFAULT_BLOCKSIZE;
735 blockSize = CM_CONFIGDEFAULT_BLOCKSIZE;
737 if (blockSize > cm_chunkSize) {
738 afsi_log("Block size (%d) cannot be larger than Chunk size (%d).",
739 blockSize, cm_chunkSize);
740 blockSize = cm_chunkSize;
742 if (cm_chunkSize % blockSize != 0) {
743 afsi_log("Block size (%d) must be a factor of Chunk size (%d).",
744 blockSize, cm_chunkSize);
745 blockSize = CM_CONFIGDEFAULT_BLOCKSIZE;
747 afsi_log("Block size %u", blockSize);
749 dummyLen = sizeof(numBkgD);
750 code = RegQueryValueEx(parmKey, "Daemons", NULL, NULL,
751 (BYTE *) &numBkgD, &dummyLen);
752 if (code == ERROR_SUCCESS)
753 afsi_log("%d background daemons", numBkgD);
755 numBkgD = CM_CONFIGDEFAULT_DAEMONS;
756 afsi_log("Defaulting to %d background daemons", numBkgD);
759 dummyLen = sizeof(numSvThreads);
760 code = RegQueryValueEx(parmKey, "ServerThreads", NULL, NULL,
761 (BYTE *) &numSvThreads, &dummyLen);
762 if (code == ERROR_SUCCESS)
763 afsi_log("%d server threads", numSvThreads);
765 numSvThreads = CM_CONFIGDEFAULT_SVTHREADS;
766 afsi_log("Defaulting to %d server threads", numSvThreads);
769 dummyLen = sizeof(stats);
770 code = RegQueryValueEx(parmKey, "Stats", NULL, NULL,
771 (BYTE *) &stats, &dummyLen);
772 if (code == ERROR_SUCCESS)
773 afsi_log("Status cache size %d", stats);
775 stats = CM_CONFIGDEFAULT_STATS;
776 afsi_log("Default status cache size %d", stats);
779 dummyLen = sizeof(ltt);
780 code = RegQueryValueEx(parmKey, "LogoffTokenTransfer", NULL, NULL,
781 (BYTE *) <t, &dummyLen);
782 if (code != ERROR_SUCCESS)
784 smb_LogoffTokenTransfer = ltt;
785 afsi_log("Logoff token transfer %s", (ltt ? "on" : "off"));
788 dummyLen = sizeof(ltto);
789 code = RegQueryValueEx(parmKey, "LogoffTokenTransferTimeout",
790 NULL, NULL, (BYTE *) <to, &dummyLen);
791 if (code != ERROR_SUCCESS)
796 smb_LogoffTransferTimeout = ltto;
797 afsi_log("Logoff token transfer timeout %d seconds", ltto);
799 dummyLen = sizeof(cm_rootVolumeName);
800 code = RegQueryValueEx(parmKey, "RootVolume", NULL, NULL,
801 cm_rootVolumeName, &dummyLen);
802 if (code == ERROR_SUCCESS)
803 afsi_log("Root volume %s", cm_rootVolumeName);
805 StringCbCopyA(cm_rootVolumeName, sizeof(cm_rootVolumeName), "root.afs");
806 afsi_log("Default root volume name root.afs");
809 cm_mountRootLen = sizeof(cm_mountRoot);
810 code = RegQueryValueEx(parmKey, "MountRoot", NULL, NULL,
811 cm_mountRoot, &cm_mountRootLen);
812 if (code == ERROR_SUCCESS) {
813 afsi_log("Mount root %s", cm_mountRoot);
814 cm_mountRootLen = (DWORD)strlen(cm_mountRoot);
816 StringCbCopyA(cm_mountRoot, sizeof(cm_mountRoot), "/afs");
821 dummyLen = sizeof(buf);
822 code = RegQueryValueEx(parmKey, "CachePath", NULL, ®Type,
824 if (code == ERROR_SUCCESS && buf[0]) {
825 if (regType == REG_EXPAND_SZ) {
826 dummyLen = ExpandEnvironmentStrings(buf, cm_CachePath, sizeof(cm_CachePath));
827 if (dummyLen > sizeof(cm_CachePath)) {
828 afsi_log("Cache path [%s] longer than %d after expanding env strings", buf, sizeof(cm_CachePath));
829 osi_panic("CachePath too long", __FILE__, __LINE__);
832 StringCbCopyA(cm_CachePath, sizeof(cm_CachePath), buf);
834 afsi_log("Cache path %s", cm_CachePath);
836 dummyLen = ExpandEnvironmentStrings("%TEMP%\\AFSCache", cm_CachePath, sizeof(cm_CachePath));
837 if (dummyLen > sizeof(cm_CachePath)) {
838 afsi_log("Cache path [%%TEMP%%\\AFSCache] longer than %d after expanding env strings",
839 sizeof(cm_CachePath));
840 osi_panic("CachePath too long", __FILE__, __LINE__);
842 afsi_log("Default cache path %s", cm_CachePath);
845 dummyLen = sizeof(virtualCache);
846 code = RegQueryValueEx(parmKey, "NonPersistentCaching", NULL, NULL,
847 (LPBYTE)&virtualCache, &dummyLen);
848 afsi_log("Cache type is %s", (virtualCache?"VIRTUAL":"FILE"));
851 dummyLen = sizeof(cm_ValidateCache);
852 code = RegQueryValueEx(parmKey, "ValidateCache", NULL, NULL,
853 (LPBYTE)&cm_ValidateCache, &dummyLen);
854 if ( cm_ValidateCache < 0 || cm_ValidateCache > 2 )
855 cm_ValidateCache = 1;
856 switch (cm_ValidateCache) {
858 afsi_log("Cache Validation disabled");
861 afsi_log("Cache Validation on Startup");
864 afsi_log("Cache Validation on Startup and Shutdown");
869 dummyLen = sizeof(traceOnPanic);
870 code = RegQueryValueEx(parmKey, "TrapOnPanic", NULL, NULL,
871 (BYTE *) &traceOnPanic, &dummyLen);
872 if (code != ERROR_SUCCESS)
873 traceOnPanic = 1; /* log */
874 afsi_log("Set to %s on panic", traceOnPanic ? "trap" : "not trap");
876 dummyLen = sizeof(reportSessionStartups);
877 code = RegQueryValueEx(parmKey, "ReportSessionStartups", NULL, NULL,
878 (BYTE *) &reportSessionStartups, &dummyLen);
879 if (code == ERROR_SUCCESS)
880 afsi_log("Session startups %s be recorded in the Event Log",
881 reportSessionStartups ? "will" : "will not");
883 reportSessionStartups = 0;
887 for ( i=0; i < MAXNUMSYSNAMES; i++ ) {
888 cm_sysNameList[i] = osi_Alloc(MAXSYSNAME);
889 cm_sysNameList[i][0] = '\0';
891 cm_sysName = cm_sysNameList[0];
893 dummyLen = sizeof(buf);
894 code = RegQueryValueEx(parmKey, "SysName", NULL, NULL, buf, &dummyLen);
895 if (code != ERROR_SUCCESS || !buf[0]) {
897 StringCbCopyA(buf, sizeof(buf), "ia64_win64");
898 #elif defined(_AMD64_)
899 StringCbCopyA(buf, sizeof(buf), "amd64_win64 x86_win32 i386_w2k");
900 #else /* assume x86 32-bit */
901 StringCbCopyA(buf, sizeof(buf), "x86_win32 i386_w2k i386_nt40");
904 afsi_log("Sys name %s", buf);
906 /* breakup buf into individual search string entries */
907 for (p = q = buf; p < buf + dummyLen; p++)
909 if (*p == '\0' || isspace(*p)) {
910 memcpy(cm_sysNameList[cm_sysNameCount],q,p-q);
911 cm_sysNameList[cm_sysNameCount][p-q] = '\0';
918 } while (*p == '\0' || isspace(*p));
924 StringCbCopyA(cm_sysName, MAXSYSNAME, cm_sysNameList[0]);
926 dummyLen = sizeof(cryptall);
927 code = RegQueryValueEx(parmKey, "SecurityLevel", NULL, NULL,
928 (BYTE *) &cryptall, &dummyLen);
929 if (code == ERROR_SUCCESS) {
930 afsi_log("SecurityLevel is %s", cryptall?"crypt":"clear");
933 afsi_log("Default SecurityLevel is clear");
937 LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_ON);
939 LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_OFF);
942 dummyLen = sizeof(cm_dnsEnabled);
943 code = RegQueryValueEx(parmKey, "UseDNS", NULL, NULL,
944 (BYTE *) &cm_dnsEnabled, &dummyLen);
945 if (code == ERROR_SUCCESS) {
946 afsi_log("DNS %s be used to find AFS cell servers",
947 cm_dnsEnabled ? "will" : "will not");
950 cm_dnsEnabled = 1; /* default on */
951 afsi_log("Default to use DNS to find AFS cell servers");
953 #else /* AFS_AFSDB_ENV */
954 afsi_log("AFS not built with DNS support to find AFS cell servers");
955 #endif /* AFS_AFSDB_ENV */
957 #ifdef AFS_FREELANCE_CLIENT
958 dummyLen = sizeof(cm_freelanceEnabled);
959 code = RegQueryValueEx(parmKey, "FreelanceClient", NULL, NULL,
960 (BYTE *) &cm_freelanceEnabled, &dummyLen);
961 if (code == ERROR_SUCCESS) {
962 afsi_log("Freelance client feature %s activated",
963 cm_freelanceEnabled ? "is" : "is not");
966 cm_freelanceEnabled = 1; /* default on */
968 #endif /* AFS_FREELANCE_CLIENT */
970 dummyLen = sizeof(smb_hideDotFiles);
971 code = RegQueryValueEx(parmKey, "HideDotFiles", NULL, NULL,
972 (BYTE *) &smb_hideDotFiles, &dummyLen);
973 if (code != ERROR_SUCCESS) {
974 smb_hideDotFiles = 1; /* default on */
976 afsi_log("Dot files/dirs will %sbe marked hidden",
977 smb_hideDotFiles ? "" : "not ");
979 dummyLen = sizeof(smb_maxMpxRequests);
980 code = RegQueryValueEx(parmKey, "MaxMpxRequests", NULL, NULL,
981 (BYTE *) &smb_maxMpxRequests, &dummyLen);
982 if (code != ERROR_SUCCESS) {
983 smb_maxMpxRequests = 50;
985 afsi_log("Maximum number of multiplexed sessions is %d", smb_maxMpxRequests);
987 dummyLen = sizeof(smb_maxVCPerServer);
988 code = RegQueryValueEx(parmKey, "MaxVCPerServer", NULL, NULL,
989 (BYTE *) &smb_maxVCPerServer, &dummyLen);
990 if (code != ERROR_SUCCESS) {
991 smb_maxVCPerServer = 100;
993 afsi_log("Maximum number of VCs per server is %d", smb_maxVCPerServer);
995 dummyLen = sizeof(smb_authType);
996 code = RegQueryValueEx(parmKey, "SMBAuthType", NULL, NULL,
997 (BYTE *) &smb_authType, &dummyLen);
999 if (code != ERROR_SUCCESS ||
1000 (smb_authType != SMB_AUTH_EXTENDED && smb_authType != SMB_AUTH_NTLM && smb_authType != SMB_AUTH_NONE)) {
1001 smb_authType = SMB_AUTH_EXTENDED; /* default is to use extended authentication */
1003 afsi_log("SMB authentication type is %s", ((smb_authType == SMB_AUTH_NONE)?"NONE":((smb_authType == SMB_AUTH_EXTENDED)?"EXTENDED":"NTLM")));
1005 dummyLen = sizeof(rx_nojumbo);
1006 code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
1007 (BYTE *) &rx_nojumbo, &dummyLen);
1008 if (code != ERROR_SUCCESS) {
1012 afsi_log("RX Jumbograms are disabled");
1014 dummyLen = sizeof(rx_mtu);
1015 code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
1016 (BYTE *) &rx_mtu, &dummyLen);
1017 if (code != ERROR_SUCCESS || !rx_mtu) {
1021 afsi_log("RX maximum MTU is %d", rx_mtu);
1023 dummyLen = sizeof(rx_enable_peer_stats);
1024 code = RegQueryValueEx(parmKey, "RxEnablePeerStats", NULL, NULL,
1025 (BYTE *) &rx_enable_peer_stats, &dummyLen);
1026 if (code != ERROR_SUCCESS) {
1027 rx_enable_peer_stats = 0;
1029 if (rx_enable_peer_stats)
1030 afsi_log("RX Peer Statistics gathering is enabled");
1032 dummyLen = sizeof(rx_enable_process_stats);
1033 code = RegQueryValueEx(parmKey, "RxEnableProcessStats", NULL, NULL,
1034 (BYTE *) &rx_enable_process_stats, &dummyLen);
1035 if (code != ERROR_SUCCESS) {
1036 rx_enable_process_stats = 0;
1038 if (rx_enable_process_stats)
1039 afsi_log("RX Process Statistics gathering is enabled");
1041 dummyLen = sizeof(DWORD);
1042 code = RegQueryValueEx(parmKey, "CallBackPort", NULL, NULL,
1043 (BYTE *) &dwValue, &dummyLen);
1044 if (code == ERROR_SUCCESS) {
1045 cm_callbackport = (unsigned short) dwValue;
1047 afsi_log("CM CallBackPort is %u", cm_callbackport);
1049 dummyLen = sizeof(DWORD);
1050 code = RegQueryValueEx(parmKey, "EnableServerLocks", NULL, NULL,
1051 (BYTE *) &dwValue, &dummyLen);
1052 if (code == ERROR_SUCCESS) {
1053 cm_enableServerLocks = (unsigned short) dwValue;
1055 switch (cm_enableServerLocks) {
1057 afsi_log("EnableServerLocks: never");
1060 afsi_log("EnableServerLocks: always");
1064 afsi_log("EnableServerLocks: server requested");
1068 dummyLen = sizeof(DWORD);
1069 code = RegQueryValueEx(parmKey, "DeleteReadOnly", NULL, NULL,
1070 (BYTE *) &dwValue, &dummyLen);
1071 if (code == ERROR_SUCCESS) {
1072 cm_deleteReadOnly = (unsigned short) dwValue;
1074 afsi_log("CM DeleteReadOnly is %u", cm_deleteReadOnly);
1077 dummyLen = sizeof(DWORD);
1078 code = RegQueryValueEx(parmKey, "BPlusTrees", NULL, NULL,
1079 (BYTE *) &dwValue, &dummyLen);
1080 if (code == ERROR_SUCCESS) {
1081 cm_BPlusTrees = (unsigned short) dwValue;
1083 afsi_log("CM BPlusTrees is %u", cm_BPlusTrees);
1085 if (cm_BPlusTrees && !cm_InitBPlusDir()) {
1087 afsi_log("CM BPlusTree initialization failure; disabled for this session");
1090 afsi_log("CM BPlusTrees is not supported");
1093 if ((RegQueryValueEx( parmKey, "PrefetchExecutableExtensions", 0,
1094 ®Type, NULL, &dummyLen) == ERROR_SUCCESS) &&
1095 (regType == REG_MULTI_SZ))
1098 dummyLen += 3; /* in case the source string is not nul terminated */
1099 pSz = malloc(dummyLen);
1100 if ((RegQueryValueEx( parmKey, "PrefetchExecutableExtensions", 0, ®Type,
1101 pSz, &dummyLen) == ERROR_SUCCESS) &&
1102 (regType == REG_MULTI_SZ))
1107 for (cnt = 0, p = pSz; (p - pSz < dummyLen) && *p; cnt++, p += strlen(p) + 1);
1109 smb_ExecutableExtensions = malloc(sizeof(char *) * (cnt+1));
1111 for (cnt = 0, p = pSz; (p - pSz < dummyLen) && *p; cnt++, p += strlen(p) + 1)
1113 smb_ExecutableExtensions[cnt] = p;
1114 afsi_log("PrefetchExecutableExtension: \"%s\"", p);
1116 smb_ExecutableExtensions[cnt] = NULL;
1119 if (!smb_ExecutableExtensions)
1122 if (!smb_ExecutableExtensions)
1123 afsi_log("No PrefetchExecutableExtensions");
1125 dummyLen = sizeof(DWORD);
1126 code = RegQueryValueEx(parmKey, "OfflineReadOnlyIsValid", NULL, NULL,
1127 (BYTE *) &dwValue, &dummyLen);
1128 if (code == ERROR_SUCCESS) {
1129 cm_OfflineROIsValid = (unsigned short) dwValue;
1131 afsi_log("CM OfflineReadOnlyIsValid is %u", cm_deleteReadOnly);
1133 dummyLen = sizeof(DWORD);
1134 code = RegQueryValueEx(parmKey, "GiveUpAllCallBacks", NULL, NULL,
1135 (BYTE *) &dwValue, &dummyLen);
1136 if (code == ERROR_SUCCESS) {
1137 cm_giveUpAllCBs = (unsigned short) dwValue;
1139 afsi_log("CM GiveUpAllCallBacks is %u", cm_giveUpAllCBs);
1141 RegCloseKey (parmKey);
1143 cacheBlocks = ((afs_uint64)cacheSize * 1024) / blockSize;
1145 /* get network related info */
1146 cm_noIPAddr = CM_MAXINTERFACE_ADDR;
1147 code = syscfg_GetIFInfo(&cm_noIPAddr,
1148 cm_IPAddr, cm_SubnetMask,
1149 cm_NetMtu, cm_NetFlags);
1151 if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
1152 afsi_log("syscfg_GetIFInfo error code %d", code);
1154 afsi_log("First Network address %x SubnetMask %x",
1155 cm_IPAddr[0], cm_SubnetMask[0]);
1158 * Save client configuration for GetCacheConfig requests
1160 cm_initParams.nChunkFiles = 0;
1161 cm_initParams.nStatCaches = stats;
1162 cm_initParams.nDataCaches = (afs_uint32)(cacheBlocks > 0xFFFFFFFF ? 0xFFFFFFFF : cacheBlocks);
1163 cm_initParams.nVolumeCaches = stats/2;
1164 cm_initParams.firstChunkSize = cm_chunkSize;
1165 cm_initParams.otherChunkSize = cm_chunkSize;
1166 cm_initParams.cacheSize = cacheSize;
1167 cm_initParams.setTime = 0;
1168 cm_initParams.memCache = 1;
1170 /* Ensure the AFS Netbios Name is registered to allow loopback access */
1171 configureBackConnectionHostNames();
1173 /* init user daemon, and other packages */
1186 code = cm_InitMappedMemory(virtualCache, cm_CachePath, stats, cm_chunkSize, cacheBlocks, blockSize);
1187 afsi_log("cm_InitMappedMemory code %x", code);
1189 *reasonP = "error initializing cache file";
1193 #ifdef AFS_AFSDB_ENV
1194 #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
1195 if (cm_InitDNS(cm_dnsEnabled) == -1)
1196 cm_dnsEnabled = 0; /* init failed, so deactivate */
1197 afsi_log("cm_InitDNS %d", cm_dnsEnabled);
1201 /* Set RX parameters before initializing RX */
1204 afsi_log("rx_SetNoJumbo successful");
1207 if ( rx_mtu != -1 ) {
1208 rx_SetMaxMTU(rx_mtu);
1209 afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
1212 /* initialize RX, and tell it to listen to the callbackport,
1213 * which is used for callback RPC messages.
1215 code = rx_Init(htons(cm_callbackport));
1217 afsi_log("rx_Init code %x - retrying with a random port number", code);
1220 afsi_log("rx_Init code %x", code);
1222 *reasonP = "afsd: failed to init rx client";
1226 /* create an unauthenticated service #1 for callbacks */
1227 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1228 serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
1229 RXAFSCB_ExecuteRequest);
1230 afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1231 if (serverp == NULL) {
1232 *reasonP = "unknown error";
1236 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1237 serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
1238 &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
1239 afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1240 if (serverp == NULL) {
1241 *reasonP = "unknown error";
1245 /* start server threads, *not* donating this one to the pool */
1247 afsi_log("rx_StartServer");
1249 if (rx_enable_peer_stats)
1250 rx_enablePeerRPCStats();
1252 if (rx_enable_process_stats)
1253 rx_enableProcessRPCStats();
1255 code = cm_GetRootCellName(rootCellName);
1256 afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s",
1257 code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
1258 if (code != 0 && !cm_freelanceEnabled)
1260 *reasonP = "can't find root cell name in CellServDB";
1263 else if (cm_freelanceEnabled)
1264 cm_data.rootCellp = NULL;
1266 if (code == 0 && !cm_freelanceEnabled)
1268 cm_data.rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
1269 afsi_log("cm_GetCell addr %x", PtrToUlong(cm_data.rootCellp));
1270 if (cm_data.rootCellp == NULL)
1272 *reasonP = "can't find root cell in afsdcell.ini";
1277 #ifdef AFS_FREELANCE_CLIENT
1278 if (cm_freelanceEnabled)
1282 /* Initialize the RPC server for session keys */
1285 afsd_InitServerPreferences();
1289 int afsd_ShutdownCM(void)
1291 cm_ReleaseSCache(cm_data.rootSCachep);
1296 int afsd_InitDaemons(char **reasonP)
1303 /* this should really be in an init daemon from here on down */
1305 if (!cm_freelanceEnabled) {
1308 osi_Log0(afsd_logp, "Loading Root Volume from cell");
1310 code = cm_GetVolumeByName(cm_data.rootCellp, cm_rootVolumeName, cm_rootUserp,
1311 &req, CM_GETVOL_FLAG_CREATE, &cm_data.rootVolumep);
1312 afsi_log("cm_GetVolumeByName code %x root vol %x", code,
1313 (code ? (cm_volume_t *)-1 : cm_data.rootVolumep));
1314 } while (code && --attempts);
1316 *reasonP = "can't find root volume in root cell";
1321 /* compute the root fid */
1322 if (!cm_freelanceEnabled) {
1323 cm_data.rootFid.cell = cm_data.rootCellp->cellID;
1324 cm_data.rootFid.volume = cm_GetROVolumeID(cm_data.rootVolumep);
1325 cm_data.rootFid.vnode = 1;
1326 cm_data.rootFid.unique = 1;
1329 cm_FakeRootFid(&cm_data.rootFid);
1331 code = cm_GetSCache(&cm_data.rootFid, &cm_data.rootSCachep, cm_rootUserp, &req);
1332 afsi_log("cm_GetSCache code %x scache %x", code,
1333 (code ? (cm_scache_t *)-1 : cm_data.rootSCachep));
1335 *reasonP = "unknown error";
1339 cm_InitDaemon(numBkgD);
1340 afsi_log("cm_InitDaemon complete");
1345 int afsd_InitSMB(char **reasonP, void *aMBfunc)
1352 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1353 0, KEY_QUERY_VALUE, &parmKey);
1354 if (code == ERROR_SUCCESS) {
1355 dummyLen = sizeof(DWORD);
1356 code = RegQueryValueEx(parmKey, "StoreAnsiFilenames", NULL, NULL,
1357 (BYTE *) &dwValue, &dummyLen);
1358 if (code == ERROR_SUCCESS)
1359 smb_StoreAnsiFilenames = dwValue ? 1 : 0;
1360 RegCloseKey (parmKey);
1363 /* Do this last so that we don't handle requests before init is done.
1364 * Here we initialize the SMB listener.
1366 smb_Init(afsd_logp, smb_UseV3, numSvThreads, aMBfunc);
1367 afsi_log("smb_Init complete");
1380 #pragma pack( push, before_imagehlp, 8 )
1381 #include <imagehlp.h>
1382 #pragma pack( pop, before_imagehlp )
1384 #define MAXNAMELEN 1024
1386 void afsd_printStack(HANDLE hThread, CONTEXT *c)
1388 HANDLE hProcess = GetCurrentProcess();
1390 #if defined(_AMD64_)
1392 #elif defined(_X86_)
1396 char functionName[MAXNAMELEN];
1398 IMAGEHLP_MODULE Module;
1402 IMAGEHLP_SYMBOL *pSym;
1404 afsi_log_useTimestamp = 0;
1406 pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
1408 memset( &s, '\0', sizeof s );
1409 if (!SymInitialize(hProcess, NULL, 1) )
1411 afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
1413 SymCleanup( hProcess );
1419 symOptions = SymGetOptions();
1420 symOptions |= SYMOPT_LOAD_LINES;
1421 symOptions &= ~SYMOPT_UNDNAME;
1422 SymSetOptions( symOptions );
1425 * init STACKFRAME for first call
1426 * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
1427 * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
1428 * and good riddance.
1430 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
1431 #error The STACKFRAME initialization in afsd_printStack() for this platform
1432 #error must be properly configured
1433 #elif defined(_AMD64_)
1434 s.AddrPC.Offset = c->Rip;
1435 s.AddrPC.Mode = AddrModeFlat;
1436 s.AddrFrame.Offset = c->Rbp;
1437 s.AddrFrame.Mode = AddrModeFlat;
1439 s.AddrPC.Offset = c->Eip;
1440 s.AddrPC.Mode = AddrModeFlat;
1441 s.AddrFrame.Offset = c->Ebp;
1442 s.AddrFrame.Mode = AddrModeFlat;
1445 memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
1446 pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
1447 pSym->MaxNameLength = MAXNAMELEN;
1449 memset( &Line, '\0', sizeof Line );
1450 Line.SizeOfStruct = sizeof Line;
1452 memset( &Module, '\0', sizeof Module );
1453 Module.SizeOfStruct = sizeof Module;
1457 afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
1459 for ( frameNum = 0; ; ++ frameNum )
1462 * get next stack frame (StackWalk(), SymFunctionTableAccess(),
1463 * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
1464 * ERROR_NOACCESS (998), you can assume that either you are done, or
1465 * that the stack is so hosed that the next deeper frame could not be
1468 if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c,
1469 NULL, SymFunctionTableAccess, SymGetModuleBase,
1473 /* display its contents */
1474 afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
1475 frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
1476 s.AddrPC.Offset, s.AddrReturn.Offset,
1477 s.AddrFrame.Offset, s.AddrStack.Offset );
1479 if ( s.AddrPC.Offset == 0 )
1481 afsi_log("(-nosymbols- PC == 0)" );
1485 /* show procedure info from a valid PC */
1486 if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
1488 if ( GetLastError() != ERROR_INVALID_ADDRESS )
1490 afsi_log("SymGetSymFromAddr(): errno = %lu",
1496 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN,
1498 afsi_log("%s", functionName );
1502 afsi_log(" %+ld bytes", (long) offset);
1506 if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
1508 if (GetLastError() != ERROR_INVALID_ADDRESS)
1510 afsi_log("Error: SymGetLineFromAddr(): errno = %lu",
1516 afsi_log(" Line: %s(%lu) %+ld bytes", Line.FileName,
1517 Line.LineNumber, offset);
1521 /* no return address means no deeper stackframe */
1522 if (s.AddrReturn.Offset == 0)
1529 if (GetLastError() != 0)
1531 afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
1534 SymCleanup(hProcess);
1539 static DWORD *afsd_crtDbgBreakCurrent = NULL;
1540 static DWORD afsd_crtDbgBreaks[256];
1543 static EFaultRepRetVal (WINAPI *pReportFault)(LPEXCEPTION_POINTERS pep, DWORD dwMode) = NULL;
1544 static BOOL (WINAPI *pMiniDumpWriteDump)(HANDLE hProcess,DWORD ProcessId,HANDLE hFile,
1545 MINIDUMP_TYPE DumpType,
1546 PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
1547 PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
1548 PMINIDUMP_CALLBACK_INFORMATION CallbackParam) = NULL;
1557 code = GetEnvironmentVariable("TEMP", wd, sizeof(wd));
1558 if ( code == 0 || code > sizeof(wd) )
1560 if (!GetWindowsDirectory(wd, sizeof(wd)))
1563 StringCbCatA(wd, sizeof(wd), "\\afsd.dmp");
1564 return CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1565 CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
1569 GenerateMiniDump(PEXCEPTION_POINTERS ep)
1571 if (IsDebuggerPresent())
1576 // Generate exception to get proper context in dump
1579 RaiseException(DBG_CONTINUE, 0, 0, NULL);
1581 __except(GenerateMiniDump(GetExceptionInformation()), EXCEPTION_CONTINUE_EXECUTION)
1587 MINIDUMP_EXCEPTION_INFORMATION eInfo;
1588 HANDLE hFile = NULL;
1589 HMODULE hDbgHelp = NULL;
1591 hDbgHelp = LoadLibrary("Dbghelp.dll");
1592 if ( hDbgHelp == NULL )
1595 (FARPROC) pMiniDumpWriteDump = GetProcAddress(hDbgHelp, "MiniDumpWriteDump");
1596 if ( pMiniDumpWriteDump == NULL ) {
1597 FreeLibrary(hDbgHelp);
1601 hFile = OpenDumpFile();
1608 DWORD dwMiniDumpType = MiniDumpWithDataSegs;
1610 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1611 0, KEY_QUERY_VALUE, &parmKey);
1612 if (code == ERROR_SUCCESS) {
1613 dummyLen = sizeof(DWORD);
1614 code = RegQueryValueEx(parmKey, "MiniDumpType", NULL, NULL,
1615 (BYTE *) &dwValue, &dummyLen);
1616 if (code == ERROR_SUCCESS)
1617 dwMiniDumpType = dwValue;
1618 RegCloseKey (parmKey);
1621 eInfo.ThreadId = GetCurrentThreadId();
1622 eInfo.ExceptionPointers = ep;
1623 eInfo.ClientPointers = FALSE;
1625 pMiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(),
1626 hFile, dwMiniDumpType, ep ? &eInfo : NULL,
1631 FreeLibrary(hDbgHelp);
1635 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
1639 BOOL allocRequestBrk = FALSE;
1641 HMODULE hLib = NULL;
1643 afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n",
1644 ep->ExceptionRecord->ExceptionCode,
1645 ep->ExceptionRecord->ExceptionAddress);
1648 if (afsd_crtDbgBreakCurrent &&
1649 *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
1651 allocRequestBrk = TRUE;
1652 afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
1656 /* save context if we want to print the stack information */
1657 context = *ep->ContextRecord;
1659 afsd_printStack(GetCurrentThread(), &context);
1661 GenerateMiniDump(ep);
1663 hLib = LoadLibrary("Faultrep.dll");
1665 (FARPROC) pReportFault = GetProcAddress(hLib, "ReportFault");
1667 pReportFault(ep, 0);
1671 if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
1673 afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
1676 if (allocRequestBrk)
1678 afsd_crtDbgBreakCurrent++;
1679 _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
1683 ep->ContextRecord->Eip++;
1685 #if defined(_AMD64_)
1686 ep->ContextRecord->Rip++;
1688 return EXCEPTION_CONTINUE_EXECUTION;
1692 return EXCEPTION_CONTINUE_SEARCH;
1696 void afsd_SetUnhandledExceptionFilter()
1698 SetUnhandledExceptionFilter(afsd_ExceptionFilter);
1702 void afsd_DbgBreakAllocInit()
1704 memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
1705 afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
1708 void afsd_DbgBreakAdd(DWORD requestNumber)
1711 for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
1713 if (afsd_crtDbgBreaks[i] == -1)
1718 afsd_crtDbgBreaks[i] = requestNumber;
1720 _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);