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_followBackupPath;
46 extern int cm_deleteReadOnly;
48 extern afs_int32 cm_BPlusTrees;
50 extern afs_int32 cm_OfflineROIsValid;
51 extern afs_int32 cm_giveUpAllCBs;
52 extern const char **smb_ExecutableExtensions;
56 cm_config_data_t cm_data;
58 char cm_rootVolumeName[VL_MAXNAMELEN];
59 DWORD cm_rootVolumeNameLen;
60 char cm_mountRoot[1024];
61 DWORD cm_mountRootLen;
64 #ifdef AFS_FREELANCE_CLIENT
66 #endif /* freelance */
79 char cm_HostName[200];
81 unsigned short cm_callbackport = CM_DEFAULT_CALLBACKPORT;
83 char cm_NetbiosName[MAX_NB_NAME_LENGTH] = "";
85 char cm_CachePath[MAX_PATH];
86 DWORD cm_CachePathLen;
87 DWORD cm_ValidateCache = 1;
89 BOOL reportSessionStartups = FALSE;
91 cm_initparams_v1 cm_initParams;
94 unsigned int cm_sysNameCount = 0;
95 char *cm_sysNameList[MAXNUMSYSNAMES];
97 DWORD TraceOption = 0;
100 * AFSD Initialization Log
102 * This is distinct from the regular debug logging facility.
103 * Log items go directly to a file, not to an array in memory, so that even
104 * if AFSD crashes, the log can be inspected.
110 int cm_dnsEnabled = 1;
114 static int afsi_log_useTimestamp = 1;
117 afsi_log(char *pattern, ...)
119 char s[256], t[100], d[100], u[512];
122 va_start(ap, pattern);
124 StringCbVPrintfA(s, sizeof(s), pattern, ap);
125 if ( afsi_log_useTimestamp ) {
126 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
127 GetDateFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, d, sizeof(d));
128 StringCbPrintfA(u, sizeof(u), "%s %s: %s\r\n", d, t, s);
129 if (afsi_file != INVALID_HANDLE_VALUE)
130 WriteFile(afsi_file, u, (DWORD)strlen(u), &zilch, NULL);
135 if (afsi_file != INVALID_HANDLE_VALUE)
136 WriteFile(afsi_file, s, (DWORD)strlen(s), &zilch, NULL);
140 extern initUpperCaseTable();
141 void afsd_initUpperCaseTable()
143 initUpperCaseTable();
150 char t[100], u[100], *p, *path;
156 DWORD maxLogSize = 100 * 1024;
158 afsi_file = INVALID_HANDLE_VALUE;
159 code = GetTempPath(sizeof(wd)-15, wd);
160 if ( code == 0 || code > (sizeof(wd)-15) )
161 return; /* unable to create a log */
163 StringCbCatA(wd, sizeof(wd), "\\afsd_init.log");
164 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
165 afsi_file = CreateFile(wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
166 OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
168 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
169 0, KEY_QUERY_VALUE, &parmKey);
170 if (code == ERROR_SUCCESS) {
171 dummyLen = sizeof(maxLogSize);
172 code = RegQueryValueEx(parmKey, "MaxLogSize", NULL, NULL,
173 (BYTE *) &maxLogSize, &dummyLen);
174 RegCloseKey (parmKey);
178 dwLow = GetFileSize( afsi_file, &dwHigh );
179 if ( dwHigh > 0 || dwLow >= maxLogSize ) {
180 CloseHandle(afsi_file);
181 afsi_file = CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
182 CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
186 SetFilePointer(afsi_file, 0, NULL, FILE_END);
187 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, u, sizeof(u));
188 StringCbCatA(t, sizeof(t), ": Create log file\r\n");
189 StringCbCatA(u, sizeof(u), ": Created log file\r\n");
190 WriteFile(afsi_file, t, (DWORD)strlen(t), &zilch, NULL);
191 WriteFile(afsi_file, u, (DWORD)strlen(u), &zilch, NULL);
193 code = GetEnvironmentVariable("PATH", NULL, 0);
195 code = GetEnvironmentVariable("PATH", path, code);
196 WriteFile(afsi_file, p, (DWORD)strlen(p), &zilch, NULL);
197 WriteFile(afsi_file, path, (DWORD)strlen(path), &zilch, NULL);
198 WriteFile(afsi_file, "\r\n", (DWORD)1, &zilch, NULL);
201 /* Initialize C RTL Code Page conversion functions */
202 /* All of the path info obtained from the SMB client is in the OEM code page */
203 afsi_log("OEM Code Page = %d", GetOEMCP());
204 afsi_log("locale = %s", setlocale(LC_ALL,NULL));
206 /* Two things to look into. First, should mbstowcs() be performing
207 * character set translations from OEM to Unicode in smb3.c;
208 * Second, do we need to set this translation in each function
209 * due to multi-threading.
211 afsi_log("locale -> %s", setlocale(LC_ALL, ".OCP"));
212 afsi_log("_setmbcp = %d -> %d", _setmbcp(_MB_CP_OEM), _getmbcp());
217 * Standard AFSD trace
220 void afsd_ForceTrace(BOOL flush)
229 len = GetTempPath(sizeof(buf)-10, buf);
230 StringCbCopyA(&buf[len], sizeof(buf)-len, "/afsd.log");
231 handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
232 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
233 if (handle == INVALID_HANDLE_VALUE) {
235 osi_panic("Cannot create log file", __FILE__, __LINE__);
237 osi_LogPrint(afsd_logp, handle);
239 FlushFileBuffers(handle);
244 configureBackConnectionHostNames(void)
246 /* On Windows XP SP2, Windows 2003 SP1, and all future Windows operating systems
247 * there is a restriction on the use of SMB authentication on loopback connections.
248 * There are two work arounds available:
250 * (1) We can disable the check for matching host names. This does not
252 * [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa]
253 * "DisableLoopbackCheck"=dword:00000001
255 * (2) We can add the AFS SMB/CIFS service name to an approved list. This
256 * does require a reboot:
257 * [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0]
258 * "BackConnectionHostNames"=multi-sz
260 * The algorithm will be:
261 * (1) Check to see if cm_NetbiosName exists in the BackConnectionHostNames list
262 * (2a) If not, add it to the list. (This will not take effect until the next reboot.)
263 * (2b1) and check to see if DisableLoopbackCheck is set.
264 * (2b2) If not set, set the DisableLoopbackCheck value to 0x1
265 * (2b3) and create HKLM\SOFTWARE\OpenAFS\Client UnsetDisableLoopbackCheck
266 * (2c) else If cm_NetbiosName exists in the BackConnectionHostNames list,
267 * check for the UnsetDisableLoopbackCheck value.
268 * If set, set the DisableLoopbackCheck flag to 0x0
269 * and delete the UnsetDisableLoopbackCheck value
271 * Starting in Longhorn Beta 1, an entry in the BackConnectionHostNames value will
272 * force Windows to use the loopback authentication mechanism for the specified
279 DWORD dwSize, dwAllocSize;
281 PBYTE pHostNames = NULL, pName = NULL;
282 BOOL bNameFound = FALSE;
284 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
285 "SYSTEM\\CurrentControlSet\\Control\\Lsa\\MSV1_0",
288 &hkMSV10) == ERROR_SUCCESS )
290 if ((RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0,
291 &dwType, NULL, &dwAllocSize) == ERROR_SUCCESS) &&
292 (dwType == REG_MULTI_SZ))
294 dwAllocSize += 1 /* in case the source string is not nul terminated */
295 + strlen(cm_NetbiosName) + 2;
296 pHostNames = malloc(dwAllocSize);
297 dwSize = dwAllocSize;
298 if (RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0, &dwType,
299 pHostNames, &dwSize) == ERROR_SUCCESS)
301 for (pName = pHostNames;
302 (pName - pHostNames < dwSize) && *pName ;
303 pName += strlen(pName) + 1)
305 if ( !stricmp(pName, cm_NetbiosName) ) {
314 size_t size = strlen(cm_NetbiosName) + 2;
316 pHostNames = malloc(size);
319 StringCbCopyA(pName, size, cm_NetbiosName);
321 *pName = '\0'; /* add a second nul terminator */
323 dwType = REG_MULTI_SZ;
324 dwSize = pName - pHostNames + 1;
325 RegSetValueEx( hkMSV10, "BackConnectionHostNames", 0, dwType, pHostNames, dwSize);
327 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
328 "SYSTEM\\CurrentControlSet\\Control\\Lsa",
331 &hkLsa) == ERROR_SUCCESS )
333 dwSize = sizeof(DWORD);
334 if ( RegQueryValueEx( hkLsa, "DisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) != ERROR_SUCCESS ||
337 dwSize = sizeof(DWORD);
339 RegSetValueEx( hkLsa, "DisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
341 if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
342 AFSREG_CLT_OPENAFS_SUBKEY,
345 REG_OPTION_NON_VOLATILE,
349 NULL) == ERROR_SUCCESS) {
352 dwSize = sizeof(DWORD);
354 RegSetValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
355 RegCloseKey(hkClient);
361 if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
362 AFSREG_CLT_OPENAFS_SUBKEY,
365 REG_OPTION_NON_VOLATILE,
369 NULL) == ERROR_SUCCESS) {
371 dwSize = sizeof(DWORD);
372 if ( RegQueryValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) == ERROR_SUCCESS &&
374 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
375 "SYSTEM\\CurrentControlSet\\Control\\Lsa",
378 &hkLsa) == ERROR_SUCCESS )
380 RegDeleteValue(hkLsa, "DisableLoopbackCheck");
384 RegDeleteValue(hkClient, "RemoveDisableLoopbackCheck");
385 RegCloseKey(hkClient);
388 RegCloseKey(hkMSV10);
396 static void afsd_InitServerPreferences(void)
399 DWORD dwType, dwSize;
403 DWORD dwHostSize = 256;
405 struct sockaddr_in saddr;
408 if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
409 AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\VLDB",
411 KEY_READ|KEY_QUERY_VALUE,
412 &hkPrefs) == ERROR_SUCCESS) {
414 RegQueryInfoKey( hkPrefs,
417 NULL, /* lpReserved */
418 NULL, /* lpcSubKeys */
419 NULL, /* lpcMaxSubKeyLen */
420 NULL, /* lpcMaxClassLen */
421 &dwPrefs, /* lpcValues */
422 NULL, /* lpcMaxValueNameLen */
423 NULL, /* lpcMaxValueLen */
424 NULL, /* lpcbSecurityDescriptor */
425 NULL /* lpftLastWriteTime */
428 for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
430 dwSize = sizeof(DWORD);
433 if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
434 &dwType, (LPBYTE)&dwRank, &dwSize))
436 afsi_log("RegEnumValue(hkPrefs) failed");
440 afsi_log("VLDB Server Preference: %s = %d",szHost, dwRank);
442 if (isdigit(szHost[0]))
444 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
448 if ((pEntry = gethostbyname (szHost)) == NULL)
451 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
453 saddr.sin_family = AF_INET;
454 dwRank += (rand() & 0x000f);
456 tsp = cm_FindServer(&saddr, CM_SERVER_VLDB);
457 if ( tsp ) /* an existing server - ref count increased */
459 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
461 /* set preferences for an existing vlserver */
462 cm_ChangeRankCellVLServer(tsp);
463 cm_PutServer(tsp); /* decrease refcount */
465 else /* add a new server without a cell */
467 tsp = cm_NewServer(&saddr, CM_SERVER_VLDB, NULL, CM_FLAG_NOPROBE); /* refcount = 1 */
468 tsp->ipRank = (USHORT)dwRank;
472 RegCloseKey(hkPrefs);
475 if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
476 AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\File",
478 KEY_READ|KEY_QUERY_VALUE,
479 &hkPrefs) == ERROR_SUCCESS) {
481 RegQueryInfoKey( hkPrefs,
484 NULL, /* lpReserved */
485 NULL, /* lpcSubKeys */
486 NULL, /* lpcMaxSubKeyLen */
487 NULL, /* lpcMaxClassLen */
488 &dwPrefs, /* lpcValues */
489 NULL, /* lpcMaxValueNameLen */
490 NULL, /* lpcMaxValueLen */
491 NULL, /* lpcbSecurityDescriptor */
492 NULL /* lpftLastWriteTime */
495 for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
497 dwSize = sizeof(DWORD);
500 if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
501 &dwType, (LPBYTE)&dwRank, &dwSize))
503 afsi_log("RegEnumValue(hkPrefs) failed");
507 afsi_log("File Server Preference: %s = %d",szHost, dwRank);
509 if (isdigit(szHost[0]))
511 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
515 if ((pEntry = gethostbyname (szHost)) == NULL)
518 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
520 saddr.sin_family = AF_INET;
521 dwRank += (rand() & 0x000f);
523 tsp = cm_FindServer(&saddr, CM_SERVER_FILE);
524 if ( tsp ) /* an existing server - ref count increased */
526 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
528 /* find volumes which might have RO copy
529 /* on server and change the ordering of
532 cm_ChangeRankVolume(tsp);
533 cm_PutServer(tsp); /* decrease refcount */
535 else /* add a new server without a cell */
537 tsp = cm_NewServer(&saddr, CM_SERVER_FILE, NULL, CM_FLAG_NOPROBE); /* refcount = 1 */
538 tsp->ipRank = (USHORT)dwRank;
542 RegCloseKey(hkPrefs);
547 * AFSD Initialization
550 int afsd_InitCM(char **reasonP)
553 afs_uint64 cacheBlocks;
559 DWORD rx_enable_peer_stats = 0;
560 DWORD rx_enable_process_stats = 0;
565 long virtualCache = 0;
566 char rootCellName[256];
567 struct rx_service *serverp;
568 static struct rx_securityClass *nullServerSecurityClassp;
576 /*int freelanceEnabled;*/
580 int cm_noIPAddr; /* number of client network interfaces */
581 int cm_IPAddr[CM_MAXINTERFACE_ADDR]; /* client's IP address in host order */
582 int cm_SubnetMask[CM_MAXINTERFACE_ADDR];/* client's subnet mask in host order*/
583 int cm_NetMtu[CM_MAXINTERFACE_ADDR]; /* client's MTU sizes */
584 int cm_NetFlags[CM_MAXINTERFACE_ADDR]; /* network flags */
586 WSAStartup(0x0101, &WSAjunk);
588 afsd_initUpperCaseTable();
589 init_et_to_sys_error();
591 /* setup osidebug server at RPC slot 1000 */
592 osi_LongToUID(1000, &debugID);
593 code = osi_InitDebug(&debugID);
594 afsi_log("osi_InitDebug code %d", code);
596 // osi_LockTypeSetDefault("stat"); /* comment this out for speed */
598 if (code == RPC_S_NO_PROTSEQS)
599 *reasonP = "No RPC Protocol Sequences registered. Check HKLM\\SOFTWARE\\Microsoft\\RPC\\ClientProtocols";
601 *reasonP = "unknown error";
606 gethostname(cm_HostName, sizeof(cm_HostName));
607 afsi_log("gethostname %s", cm_HostName);
608 thp = gethostbyname(cm_HostName);
609 memcpy(&cm_HostAddr, thp->h_addr_list[0], 4);
611 /* seed random number generator */
612 srand(ntohl(cm_HostAddr));
614 /* Look up configuration parameters in Registry */
615 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
616 0, KEY_QUERY_VALUE, &parmKey);
617 if (code != ERROR_SUCCESS) {
618 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
619 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
620 NULL, code, 0, (LPTSTR)&msgBuf, 0, NULL);
621 StringCbPrintfA(buf, sizeof(buf),
622 "Failure in configuration while opening Registry: %s",
624 osi_panic(buf, __FILE__, __LINE__);
627 dummyLen = sizeof(maxcpus);
628 code = RegQueryValueEx(parmKey, "MaxCPUs", NULL, NULL,
629 (BYTE *) &maxcpus, &dummyLen);
630 if (code == ERROR_SUCCESS) {
632 DWORD_PTR processAffinityMask, systemAffinityMask;
634 hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION,
635 FALSE, GetCurrentProcessId());
636 if ( hProcess != NULL &&
637 GetProcessAffinityMask(hProcess, &processAffinityMask, &systemAffinityMask) )
640 DWORD_PTR mask, newAffinityMask;
647 for ( i=0, n=0, mask=1, newAffinityMask=0; i<bits && n<maxcpus; i++ ) {
648 if ( processAffinityMask & mask ) {
649 newAffinityMask |= mask;
655 SetProcessAffinityMask(hProcess, newAffinityMask);
656 CloseHandle(hProcess);
657 afsi_log("CPU Restrictions set to %d cpu(s); %d cpu(s) available", maxcpus, n);
659 afsi_log("CPU Restrictions set to %d cpu(s); unable to access process information", maxcpus);
663 dummyLen = sizeof(TraceOption);
664 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
665 (BYTE *) &TraceOption, &dummyLen);
666 afsi_log("Trace Options = %lX", TraceOption);
668 dummyLen = sizeof(traceBufSize);
669 code = RegQueryValueEx(parmKey, "TraceBufferSize", NULL, NULL,
670 (BYTE *) &traceBufSize, &dummyLen);
671 if (code == ERROR_SUCCESS)
672 afsi_log("Trace Buffer size %d", traceBufSize);
674 traceBufSize = CM_CONFIGDEFAULT_TRACEBUFSIZE;
675 afsi_log("Default trace buffer size %d", traceBufSize);
678 /* setup and enable debug log */
679 afsd_logp = osi_LogCreate("afsd", traceBufSize);
680 afsi_log("osi_LogCreate log addr %x", PtrToUlong(afsd_logp));
681 if ((TraceOption & 0x8)
686 osi_LogEnable(afsd_logp);
690 osi_Log0(afsd_logp, "Log init");
692 dummyLen = sizeof(cacheSize);
693 code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
694 (BYTE *) &cacheSize, &dummyLen);
695 if (code == ERROR_SUCCESS)
696 afsi_log("Cache size %d", cacheSize);
698 cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
699 afsi_log("Default cache size %d", cacheSize);
702 dummyLen = sizeof(logChunkSize);
703 code = RegQueryValueEx(parmKey, "ChunkSize", NULL, NULL,
704 (BYTE *) &logChunkSize, &dummyLen);
705 if (code == ERROR_SUCCESS) {
706 if (logChunkSize < 12 || logChunkSize > 30) {
707 afsi_log("Invalid chunk size %d, using default",
709 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
712 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
714 cm_logChunkSize = logChunkSize;
715 cm_chunkSize = 1 << logChunkSize;
716 afsi_log("Chunk size %u (%d)", cm_chunkSize, cm_logChunkSize);
718 dummyLen = sizeof(blockSize);
719 code = RegQueryValueEx(parmKey, "blockSize", NULL, NULL,
720 (BYTE *) &blockSize, &dummyLen);
721 if (code == ERROR_SUCCESS) {
723 (blockSize > 1024 && (blockSize % CM_CONFIGDEFAULT_BLOCKSIZE != 0)))
725 afsi_log("Invalid block size %u specified, using default", blockSize);
726 blockSize = CM_CONFIGDEFAULT_BLOCKSIZE;
729 * if the blockSize is less than 1024 we permit the blockSize to be
730 * specified in multiples of the default blocksize
732 if (blockSize <= 1024)
733 blockSize *= CM_CONFIGDEFAULT_BLOCKSIZE;
736 blockSize = CM_CONFIGDEFAULT_BLOCKSIZE;
738 if (blockSize > cm_chunkSize) {
739 afsi_log("Block size (%d) cannot be larger than Chunk size (%d).",
740 blockSize, cm_chunkSize);
741 blockSize = cm_chunkSize;
743 if (cm_chunkSize % blockSize != 0) {
744 afsi_log("Block size (%d) must be a factor of Chunk size (%d).",
745 blockSize, cm_chunkSize);
746 blockSize = CM_CONFIGDEFAULT_BLOCKSIZE;
748 afsi_log("Block size %u", blockSize);
750 dummyLen = sizeof(numBkgD);
751 code = RegQueryValueEx(parmKey, "Daemons", NULL, NULL,
752 (BYTE *) &numBkgD, &dummyLen);
753 if (code == ERROR_SUCCESS) {
754 if (numBkgD > CM_MAX_DAEMONS)
755 numBkgD = CM_MAX_DAEMONS;
756 afsi_log("%d background daemons", numBkgD);
758 numBkgD = CM_CONFIGDEFAULT_DAEMONS;
759 afsi_log("Defaulting to %d background daemons", numBkgD);
762 dummyLen = sizeof(numSvThreads);
763 code = RegQueryValueEx(parmKey, "ServerThreads", NULL, NULL,
764 (BYTE *) &numSvThreads, &dummyLen);
765 if (code == ERROR_SUCCESS)
766 afsi_log("%d server threads", numSvThreads);
768 numSvThreads = CM_CONFIGDEFAULT_SVTHREADS;
769 afsi_log("Defaulting to %d server threads", numSvThreads);
772 dummyLen = sizeof(stats);
773 code = RegQueryValueEx(parmKey, "Stats", NULL, NULL,
774 (BYTE *) &stats, &dummyLen);
775 if (code == ERROR_SUCCESS)
776 afsi_log("Status cache size %d", stats);
778 stats = CM_CONFIGDEFAULT_STATS;
779 afsi_log("Default status cache size %d", stats);
782 dummyLen = sizeof(ltt);
783 code = RegQueryValueEx(parmKey, "LogoffTokenTransfer", NULL, NULL,
784 (BYTE *) <t, &dummyLen);
785 if (code != ERROR_SUCCESS)
787 smb_LogoffTokenTransfer = ltt;
788 afsi_log("Logoff token transfer %s", (ltt ? "on" : "off"));
791 dummyLen = sizeof(ltto);
792 code = RegQueryValueEx(parmKey, "LogoffTokenTransferTimeout",
793 NULL, NULL, (BYTE *) <to, &dummyLen);
794 if (code != ERROR_SUCCESS)
799 smb_LogoffTransferTimeout = ltto;
800 afsi_log("Logoff token transfer timeout %d seconds", ltto);
802 dummyLen = sizeof(cm_rootVolumeName);
803 code = RegQueryValueEx(parmKey, "RootVolume", NULL, NULL,
804 cm_rootVolumeName, &dummyLen);
805 if (code == ERROR_SUCCESS)
806 afsi_log("Root volume %s", cm_rootVolumeName);
808 StringCbCopyA(cm_rootVolumeName, sizeof(cm_rootVolumeName), "root.afs");
809 afsi_log("Default root volume name root.afs");
812 cm_mountRootLen = sizeof(cm_mountRoot);
813 code = RegQueryValueEx(parmKey, "MountRoot", NULL, NULL,
814 cm_mountRoot, &cm_mountRootLen);
815 if (code == ERROR_SUCCESS) {
816 afsi_log("Mount root %s", cm_mountRoot);
817 cm_mountRootLen = (DWORD)strlen(cm_mountRoot);
819 StringCbCopyA(cm_mountRoot, sizeof(cm_mountRoot), "/afs");
824 dummyLen = sizeof(buf);
825 code = RegQueryValueEx(parmKey, "CachePath", NULL, ®Type,
827 if (code == ERROR_SUCCESS && buf[0]) {
828 if (regType == REG_EXPAND_SZ) {
829 dummyLen = ExpandEnvironmentStrings(buf, cm_CachePath, sizeof(cm_CachePath));
830 if (dummyLen > sizeof(cm_CachePath)) {
831 afsi_log("Cache path [%s] longer than %d after expanding env strings", buf, sizeof(cm_CachePath));
832 osi_panic("CachePath too long", __FILE__, __LINE__);
835 StringCbCopyA(cm_CachePath, sizeof(cm_CachePath), buf);
837 afsi_log("Cache path %s", cm_CachePath);
839 dummyLen = ExpandEnvironmentStrings("%TEMP%\\AFSCache", cm_CachePath, sizeof(cm_CachePath));
840 if (dummyLen > sizeof(cm_CachePath)) {
841 afsi_log("Cache path [%%TEMP%%\\AFSCache] longer than %d after expanding env strings",
842 sizeof(cm_CachePath));
843 osi_panic("CachePath too long", __FILE__, __LINE__);
845 afsi_log("Default cache path %s", cm_CachePath);
848 dummyLen = sizeof(virtualCache);
849 code = RegQueryValueEx(parmKey, "NonPersistentCaching", NULL, NULL,
850 (LPBYTE)&virtualCache, &dummyLen);
851 afsi_log("Cache type is %s", (virtualCache?"VIRTUAL":"FILE"));
854 dummyLen = sizeof(cm_ValidateCache);
855 code = RegQueryValueEx(parmKey, "ValidateCache", NULL, NULL,
856 (LPBYTE)&cm_ValidateCache, &dummyLen);
857 if ( cm_ValidateCache < 0 || cm_ValidateCache > 2 )
858 cm_ValidateCache = 1;
859 switch (cm_ValidateCache) {
861 afsi_log("Cache Validation disabled");
864 afsi_log("Cache Validation on Startup");
867 afsi_log("Cache Validation on Startup and Shutdown");
872 dummyLen = sizeof(traceOnPanic);
873 code = RegQueryValueEx(parmKey, "TrapOnPanic", NULL, NULL,
874 (BYTE *) &traceOnPanic, &dummyLen);
875 if (code != ERROR_SUCCESS)
876 traceOnPanic = 1; /* log */
877 afsi_log("Set to %s on panic", traceOnPanic ? "trap" : "not trap");
879 dummyLen = sizeof(reportSessionStartups);
880 code = RegQueryValueEx(parmKey, "ReportSessionStartups", NULL, NULL,
881 (BYTE *) &reportSessionStartups, &dummyLen);
882 if (code == ERROR_SUCCESS)
883 afsi_log("Session startups %s be recorded in the Event Log",
884 reportSessionStartups ? "will" : "will not");
886 reportSessionStartups = 0;
890 for ( i=0; i < MAXNUMSYSNAMES; i++ ) {
891 cm_sysNameList[i] = osi_Alloc(MAXSYSNAME);
892 cm_sysNameList[i][0] = '\0';
894 cm_sysName = cm_sysNameList[0];
896 dummyLen = sizeof(buf);
897 code = RegQueryValueEx(parmKey, "SysName", NULL, NULL, buf, &dummyLen);
898 if (code != ERROR_SUCCESS || !buf[0]) {
900 StringCbCopyA(buf, sizeof(buf), "ia64_win64");
901 #elif defined(_AMD64_)
902 StringCbCopyA(buf, sizeof(buf), "amd64_win64 x86_win32 i386_w2k");
903 #else /* assume x86 32-bit */
904 StringCbCopyA(buf, sizeof(buf), "x86_win32 i386_w2k i386_nt40");
907 afsi_log("Sys name %s", buf);
909 /* breakup buf into individual search string entries */
910 for (p = q = buf; p < buf + dummyLen; p++)
912 if (*p == '\0' || isspace(*p)) {
913 memcpy(cm_sysNameList[cm_sysNameCount],q,p-q);
914 cm_sysNameList[cm_sysNameCount][p-q] = '\0';
921 } while (*p == '\0' || isspace(*p));
927 StringCbCopyA(cm_sysName, MAXSYSNAME, cm_sysNameList[0]);
929 dummyLen = sizeof(cryptall);
930 code = RegQueryValueEx(parmKey, "SecurityLevel", NULL, NULL,
931 (BYTE *) &cryptall, &dummyLen);
932 if (code == ERROR_SUCCESS) {
933 afsi_log("SecurityLevel is %s", cryptall?"crypt":"clear");
936 afsi_log("Default SecurityLevel is clear");
940 LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_ON);
942 LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_OFF);
945 dummyLen = sizeof(cm_dnsEnabled);
946 code = RegQueryValueEx(parmKey, "UseDNS", NULL, NULL,
947 (BYTE *) &cm_dnsEnabled, &dummyLen);
948 if (code == ERROR_SUCCESS) {
949 afsi_log("DNS %s be used to find AFS cell servers",
950 cm_dnsEnabled ? "will" : "will not");
953 cm_dnsEnabled = 1; /* default on */
954 afsi_log("Default to use DNS to find AFS cell servers");
956 #else /* AFS_AFSDB_ENV */
957 afsi_log("AFS not built with DNS support to find AFS cell servers");
958 #endif /* AFS_AFSDB_ENV */
960 #ifdef AFS_FREELANCE_CLIENT
961 dummyLen = sizeof(cm_freelanceEnabled);
962 code = RegQueryValueEx(parmKey, "FreelanceClient", NULL, NULL,
963 (BYTE *) &cm_freelanceEnabled, &dummyLen);
964 if (code == ERROR_SUCCESS) {
965 afsi_log("Freelance client feature %s activated",
966 cm_freelanceEnabled ? "is" : "is not");
969 cm_freelanceEnabled = 1; /* default on */
971 #endif /* AFS_FREELANCE_CLIENT */
973 dummyLen = sizeof(smb_hideDotFiles);
974 code = RegQueryValueEx(parmKey, "HideDotFiles", NULL, NULL,
975 (BYTE *) &smb_hideDotFiles, &dummyLen);
976 if (code != ERROR_SUCCESS) {
977 smb_hideDotFiles = 1; /* default on */
979 afsi_log("Dot files/dirs will %sbe marked hidden",
980 smb_hideDotFiles ? "" : "not ");
982 dummyLen = sizeof(smb_maxMpxRequests);
983 code = RegQueryValueEx(parmKey, "MaxMpxRequests", NULL, NULL,
984 (BYTE *) &smb_maxMpxRequests, &dummyLen);
985 if (code != ERROR_SUCCESS) {
986 smb_maxMpxRequests = 50;
988 afsi_log("Maximum number of multiplexed sessions is %d", smb_maxMpxRequests);
990 dummyLen = sizeof(smb_maxVCPerServer);
991 code = RegQueryValueEx(parmKey, "MaxVCPerServer", NULL, NULL,
992 (BYTE *) &smb_maxVCPerServer, &dummyLen);
993 if (code != ERROR_SUCCESS) {
994 smb_maxVCPerServer = 100;
996 afsi_log("Maximum number of VCs per server is %d", smb_maxVCPerServer);
998 dummyLen = sizeof(smb_authType);
999 code = RegQueryValueEx(parmKey, "SMBAuthType", NULL, NULL,
1000 (BYTE *) &smb_authType, &dummyLen);
1002 if (code != ERROR_SUCCESS ||
1003 (smb_authType != SMB_AUTH_EXTENDED && smb_authType != SMB_AUTH_NTLM && smb_authType != SMB_AUTH_NONE)) {
1004 smb_authType = SMB_AUTH_EXTENDED; /* default is to use extended authentication */
1006 afsi_log("SMB authentication type is %s", ((smb_authType == SMB_AUTH_NONE)?"NONE":((smb_authType == SMB_AUTH_EXTENDED)?"EXTENDED":"NTLM")));
1008 dummyLen = sizeof(rx_nojumbo);
1009 code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
1010 (BYTE *) &rx_nojumbo, &dummyLen);
1011 if (code != ERROR_SUCCESS) {
1015 afsi_log("RX Jumbograms are disabled");
1017 dummyLen = sizeof(rx_mtu);
1018 code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
1019 (BYTE *) &rx_mtu, &dummyLen);
1020 if (code != ERROR_SUCCESS || !rx_mtu) {
1024 afsi_log("RX maximum MTU is %d", rx_mtu);
1026 dummyLen = sizeof(rx_enable_peer_stats);
1027 code = RegQueryValueEx(parmKey, "RxEnablePeerStats", NULL, NULL,
1028 (BYTE *) &rx_enable_peer_stats, &dummyLen);
1029 if (code != ERROR_SUCCESS) {
1030 rx_enable_peer_stats = 0;
1032 if (rx_enable_peer_stats)
1033 afsi_log("RX Peer Statistics gathering is enabled");
1035 dummyLen = sizeof(rx_enable_process_stats);
1036 code = RegQueryValueEx(parmKey, "RxEnableProcessStats", NULL, NULL,
1037 (BYTE *) &rx_enable_process_stats, &dummyLen);
1038 if (code != ERROR_SUCCESS) {
1039 rx_enable_process_stats = 0;
1041 if (rx_enable_process_stats)
1042 afsi_log("RX Process Statistics gathering is enabled");
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");
1071 dummyLen = sizeof(DWORD);
1072 code = RegQueryValueEx(parmKey, "DeleteReadOnly", NULL, NULL,
1073 (BYTE *) &dwValue, &dummyLen);
1074 if (code == ERROR_SUCCESS) {
1075 cm_deleteReadOnly = (unsigned short) dwValue;
1077 afsi_log("CM DeleteReadOnly is %u", cm_deleteReadOnly);
1080 dummyLen = sizeof(DWORD);
1081 code = RegQueryValueEx(parmKey, "BPlusTrees", NULL, NULL,
1082 (BYTE *) &dwValue, &dummyLen);
1083 if (code == ERROR_SUCCESS) {
1084 cm_BPlusTrees = (unsigned short) dwValue;
1086 afsi_log("CM BPlusTrees is %u", cm_BPlusTrees);
1088 if (cm_BPlusTrees && !cm_InitBPlusDir()) {
1090 afsi_log("CM BPlusTree initialization failure; disabled for this session");
1093 afsi_log("CM BPlusTrees is not supported");
1096 if ((RegQueryValueEx( parmKey, "PrefetchExecutableExtensions", 0,
1097 ®Type, NULL, &dummyLen) == ERROR_SUCCESS) &&
1098 (regType == REG_MULTI_SZ))
1101 dummyLen += 3; /* in case the source string is not nul terminated */
1102 pSz = malloc(dummyLen);
1103 if ((RegQueryValueEx( parmKey, "PrefetchExecutableExtensions", 0, ®Type,
1104 pSz, &dummyLen) == ERROR_SUCCESS) &&
1105 (regType == REG_MULTI_SZ))
1110 for (cnt = 0, p = pSz; (p - pSz < dummyLen) && *p; cnt++, p += strlen(p) + 1);
1112 smb_ExecutableExtensions = malloc(sizeof(char *) * (cnt+1));
1114 for (cnt = 0, p = pSz; (p - pSz < dummyLen) && *p; cnt++, p += strlen(p) + 1)
1116 smb_ExecutableExtensions[cnt] = p;
1117 afsi_log("PrefetchExecutableExtension: \"%s\"", p);
1119 smb_ExecutableExtensions[cnt] = NULL;
1122 if (!smb_ExecutableExtensions)
1125 if (!smb_ExecutableExtensions)
1126 afsi_log("No PrefetchExecutableExtensions");
1128 dummyLen = sizeof(DWORD);
1129 code = RegQueryValueEx(parmKey, "OfflineReadOnlyIsValid", NULL, NULL,
1130 (BYTE *) &dwValue, &dummyLen);
1131 if (code == ERROR_SUCCESS) {
1132 cm_OfflineROIsValid = (unsigned short) dwValue;
1134 afsi_log("CM OfflineReadOnlyIsValid is %u", cm_deleteReadOnly);
1136 dummyLen = sizeof(DWORD);
1137 code = RegQueryValueEx(parmKey, "GiveUpAllCallBacks", NULL, NULL,
1138 (BYTE *) &dwValue, &dummyLen);
1139 if (code == ERROR_SUCCESS) {
1140 cm_giveUpAllCBs = (unsigned short) dwValue;
1142 afsi_log("CM GiveUpAllCallBacks is %u", cm_giveUpAllCBs);
1144 dummyLen = sizeof(DWORD);
1145 code = RegQueryValueEx(parmKey, "FollowBackupPath", NULL, NULL,
1146 (BYTE *) &dwValue, &dummyLen);
1147 if (code == ERROR_SUCCESS) {
1148 cm_followBackupPath = (unsigned short) dwValue;
1150 afsi_log("CM FollowBackupPath is %u", cm_followBackupPath);
1152 RegCloseKey (parmKey);
1154 cacheBlocks = ((afs_uint64)cacheSize * 1024) / blockSize;
1156 /* get network related info */
1157 cm_noIPAddr = CM_MAXINTERFACE_ADDR;
1158 code = syscfg_GetIFInfo(&cm_noIPAddr,
1159 cm_IPAddr, cm_SubnetMask,
1160 cm_NetMtu, cm_NetFlags);
1162 if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
1163 afsi_log("syscfg_GetIFInfo error code %d", code);
1165 afsi_log("First Network address %x SubnetMask %x",
1166 cm_IPAddr[0], cm_SubnetMask[0]);
1169 * Save client configuration for GetCacheConfig requests
1171 cm_initParams.nChunkFiles = 0;
1172 cm_initParams.nStatCaches = stats;
1173 cm_initParams.nDataCaches = (afs_uint32)(cacheBlocks > 0xFFFFFFFF ? 0xFFFFFFFF : cacheBlocks);
1174 cm_initParams.nVolumeCaches = stats/2;
1175 cm_initParams.firstChunkSize = cm_chunkSize;
1176 cm_initParams.otherChunkSize = cm_chunkSize;
1177 cm_initParams.cacheSize = cacheSize;
1178 cm_initParams.setTime = 0;
1179 cm_initParams.memCache = 1;
1181 /* Ensure the AFS Netbios Name is registered to allow loopback access */
1182 configureBackConnectionHostNames();
1184 /* init user daemon, and other packages */
1197 code = cm_InitMappedMemory(virtualCache, cm_CachePath, stats, cm_chunkSize, cacheBlocks, blockSize);
1198 afsi_log("cm_InitMappedMemory code %x", code);
1200 *reasonP = "error initializing cache file";
1204 #ifdef AFS_AFSDB_ENV
1205 #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
1206 if (cm_InitDNS(cm_dnsEnabled) == -1)
1207 cm_dnsEnabled = 0; /* init failed, so deactivate */
1208 afsi_log("cm_InitDNS %d", cm_dnsEnabled);
1212 /* Set RX parameters before initializing RX */
1215 afsi_log("rx_SetNoJumbo successful");
1218 if ( rx_mtu != -1 ) {
1219 rx_SetMaxMTU(rx_mtu);
1220 afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
1223 /* initialize RX, and tell it to listen to the callbackport,
1224 * which is used for callback RPC messages.
1226 code = rx_Init(htons(cm_callbackport));
1228 afsi_log("rx_Init code %x - retrying with a random port number", code);
1231 afsi_log("rx_Init code %x", code);
1233 *reasonP = "afsd: failed to init rx client";
1237 /* create an unauthenticated service #1 for callbacks */
1238 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1239 serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
1240 RXAFSCB_ExecuteRequest);
1241 afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1242 if (serverp == NULL) {
1243 *reasonP = "unknown error";
1247 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1248 serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
1249 &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
1250 afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1251 if (serverp == NULL) {
1252 *reasonP = "unknown error";
1256 /* start server threads, *not* donating this one to the pool */
1258 afsi_log("rx_StartServer");
1260 if (rx_enable_peer_stats)
1261 rx_enablePeerRPCStats();
1263 if (rx_enable_process_stats)
1264 rx_enableProcessRPCStats();
1266 code = cm_GetRootCellName(rootCellName);
1267 afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s",
1268 code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
1269 if (code != 0 && !cm_freelanceEnabled)
1271 *reasonP = "can't find root cell name in CellServDB";
1274 else if (cm_freelanceEnabled)
1275 cm_data.rootCellp = NULL;
1277 if (code == 0 && !cm_freelanceEnabled)
1279 cm_data.rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
1280 afsi_log("cm_GetCell addr %x", PtrToUlong(cm_data.rootCellp));
1281 if (cm_data.rootCellp == NULL)
1283 *reasonP = "can't find root cell in afsdcell.ini";
1288 #ifdef AFS_FREELANCE_CLIENT
1289 if (cm_freelanceEnabled)
1293 /* Initialize the RPC server for session keys */
1296 afsd_InitServerPreferences();
1300 int afsd_ShutdownCM(void)
1302 cm_ReleaseSCache(cm_data.rootSCachep);
1307 int afsd_InitDaemons(char **reasonP)
1314 /* this should really be in an init daemon from here on down */
1316 if (!cm_freelanceEnabled) {
1319 osi_Log0(afsd_logp, "Loading Root Volume from cell");
1321 code = cm_GetVolumeByName(cm_data.rootCellp, cm_rootVolumeName, cm_rootUserp,
1322 &req, CM_GETVOL_FLAG_CREATE, &cm_data.rootVolumep);
1323 afsi_log("cm_GetVolumeByName code %x root vol %x", code,
1324 (code ? (cm_volume_t *)-1 : cm_data.rootVolumep));
1325 } while (code && --attempts);
1327 *reasonP = "can't find root volume in root cell";
1332 /* compute the root fid */
1333 if (!cm_freelanceEnabled) {
1334 cm_data.rootFid.cell = cm_data.rootCellp->cellID;
1335 cm_data.rootFid.volume = cm_GetROVolumeID(cm_data.rootVolumep);
1336 cm_data.rootFid.vnode = 1;
1337 cm_data.rootFid.unique = 1;
1340 cm_FakeRootFid(&cm_data.rootFid);
1342 code = cm_GetSCache(&cm_data.rootFid, &cm_data.rootSCachep, cm_rootUserp, &req);
1343 afsi_log("cm_GetSCache code %x scache %x", code,
1344 (code ? (cm_scache_t *)-1 : cm_data.rootSCachep));
1346 *reasonP = "unknown error";
1350 cm_InitDaemon(numBkgD);
1351 afsi_log("cm_InitDaemon complete");
1356 int afsd_InitSMB(char **reasonP, void *aMBfunc)
1363 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1364 0, KEY_QUERY_VALUE, &parmKey);
1365 if (code == ERROR_SUCCESS) {
1366 dummyLen = sizeof(DWORD);
1367 code = RegQueryValueEx(parmKey, "StoreAnsiFilenames", NULL, NULL,
1368 (BYTE *) &dwValue, &dummyLen);
1369 if (code == ERROR_SUCCESS)
1370 smb_StoreAnsiFilenames = dwValue ? 1 : 0;
1371 RegCloseKey (parmKey);
1374 /* Do this last so that we don't handle requests before init is done.
1375 * Here we initialize the SMB listener.
1377 smb_Init(afsd_logp, smb_UseV3, numSvThreads, aMBfunc);
1378 afsi_log("smb_Init complete");
1391 #pragma pack( push, before_imagehlp, 8 )
1392 #include <imagehlp.h>
1393 #pragma pack( pop, before_imagehlp )
1395 #define MAXNAMELEN 1024
1397 void afsd_printStack(HANDLE hThread, CONTEXT *c)
1399 HANDLE hProcess = GetCurrentProcess();
1401 #if defined(_AMD64_)
1403 #elif defined(_X86_)
1407 char functionName[MAXNAMELEN];
1409 IMAGEHLP_MODULE Module;
1413 IMAGEHLP_SYMBOL *pSym;
1415 afsi_log_useTimestamp = 0;
1417 pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
1419 memset( &s, '\0', sizeof s );
1420 if (!SymInitialize(hProcess, NULL, 1) )
1422 afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
1424 SymCleanup( hProcess );
1430 symOptions = SymGetOptions();
1431 symOptions |= SYMOPT_LOAD_LINES;
1432 symOptions &= ~SYMOPT_UNDNAME;
1433 SymSetOptions( symOptions );
1436 * init STACKFRAME for first call
1437 * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
1438 * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
1439 * and good riddance.
1441 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
1442 #error The STACKFRAME initialization in afsd_printStack() for this platform
1443 #error must be properly configured
1444 #elif defined(_AMD64_)
1445 s.AddrPC.Offset = c->Rip;
1446 s.AddrPC.Mode = AddrModeFlat;
1447 s.AddrFrame.Offset = c->Rbp;
1448 s.AddrFrame.Mode = AddrModeFlat;
1450 s.AddrPC.Offset = c->Eip;
1451 s.AddrPC.Mode = AddrModeFlat;
1452 s.AddrFrame.Offset = c->Ebp;
1453 s.AddrFrame.Mode = AddrModeFlat;
1456 memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
1457 pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
1458 pSym->MaxNameLength = MAXNAMELEN;
1460 memset( &Line, '\0', sizeof Line );
1461 Line.SizeOfStruct = sizeof Line;
1463 memset( &Module, '\0', sizeof Module );
1464 Module.SizeOfStruct = sizeof Module;
1468 afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
1470 for ( frameNum = 0; ; ++ frameNum )
1473 * get next stack frame (StackWalk(), SymFunctionTableAccess(),
1474 * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
1475 * ERROR_NOACCESS (998), you can assume that either you are done, or
1476 * that the stack is so hosed that the next deeper frame could not be
1479 if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c,
1480 NULL, SymFunctionTableAccess, SymGetModuleBase,
1484 /* display its contents */
1485 afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
1486 frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
1487 s.AddrPC.Offset, s.AddrReturn.Offset,
1488 s.AddrFrame.Offset, s.AddrStack.Offset );
1490 if ( s.AddrPC.Offset == 0 )
1492 afsi_log("(-nosymbols- PC == 0)" );
1496 /* show procedure info from a valid PC */
1497 if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
1499 if ( GetLastError() != ERROR_INVALID_ADDRESS )
1501 afsi_log("SymGetSymFromAddr(): errno = %lu",
1507 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN,
1509 afsi_log("%s", functionName );
1513 afsi_log(" %+ld bytes", (long) offset);
1517 if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
1519 if (GetLastError() != ERROR_INVALID_ADDRESS)
1521 afsi_log("Error: SymGetLineFromAddr(): errno = %lu",
1527 afsi_log(" Line: %s(%lu) %+ld bytes", Line.FileName,
1528 Line.LineNumber, offset);
1532 /* no return address means no deeper stackframe */
1533 if (s.AddrReturn.Offset == 0)
1540 if (GetLastError() != 0)
1542 afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
1545 SymCleanup(hProcess);
1550 static DWORD *afsd_crtDbgBreakCurrent = NULL;
1551 static DWORD afsd_crtDbgBreaks[256];
1554 static EFaultRepRetVal (WINAPI *pReportFault)(LPEXCEPTION_POINTERS pep, DWORD dwMode) = NULL;
1555 static BOOL (WINAPI *pMiniDumpWriteDump)(HANDLE hProcess,DWORD ProcessId,HANDLE hFile,
1556 MINIDUMP_TYPE DumpType,
1557 PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
1558 PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
1559 PMINIDUMP_CALLBACK_INFORMATION CallbackParam) = NULL;
1568 code = GetEnvironmentVariable("TEMP", wd, sizeof(wd));
1569 if ( code == 0 || code > sizeof(wd) )
1571 if (!GetWindowsDirectory(wd, sizeof(wd)))
1574 StringCbCatA(wd, sizeof(wd), "\\afsd.dmp");
1575 return CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1576 CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
1580 GenerateMiniDump(PEXCEPTION_POINTERS ep)
1582 if (IsDebuggerPresent())
1587 // Generate exception to get proper context in dump
1590 RaiseException(DBG_CONTINUE, 0, 0, NULL);
1592 __except(GenerateMiniDump(GetExceptionInformation()), EXCEPTION_CONTINUE_EXECUTION)
1598 MINIDUMP_EXCEPTION_INFORMATION eInfo;
1599 HANDLE hFile = NULL;
1600 HMODULE hDbgHelp = NULL;
1602 hDbgHelp = LoadLibrary("Dbghelp.dll");
1603 if ( hDbgHelp == NULL )
1606 (FARPROC) pMiniDumpWriteDump = GetProcAddress(hDbgHelp, "MiniDumpWriteDump");
1607 if ( pMiniDumpWriteDump == NULL ) {
1608 FreeLibrary(hDbgHelp);
1612 hFile = OpenDumpFile();
1619 DWORD dwMiniDumpType = MiniDumpWithDataSegs;
1621 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1622 0, KEY_QUERY_VALUE, &parmKey);
1623 if (code == ERROR_SUCCESS) {
1624 dummyLen = sizeof(DWORD);
1625 code = RegQueryValueEx(parmKey, "MiniDumpType", NULL, NULL,
1626 (BYTE *) &dwValue, &dummyLen);
1627 if (code == ERROR_SUCCESS)
1628 dwMiniDumpType = dwValue;
1629 RegCloseKey (parmKey);
1632 eInfo.ThreadId = GetCurrentThreadId();
1633 eInfo.ExceptionPointers = ep;
1634 eInfo.ClientPointers = FALSE;
1636 pMiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(),
1637 hFile, dwMiniDumpType, ep ? &eInfo : NULL,
1642 FreeLibrary(hDbgHelp);
1646 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
1650 BOOL allocRequestBrk = FALSE;
1652 HMODULE hLib = NULL;
1654 afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n",
1655 ep->ExceptionRecord->ExceptionCode,
1656 ep->ExceptionRecord->ExceptionAddress);
1659 if (afsd_crtDbgBreakCurrent &&
1660 *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
1662 allocRequestBrk = TRUE;
1663 afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
1667 /* save context if we want to print the stack information */
1668 context = *ep->ContextRecord;
1670 afsd_printStack(GetCurrentThread(), &context);
1672 GenerateMiniDump(ep);
1674 hLib = LoadLibrary("Faultrep.dll");
1676 (FARPROC) pReportFault = GetProcAddress(hLib, "ReportFault");
1678 pReportFault(ep, 0);
1682 if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
1684 afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
1687 if (allocRequestBrk)
1689 afsd_crtDbgBreakCurrent++;
1690 _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
1694 ep->ContextRecord->Eip++;
1696 #if defined(_AMD64_)
1697 ep->ContextRecord->Rip++;
1699 return EXCEPTION_CONTINUE_EXECUTION;
1703 return EXCEPTION_CONTINUE_SEARCH;
1707 void afsd_SetUnhandledExceptionFilter()
1709 SetUnhandledExceptionFilter(afsd_ExceptionFilter);
1713 void afsd_DbgBreakAllocInit()
1715 memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
1716 afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
1719 void afsd_DbgBreakAdd(DWORD requestNumber)
1722 for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
1724 if (afsd_crtDbgBreaks[i] == -1)
1729 afsd_crtDbgBreaks[i] = requestNumber;
1731 _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);