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;
42 extern int cm_deleteReadOnly;
46 cm_config_data_t cm_data;
48 char cm_rootVolumeName[VL_MAXNAMELEN];
49 DWORD cm_rootVolumeNameLen;
50 char cm_mountRoot[1024];
51 DWORD cm_mountRootLen;
54 #ifdef AFS_FREELANCE_CLIENT
56 #endif /* freelance */
69 char cm_HostName[200];
71 unsigned short cm_callbackport = CM_DEFAULT_CALLBACKPORT;
73 char cm_NetbiosName[MAX_NB_NAME_LENGTH] = "";
75 char cm_CachePath[MAX_PATH];
76 DWORD cm_CachePathLen;
77 DWORD cm_ValidateCache = 1;
79 BOOL isGateway = FALSE;
81 BOOL reportSessionStartups = FALSE;
83 cm_initparams_v1 cm_initParams;
86 unsigned int cm_sysNameCount = 0;
87 char *cm_sysNameList[MAXNUMSYSNAMES];
89 DWORD TraceOption = 0;
92 * AFSD Initialization Log
94 * This is distinct from the regular debug logging facility.
95 * Log items go directly to a file, not to an array in memory, so that even
96 * if AFSD crashes, the log can be inspected.
102 int cm_dnsEnabled = 1;
106 static int afsi_log_useTimestamp = 1;
109 afsi_log(char *pattern, ...)
111 char s[256], t[100], d[100], u[512];
114 va_start(ap, pattern);
116 StringCbVPrintfA(s, sizeof(s), pattern, ap);
117 if ( afsi_log_useTimestamp ) {
118 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
119 GetDateFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, d, sizeof(d));
120 StringCbPrintfA(u, sizeof(u), "%s %s: %s\r\n", d, t, s);
121 if (afsi_file != INVALID_HANDLE_VALUE)
122 WriteFile(afsi_file, u, (DWORD)strlen(u), &zilch, NULL);
127 if (afsi_file != INVALID_HANDLE_VALUE)
128 WriteFile(afsi_file, s, (DWORD)strlen(s), &zilch, NULL);
132 extern initUpperCaseTable();
133 void afsd_initUpperCaseTable()
135 initUpperCaseTable();
142 char t[100], u[100], *p, *path;
148 DWORD maxLogSize = 100 * 1024;
150 afsi_file = INVALID_HANDLE_VALUE;
151 code = GetEnvironmentVariable("TEMP", wd, sizeof(wd));
152 if ( code == 0 || code > sizeof(wd) )
154 code = GetWindowsDirectory(wd, sizeof(wd));
158 StringCbCatA(wd, sizeof(wd), "\\afsd_init.log");
159 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
160 afsi_file = CreateFile(wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
161 OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
163 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
164 0, KEY_QUERY_VALUE, &parmKey);
165 if (code == ERROR_SUCCESS) {
166 dummyLen = sizeof(maxLogSize);
167 code = RegQueryValueEx(parmKey, "MaxLogSize", NULL, NULL,
168 (BYTE *) &maxLogSize, &dummyLen);
169 RegCloseKey (parmKey);
173 dwLow = GetFileSize( afsi_file, &dwHigh );
174 if ( dwHigh > 0 || dwLow >= maxLogSize ) {
175 CloseHandle(afsi_file);
176 afsi_file = CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
177 CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
181 SetFilePointer(afsi_file, 0, NULL, FILE_END);
182 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, u, sizeof(u));
183 StringCbCatA(t, sizeof(t), ": Create log file\r\n");
184 StringCbCatA(u, sizeof(u), ": Created log file\r\n");
185 WriteFile(afsi_file, t, (DWORD)strlen(t), &zilch, NULL);
186 WriteFile(afsi_file, u, (DWORD)strlen(u), &zilch, NULL);
188 code = GetEnvironmentVariable("PATH", NULL, 0);
190 code = GetEnvironmentVariable("PATH", path, code);
191 WriteFile(afsi_file, p, (DWORD)strlen(p), &zilch, NULL);
192 WriteFile(afsi_file, path, (DWORD)strlen(path), &zilch, NULL);
193 WriteFile(afsi_file, "\r\n", (DWORD)1, &zilch, NULL);
196 /* Initialize C RTL Code Page conversion functions */
197 /* All of the path info obtained from the SMB client is in the OEM code page */
198 afsi_log("OEM Code Page = %d", GetOEMCP());
199 afsi_log("locale = %s", setlocale(LC_ALL,NULL));
201 /* Two things to look into. First, should mbstowcs() be performing
202 * character set translations from OEM to Unicode in smb3.c;
203 * Second, do we need to set this translation in each function
204 * due to multi-threading.
206 afsi_log("locale -> %s", setlocale(LC_ALL, ".OCP"));
207 afsi_log("_setmbcp = %d -> %d", _setmbcp(_MB_CP_OEM), _getmbcp());
212 * Standard AFSD trace
215 void afsd_ForceTrace(BOOL flush)
224 len = GetTempPath(sizeof(buf)-10, buf);
225 StringCbCopyA(&buf[len], sizeof(buf)-len, "/afsd.log");
226 handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
227 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
228 if (handle == INVALID_HANDLE_VALUE) {
230 osi_panic("Cannot create log file", __FILE__, __LINE__);
232 osi_LogPrint(afsd_logp, handle);
234 FlushFileBuffers(handle);
239 configureBackConnectionHostNames(void)
241 /* On Windows XP SP2, Windows 2003 SP1, and all future Windows operating systems
242 * there is a restriction on the use of SMB authentication on loopback connections.
243 * There are two work arounds available:
245 * (1) We can disable the check for matching host names. This does not
247 * [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa]
248 * "DisableLoopbackCheck"=dword:00000001
250 * (2) We can add the AFS SMB/CIFS service name to an approved list. This
251 * does require a reboot:
252 * [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0]
253 * "BackConnectionHostNames"=multi-sz
255 * The algorithm will be:
256 * (1) Check to see if cm_NetbiosName exists in the BackConnectionHostNames list
257 * (2a) If not, add it to the list. (This will not take effect until the next reboot.)
258 * (2b1) and check to see if DisableLoopbackCheck is set.
259 * (2b2) If not set, set the DisableLoopbackCheck value to 0x1
260 * (2b3) and create HKLM\SOFTWARE\OpenAFS\Client UnsetDisableLoopbackCheck
261 * (2c) else If cm_NetbiosName exists in the BackConnectionHostNames list,
262 * check for the UnsetDisableLoopbackCheck value.
263 * If set, set the DisableLoopbackCheck flag to 0x0
264 * and delete the UnsetDisableLoopbackCheck value
266 * Starting in Longhorn Beta 1, an entry in the BackConnectionHostNames value will
267 * force Windows to use the loopback authentication mechanism for the specified
274 DWORD dwSize, dwAllocSize;
276 PBYTE pHostNames = NULL, pName = NULL;
277 BOOL bNameFound = FALSE;
279 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
280 "SYSTEM\\CurrentControlSet\\Control\\Lsa\\MSV1_0",
283 &hkMSV10) == ERROR_SUCCESS )
285 if (RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0,
286 &dwType, NULL, &dwAllocSize) == ERROR_SUCCESS) {
287 dwAllocSize += 1 /* in case the source string is not nul terminated */
288 + strlen(cm_NetbiosName) + 2;
289 pHostNames = malloc(dwAllocSize);
290 dwSize = dwAllocSize;
291 if (RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0, &dwType,
292 pHostNames, &dwSize) == ERROR_SUCCESS) {
293 for (pName = pHostNames;
294 (pName - pHostNames < dwSize) && *pName ;
295 pName += strlen(pName) + 1)
297 if ( !stricmp(pName, cm_NetbiosName) ) {
306 size_t size = strlen(cm_NetbiosName) + 2;
308 pHostNames = malloc(size);
311 StringCbCopyA(pName, size, cm_NetbiosName);
313 *pName = '\0'; /* add a second nul terminator */
315 dwType = REG_MULTI_SZ;
316 dwSize = pName - pHostNames + 1;
317 RegSetValueEx( hkMSV10, "BackConnectionHostNames", 0, dwType, pHostNames, dwSize);
319 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
320 "SYSTEM\\CurrentControlSet\\Control\\Lsa",
323 &hkLsa) == ERROR_SUCCESS )
325 dwSize = sizeof(DWORD);
326 if ( RegQueryValueEx( hkLsa, "DisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) != ERROR_SUCCESS ||
329 dwSize = sizeof(DWORD);
331 RegSetValueEx( hkLsa, "DisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
333 if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
334 AFSREG_CLT_OPENAFS_SUBKEY,
337 REG_OPTION_NON_VOLATILE,
341 NULL) == ERROR_SUCCESS) {
344 dwSize = sizeof(DWORD);
346 RegSetValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
347 RegCloseKey(hkClient);
353 if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
354 AFSREG_CLT_OPENAFS_SUBKEY,
357 REG_OPTION_NON_VOLATILE,
361 NULL) == ERROR_SUCCESS) {
363 dwSize = sizeof(DWORD);
364 if ( RegQueryValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) == ERROR_SUCCESS &&
366 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
367 "SYSTEM\\CurrentControlSet\\Control\\Lsa",
370 &hkLsa) == ERROR_SUCCESS )
372 RegDeleteValue(hkLsa, "DisableLoopbackCheck");
376 RegDeleteValue(hkClient, "RemoveDisableLoopbackCheck");
377 RegCloseKey(hkClient);
380 RegCloseKey(hkMSV10);
388 static void afsd_InitServerPreferences(void)
391 DWORD dwType, dwSize;
395 DWORD dwHostSize = 256;
397 struct sockaddr_in saddr;
400 if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
401 AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\VLDB",
403 KEY_READ|KEY_QUERY_VALUE,
404 &hkPrefs) == ERROR_SUCCESS) {
406 RegQueryInfoKey( hkPrefs,
409 NULL, /* lpReserved */
410 NULL, /* lpcSubKeys */
411 NULL, /* lpcMaxSubKeyLen */
412 NULL, /* lpcMaxClassLen */
413 &dwPrefs, /* lpcValues */
414 NULL, /* lpcMaxValueNameLen */
415 NULL, /* lpcMaxValueLen */
416 NULL, /* lpcbSecurityDescriptor */
417 NULL /* lpftLastWriteTime */
420 for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
422 dwSize = sizeof(DWORD);
425 if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
426 &dwType, (LPBYTE)&dwRank, &dwSize))
428 afsi_log("RegEnumValue(hkPrefs) failed");
432 afsi_log("VLDB Server Preference: %s = %d",szHost, dwRank);
434 if (isdigit(szHost[0]))
436 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
440 if ((pEntry = gethostbyname (szHost)) == NULL)
443 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
445 saddr.sin_family = AF_INET;
446 dwRank += (rand() & 0x000f);
448 tsp = cm_FindServer(&saddr, CM_SERVER_VLDB);
449 if ( tsp ) /* an existing server - ref count increased */
451 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
453 /* set preferences for an existing vlserver */
454 cm_ChangeRankCellVLServer(tsp);
455 cm_PutServer(tsp); /* decrease refcount */
457 else /* add a new server without a cell */
459 tsp = cm_NewServer(&saddr, CM_SERVER_VLDB, NULL); /* refcount = 1 */
460 tsp->ipRank = (USHORT)dwRank;
464 RegCloseKey(hkPrefs);
467 if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
468 AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\File",
470 KEY_READ|KEY_QUERY_VALUE,
471 &hkPrefs) == ERROR_SUCCESS) {
473 RegQueryInfoKey( hkPrefs,
476 NULL, /* lpReserved */
477 NULL, /* lpcSubKeys */
478 NULL, /* lpcMaxSubKeyLen */
479 NULL, /* lpcMaxClassLen */
480 &dwPrefs, /* lpcValues */
481 NULL, /* lpcMaxValueNameLen */
482 NULL, /* lpcMaxValueLen */
483 NULL, /* lpcbSecurityDescriptor */
484 NULL /* lpftLastWriteTime */
487 for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
489 dwSize = sizeof(DWORD);
492 if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
493 &dwType, (LPBYTE)&dwRank, &dwSize))
495 afsi_log("RegEnumValue(hkPrefs) failed");
499 afsi_log("File Server Preference: %s = %d",szHost, dwRank);
501 if (isdigit(szHost[0]))
503 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
507 if ((pEntry = gethostbyname (szHost)) == NULL)
510 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
512 saddr.sin_family = AF_INET;
513 dwRank += (rand() & 0x000f);
515 tsp = cm_FindServer(&saddr, CM_SERVER_FILE);
516 if ( tsp ) /* an existing server - ref count increased */
518 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
520 /* find volumes which might have RO copy
521 /* on server and change the ordering of
524 cm_ChangeRankVolume(tsp);
525 cm_PutServer(tsp); /* decrease refcount */
527 else /* add a new server without a cell */
529 tsp = cm_NewServer(&saddr, CM_SERVER_FILE, NULL); /* refcount = 1 */
530 tsp->ipRank = (USHORT)dwRank;
534 RegCloseKey(hkPrefs);
539 * AFSD Initialization
542 int afsd_InitCM(char **reasonP)
545 afs_uint64 cacheBlocks;
550 DWORD rx_enable_peer_stats = 0;
551 DWORD rx_enable_process_stats = 0;
556 long virtualCache = 0;
557 char rootCellName[256];
558 struct rx_service *serverp;
559 static struct rx_securityClass *nullServerSecurityClassp;
567 /*int freelanceEnabled;*/
569 lana_number_t lanaNum;
572 int cm_noIPAddr; /* number of client network interfaces */
573 int cm_IPAddr[CM_MAXINTERFACE_ADDR]; /* client's IP address in host order */
574 int cm_SubnetMask[CM_MAXINTERFACE_ADDR];/* client's subnet mask in host order*/
575 int cm_NetMtu[CM_MAXINTERFACE_ADDR]; /* client's MTU sizes */
576 int cm_NetFlags[CM_MAXINTERFACE_ADDR]; /* network flags */
578 WSAStartup(0x0101, &WSAjunk);
580 afsd_initUpperCaseTable();
581 init_et_to_sys_error();
583 /* setup osidebug server at RPC slot 1000 */
584 osi_LongToUID(1000, &debugID);
585 code = osi_InitDebug(&debugID);
586 afsi_log("osi_InitDebug code %d", code);
588 // osi_LockTypeSetDefault("stat"); /* comment this out for speed */
590 if (code == RPC_S_NO_PROTSEQS)
591 *reasonP = "No RPC Protocol Sequences registered. Check HKLM\\SOFTWARE\\Microsoft\\RPC\\ClientProtocols";
593 *reasonP = "unknown error";
598 gethostname(cm_HostName, sizeof(cm_HostName));
599 afsi_log("gethostname %s", cm_HostName);
600 thp = gethostbyname(cm_HostName);
601 memcpy(&cm_HostAddr, thp->h_addr_list[0], 4);
603 /* seed random number generator */
604 srand(ntohl(cm_HostAddr));
606 /* Look up configuration parameters in Registry */
607 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
608 0, KEY_QUERY_VALUE, &parmKey);
609 if (code != ERROR_SUCCESS) {
610 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
611 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
612 NULL, code, 0, (LPTSTR)&msgBuf, 0, NULL);
613 StringCbPrintfA(buf, sizeof(buf),
614 "Failure in configuration while opening Registry: %s",
616 osi_panic(buf, __FILE__, __LINE__);
619 dummyLen = sizeof(maxcpus);
620 code = RegQueryValueEx(parmKey, "MaxCPUs", NULL, NULL,
621 (BYTE *) &maxcpus, &dummyLen);
622 if (code == ERROR_SUCCESS) {
624 DWORD_PTR processAffinityMask, systemAffinityMask;
626 hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION,
627 FALSE, GetCurrentProcessId());
628 if ( hProcess != NULL &&
629 GetProcessAffinityMask(hProcess, &processAffinityMask, &systemAffinityMask) )
632 DWORD_PTR mask, newAffinityMask;
639 for ( i=0, n=0, mask=1, newAffinityMask=0; i<bits && n<maxcpus; i++ ) {
640 if ( processAffinityMask & mask ) {
641 newAffinityMask |= mask;
647 SetProcessAffinityMask(hProcess, newAffinityMask);
648 CloseHandle(hProcess);
649 afsi_log("CPU Restrictions set to %d cpu(s); %d cpu(s) available", maxcpus, n);
651 afsi_log("CPU Restrictions set to %d cpu(s); unable to access process information", maxcpus);
655 dummyLen = sizeof(TraceOption);
656 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
657 (BYTE *) &TraceOption, &dummyLen);
658 afsi_log("Trace Options = %lX", TraceOption);
660 dummyLen = sizeof(traceBufSize);
661 code = RegQueryValueEx(parmKey, "TraceBufferSize", NULL, NULL,
662 (BYTE *) &traceBufSize, &dummyLen);
663 if (code == ERROR_SUCCESS)
664 afsi_log("Trace Buffer size %d", traceBufSize);
666 traceBufSize = CM_CONFIGDEFAULT_TRACEBUFSIZE;
667 afsi_log("Default trace buffer size %d", traceBufSize);
670 /* setup and enable debug log */
671 afsd_logp = osi_LogCreate("afsd", traceBufSize);
672 afsi_log("osi_LogCreate log addr %x", PtrToUlong(afsd_logp));
673 if ((TraceOption & 0x8)
678 osi_LogEnable(afsd_logp);
682 osi_Log0(afsd_logp, "Log init");
684 dummyLen = sizeof(cacheSize);
685 code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
686 (BYTE *) &cacheSize, &dummyLen);
687 if (code == ERROR_SUCCESS)
688 afsi_log("Cache size %d", cacheSize);
690 cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
691 afsi_log("Default cache size %d", cacheSize);
694 dummyLen = sizeof(logChunkSize);
695 code = RegQueryValueEx(parmKey, "ChunkSize", NULL, NULL,
696 (BYTE *) &logChunkSize, &dummyLen);
697 if (code == ERROR_SUCCESS) {
698 if (logChunkSize < 12 || logChunkSize > 30) {
699 afsi_log("Invalid chunk size %d, using default",
701 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
703 afsi_log("Chunk size %d", logChunkSize);
705 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
706 afsi_log("Default chunk size %d", logChunkSize);
708 cm_logChunkSize = logChunkSize;
709 cm_chunkSize = 1 << logChunkSize;
711 dummyLen = sizeof(numBkgD);
712 code = RegQueryValueEx(parmKey, "Daemons", NULL, NULL,
713 (BYTE *) &numBkgD, &dummyLen);
714 if (code == ERROR_SUCCESS)
715 afsi_log("%d background daemons", numBkgD);
717 numBkgD = CM_CONFIGDEFAULT_DAEMONS;
718 afsi_log("Defaulting to %d background daemons", numBkgD);
721 dummyLen = sizeof(numSvThreads);
722 code = RegQueryValueEx(parmKey, "ServerThreads", NULL, NULL,
723 (BYTE *) &numSvThreads, &dummyLen);
724 if (code == ERROR_SUCCESS)
725 afsi_log("%d server threads", numSvThreads);
727 numSvThreads = CM_CONFIGDEFAULT_SVTHREADS;
728 afsi_log("Defaulting to %d server threads", numSvThreads);
731 dummyLen = sizeof(stats);
732 code = RegQueryValueEx(parmKey, "Stats", NULL, NULL,
733 (BYTE *) &stats, &dummyLen);
734 if (code == ERROR_SUCCESS)
735 afsi_log("Status cache size %d", stats);
737 stats = CM_CONFIGDEFAULT_STATS;
738 afsi_log("Default status cache size %d", stats);
741 dummyLen = sizeof(ltt);
742 code = RegQueryValueEx(parmKey, "LogoffTokenTransfer", NULL, NULL,
743 (BYTE *) <t, &dummyLen);
744 if (code != ERROR_SUCCESS)
746 smb_LogoffTokenTransfer = ltt;
747 afsi_log("Logoff token transfer %s", (ltt ? "on" : "off"));
750 dummyLen = sizeof(ltto);
751 code = RegQueryValueEx(parmKey, "LogoffTokenTransferTimeout",
752 NULL, NULL, (BYTE *) <to, &dummyLen);
753 if (code != ERROR_SUCCESS)
758 smb_LogoffTransferTimeout = ltto;
759 afsi_log("Logoff token transfer timeout %d seconds", ltto);
761 dummyLen = sizeof(cm_rootVolumeName);
762 code = RegQueryValueEx(parmKey, "RootVolume", NULL, NULL,
763 cm_rootVolumeName, &dummyLen);
764 if (code == ERROR_SUCCESS)
765 afsi_log("Root volume %s", cm_rootVolumeName);
767 StringCbCopyA(cm_rootVolumeName, sizeof(cm_rootVolumeName), "root.afs");
768 afsi_log("Default root volume name root.afs");
771 cm_mountRootLen = sizeof(cm_mountRoot);
772 code = RegQueryValueEx(parmKey, "MountRoot", NULL, NULL,
773 cm_mountRoot, &cm_mountRootLen);
774 if (code == ERROR_SUCCESS) {
775 afsi_log("Mount root %s", cm_mountRoot);
776 cm_mountRootLen = (DWORD)strlen(cm_mountRoot);
778 StringCbCopyA(cm_mountRoot, sizeof(cm_mountRoot), "/afs");
783 dummyLen = sizeof(buf);
784 code = RegQueryValueEx(parmKey, "CachePath", NULL, ®Type,
786 if (code == ERROR_SUCCESS && buf[0]) {
787 if (regType == REG_EXPAND_SZ) {
788 dummyLen = ExpandEnvironmentStrings(buf, cm_CachePath, sizeof(cm_CachePath));
789 if (dummyLen > sizeof(cm_CachePath)) {
790 afsi_log("Cache path [%s] longer than %d after expanding env strings", buf, sizeof(cm_CachePath));
791 osi_panic("CachePath too long", __FILE__, __LINE__);
794 StringCbCopyA(cm_CachePath, sizeof(cm_CachePath), buf);
796 afsi_log("Cache path %s", cm_CachePath);
798 dummyLen = ExpandEnvironmentStrings("%TEMP%\\AFSCache", cm_CachePath, sizeof(cm_CachePath));
799 if (dummyLen > sizeof(cm_CachePath)) {
800 afsi_log("Cache path [%%TEMP%%\\AFSCache] longer than %d after expanding env strings",
801 sizeof(cm_CachePath));
802 osi_panic("CachePath too long", __FILE__, __LINE__);
804 afsi_log("Default cache path %s", cm_CachePath);
807 dummyLen = sizeof(virtualCache);
808 code = RegQueryValueEx(parmKey, "NonPersistentCaching", NULL, NULL,
809 (LPBYTE)&virtualCache, &dummyLen);
810 afsi_log("Cache type is %s", (virtualCache?"VIRTUAL":"FILE"));
813 dummyLen = sizeof(cm_ValidateCache);
814 code = RegQueryValueEx(parmKey, "ValidateCache", NULL, NULL,
815 (LPBYTE)&cm_ValidateCache, &dummyLen);
816 if ( cm_ValidateCache < 0 || cm_ValidateCache > 2 )
817 cm_ValidateCache = 1;
818 switch (cm_ValidateCache) {
820 afsi_log("Cache Validation disabled");
823 afsi_log("Cache Validation on Startup");
826 afsi_log("Cache Validation on Startup and Shutdown");
831 dummyLen = sizeof(traceOnPanic);
832 code = RegQueryValueEx(parmKey, "TrapOnPanic", NULL, NULL,
833 (BYTE *) &traceOnPanic, &dummyLen);
834 if (code != ERROR_SUCCESS)
835 traceOnPanic = 1; /* log */
836 afsi_log("Set to %s on panic", traceOnPanic ? "trap" : "not trap");
838 dummyLen = sizeof(reportSessionStartups);
839 code = RegQueryValueEx(parmKey, "ReportSessionStartups", NULL, NULL,
840 (BYTE *) &reportSessionStartups, &dummyLen);
841 if (code == ERROR_SUCCESS)
842 afsi_log("Session startups %s be recorded in the Event Log",
843 reportSessionStartups ? "will" : "will not");
845 reportSessionStartups = 0;
849 for ( i=0; i < MAXNUMSYSNAMES; i++ ) {
850 cm_sysNameList[i] = osi_Alloc(MAXSYSNAME);
851 cm_sysNameList[i][0] = '\0';
853 cm_sysName = cm_sysNameList[0];
855 dummyLen = sizeof(buf);
856 code = RegQueryValueEx(parmKey, "SysName", NULL, NULL, buf, &dummyLen);
857 if (code != ERROR_SUCCESS || !buf[0]) {
859 StringCbCopyA(buf, sizeof(buf), "ia64_win64");
860 #elif defined(_AMD64_)
861 StringCbCopyA(buf, sizeof(buf), "amd64_win64 x86_win32 i386_w2k");
862 #else /* assume x86 32-bit */
863 StringCbCopyA(buf, sizeof(buf), "x86_win32 i386_w2k i386_nt40");
866 afsi_log("Sys name %s", buf);
868 /* breakup buf into individual search string entries */
869 for (p = q = buf; p < buf + dummyLen; p++)
871 if (*p == '\0' || isspace(*p)) {
872 memcpy(cm_sysNameList[cm_sysNameCount],q,p-q);
873 cm_sysNameList[cm_sysNameCount][p-q] = '\0';
880 } while (*p == '\0' || isspace(*p));
886 StringCbCopyA(cm_sysName, MAXSYSNAME, cm_sysNameList[0]);
888 dummyLen = sizeof(cryptall);
889 code = RegQueryValueEx(parmKey, "SecurityLevel", NULL, NULL,
890 (BYTE *) &cryptall, &dummyLen);
891 if (code == ERROR_SUCCESS) {
892 afsi_log("SecurityLevel is %s", cryptall?"crypt":"clear");
895 afsi_log("Default SecurityLevel is clear");
899 LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_ON);
901 LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_OFF);
904 dummyLen = sizeof(cm_dnsEnabled);
905 code = RegQueryValueEx(parmKey, "UseDNS", NULL, NULL,
906 (BYTE *) &cm_dnsEnabled, &dummyLen);
907 if (code == ERROR_SUCCESS) {
908 afsi_log("DNS %s be used to find AFS cell servers",
909 cm_dnsEnabled ? "will" : "will not");
912 cm_dnsEnabled = 1; /* default on */
913 afsi_log("Default to use DNS to find AFS cell servers");
915 #else /* AFS_AFSDB_ENV */
916 afsi_log("AFS not built with DNS support to find AFS cell servers");
917 #endif /* AFS_AFSDB_ENV */
919 #ifdef AFS_FREELANCE_CLIENT
920 dummyLen = sizeof(cm_freelanceEnabled);
921 code = RegQueryValueEx(parmKey, "FreelanceClient", NULL, NULL,
922 (BYTE *) &cm_freelanceEnabled, &dummyLen);
923 if (code == ERROR_SUCCESS) {
924 afsi_log("Freelance client feature %s activated",
925 cm_freelanceEnabled ? "is" : "is not");
928 cm_freelanceEnabled = 1; /* default on */
930 #endif /* AFS_FREELANCE_CLIENT */
932 dummyLen = sizeof(smb_hideDotFiles);
933 code = RegQueryValueEx(parmKey, "HideDotFiles", NULL, NULL,
934 (BYTE *) &smb_hideDotFiles, &dummyLen);
935 if (code != ERROR_SUCCESS) {
936 smb_hideDotFiles = 1; /* default on */
938 afsi_log("Dot files/dirs will %sbe marked hidden",
939 smb_hideDotFiles ? "" : "not ");
941 dummyLen = sizeof(smb_maxMpxRequests);
942 code = RegQueryValueEx(parmKey, "MaxMpxRequests", NULL, NULL,
943 (BYTE *) &smb_maxMpxRequests, &dummyLen);
944 if (code != ERROR_SUCCESS) {
945 smb_maxMpxRequests = 50;
947 afsi_log("Maximum number of multiplexed sessions is %d", smb_maxMpxRequests);
949 dummyLen = sizeof(smb_maxVCPerServer);
950 code = RegQueryValueEx(parmKey, "MaxVCPerServer", NULL, NULL,
951 (BYTE *) &smb_maxVCPerServer, &dummyLen);
952 if (code != ERROR_SUCCESS) {
953 smb_maxVCPerServer = 100;
955 afsi_log("Maximum number of VCs per server is %d", smb_maxVCPerServer);
957 dummyLen = sizeof(smb_authType);
958 code = RegQueryValueEx(parmKey, "SMBAuthType", NULL, NULL,
959 (BYTE *) &smb_authType, &dummyLen);
961 if (code != ERROR_SUCCESS ||
962 (smb_authType != SMB_AUTH_EXTENDED && smb_authType != SMB_AUTH_NTLM && smb_authType != SMB_AUTH_NONE)) {
963 smb_authType = SMB_AUTH_EXTENDED; /* default is to use extended authentication */
965 afsi_log("SMB authentication type is %s", ((smb_authType == SMB_AUTH_NONE)?"NONE":((smb_authType == SMB_AUTH_EXTENDED)?"EXTENDED":"NTLM")));
967 dummyLen = sizeof(rx_nojumbo);
968 code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
969 (BYTE *) &rx_nojumbo, &dummyLen);
970 if (code != ERROR_SUCCESS) {
974 afsi_log("RX Jumbograms are disabled");
976 dummyLen = sizeof(rx_mtu);
977 code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
978 (BYTE *) &rx_mtu, &dummyLen);
979 if (code != ERROR_SUCCESS || !rx_mtu) {
983 afsi_log("RX maximum MTU is %d", rx_mtu);
985 dummyLen = sizeof(rx_enable_peer_stats);
986 code = RegQueryValueEx(parmKey, "RxEnablePeerStats", NULL, NULL,
987 (BYTE *) &rx_enable_peer_stats, &dummyLen);
988 if (code != ERROR_SUCCESS) {
989 rx_enable_peer_stats = 0;
991 if (rx_enable_peer_stats)
992 afsi_log("RX Peer Statistics gathering is enabled");
994 dummyLen = sizeof(rx_enable_process_stats);
995 code = RegQueryValueEx(parmKey, "RxEnableProcessStats", NULL, NULL,
996 (BYTE *) &rx_enable_process_stats, &dummyLen);
997 if (code != ERROR_SUCCESS) {
998 rx_enable_process_stats = 0;
1000 if (rx_enable_process_stats)
1001 afsi_log("RX Process Statistics gathering is enabled");
1003 dummyLen = sizeof(DWORD);
1004 code = RegQueryValueEx(parmKey, "daemonCheckDownInterval", NULL, NULL,
1005 (BYTE *) &dwValue, &dummyLen);
1006 if (code == ERROR_SUCCESS)
1007 cm_daemonCheckDownInterval = dwValue;
1008 afsi_log("daemonCheckDownInterval is %d", cm_daemonCheckDownInterval);
1010 dummyLen = sizeof(DWORD);
1011 code = RegQueryValueEx(parmKey, "daemonCheckUpInterval", NULL, NULL,
1012 (BYTE *) &dwValue, &dummyLen);
1013 if (code == ERROR_SUCCESS)
1014 cm_daemonCheckUpInterval = dwValue;
1015 afsi_log("daemonCheckUpInterval is %d", cm_daemonCheckUpInterval);
1017 dummyLen = sizeof(DWORD);
1018 code = RegQueryValueEx(parmKey, "daemonCheckVolInterval", NULL, NULL,
1019 (BYTE *) &dwValue, &dummyLen);
1020 if (code == ERROR_SUCCESS)
1021 cm_daemonCheckVolInterval = dwValue;
1022 afsi_log("daemonCheckVolInterval is %d", cm_daemonCheckVolInterval);
1024 dummyLen = sizeof(DWORD);
1025 code = RegQueryValueEx(parmKey, "daemonCheckCBInterval", NULL, NULL,
1026 (BYTE *) &dwValue, &dummyLen);
1027 if (code == ERROR_SUCCESS)
1028 cm_daemonCheckCBInterval = dwValue;
1029 afsi_log("daemonCheckCBInterval is %d", cm_daemonCheckCBInterval);
1031 dummyLen = sizeof(DWORD);
1032 code = RegQueryValueEx(parmKey, "daemonCheckLockInterval", NULL, NULL,
1033 (BYTE *) &dwValue, &dummyLen);
1034 if (code == ERROR_SUCCESS)
1035 cm_daemonCheckLockInterval = dwValue;
1036 afsi_log("daemonCheckLockInterval is %d", cm_daemonCheckLockInterval);
1038 dummyLen = sizeof(DWORD);
1039 code = RegQueryValueEx(parmKey, "daemonCheckTokenInterval", NULL, NULL,
1040 (BYTE *) &dwValue, &dummyLen);
1041 if (code == ERROR_SUCCESS)
1042 cm_daemonTokenCheckInterval = dwValue;
1043 afsi_log("daemonCheckTokenInterval is %d", cm_daemonTokenCheckInterval);
1045 dummyLen = sizeof(DWORD);
1046 code = RegQueryValueEx(parmKey, "CallBackPort", NULL, NULL,
1047 (BYTE *) &dwValue, &dummyLen);
1048 if (code == ERROR_SUCCESS) {
1049 cm_callbackport = (unsigned short) dwValue;
1051 afsi_log("CM CallBackPort is %u", cm_callbackport);
1053 dummyLen = sizeof(DWORD);
1054 code = RegQueryValueEx(parmKey, "EnableServerLocks", NULL, NULL,
1055 (BYTE *) &dwValue, &dummyLen);
1056 if (code == ERROR_SUCCESS) {
1057 cm_enableServerLocks = (unsigned short) dwValue;
1059 switch (cm_enableServerLocks) {
1061 afsi_log("EnableServerLocks: never");
1064 afsi_log("EnableServerLocks: always");
1068 afsi_log("EnableServerLocks: server requested");
1072 dummyLen = sizeof(DWORD);
1073 code = RegQueryValueEx(parmKey, "DeleteReadOnly", NULL, NULL,
1074 (BYTE *) &dwValue, &dummyLen);
1075 if (code == ERROR_SUCCESS) {
1076 cm_deleteReadOnly = (unsigned short) dwValue;
1078 afsi_log("CM DeleteReadOnly is %u", cm_deleteReadOnly);
1080 RegCloseKey (parmKey);
1082 /* Call lanahelper to get Netbios name, lan adapter number and gateway flag */
1083 if (SUCCEEDED(code = lana_GetUncServerNameEx(cm_NetbiosName, &lanaNum, &isGateway, LANA_NETBIOS_NAME_FULL))) {
1084 LANadapter = (lanaNum == LANA_INVALID)? -1: lanaNum;
1086 if (LANadapter != -1)
1087 afsi_log("LAN adapter number %d", LANadapter);
1089 afsi_log("LAN adapter number not determined");
1092 afsi_log("Set for gateway service");
1094 afsi_log("Using >%s< as SMB server name", cm_NetbiosName);
1096 /* something went horribly wrong. We can't proceed without a netbios name */
1097 StringCbPrintfA(buf,sizeof(buf),"Netbios name could not be determined: %li", code);
1098 osi_panic(buf, __FILE__, __LINE__);
1101 cacheBlocks = ((afs_uint64)cacheSize * 1024) / CM_CONFIGDEFAULT_BLOCKSIZE;
1103 /* get network related info */
1104 cm_noIPAddr = CM_MAXINTERFACE_ADDR;
1105 code = syscfg_GetIFInfo(&cm_noIPAddr,
1106 cm_IPAddr, cm_SubnetMask,
1107 cm_NetMtu, cm_NetFlags);
1109 if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
1110 afsi_log("syscfg_GetIFInfo error code %d", code);
1112 afsi_log("First Network address %x SubnetMask %x",
1113 cm_IPAddr[0], cm_SubnetMask[0]);
1116 * Save client configuration for GetCacheConfig requests
1118 cm_initParams.nChunkFiles = 0;
1119 cm_initParams.nStatCaches = stats;
1120 cm_initParams.nDataCaches = (afs_uint32)(cacheBlocks > 0xFFFFFFFF ? 0xFFFFFFFF : cacheBlocks);
1121 cm_initParams.nVolumeCaches = stats/2;
1122 cm_initParams.firstChunkSize = cm_chunkSize;
1123 cm_initParams.otherChunkSize = cm_chunkSize;
1124 cm_initParams.cacheSize = cacheSize;
1125 cm_initParams.setTime = 0;
1126 cm_initParams.memCache = 1;
1128 /* Ensure the AFS Netbios Name is registered to allow loopback access */
1129 configureBackConnectionHostNames();
1131 /* init user daemon, and other packages */
1144 code = cm_InitMappedMemory(virtualCache, cm_CachePath, stats, cm_chunkSize, cacheBlocks);
1145 afsi_log("cm_InitMappedMemory code %x", code);
1147 *reasonP = "error initializing cache file";
1151 #ifdef AFS_AFSDB_ENV
1152 #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
1153 if (cm_InitDNS(cm_dnsEnabled) == -1)
1154 cm_dnsEnabled = 0; /* init failed, so deactivate */
1155 afsi_log("cm_InitDNS %d", cm_dnsEnabled);
1159 /* Set RX parameters before initializing RX */
1162 afsi_log("rx_SetNoJumbo successful");
1165 if ( rx_mtu != -1 ) {
1166 rx_SetMaxMTU(rx_mtu);
1167 afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
1170 /* initialize RX, and tell it to listen to the callbackport,
1171 * which is used for callback RPC messages.
1173 code = rx_Init(htons(cm_callbackport));
1175 afsi_log("rx_Init code %x - retrying with a random port number", code);
1178 afsi_log("rx_Init code %x", code);
1180 *reasonP = "afsd: failed to init rx client";
1184 /* create an unauthenticated service #1 for callbacks */
1185 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1186 serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
1187 RXAFSCB_ExecuteRequest);
1188 afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1189 if (serverp == NULL) {
1190 *reasonP = "unknown error";
1194 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1195 serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
1196 &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
1197 afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1198 if (serverp == NULL) {
1199 *reasonP = "unknown error";
1203 /* start server threads, *not* donating this one to the pool */
1205 afsi_log("rx_StartServer");
1207 if (rx_enable_peer_stats)
1208 rx_enablePeerRPCStats();
1210 if (rx_enable_process_stats)
1211 rx_enableProcessRPCStats();
1213 code = cm_GetRootCellName(rootCellName);
1214 afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s",
1215 code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
1216 if (code != 0 && !cm_freelanceEnabled)
1218 *reasonP = "can't find root cell name in CellServDB";
1221 else if (cm_freelanceEnabled)
1222 cm_data.rootCellp = NULL;
1224 if (code == 0 && !cm_freelanceEnabled)
1226 cm_data.rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
1227 afsi_log("cm_GetCell addr %x", PtrToUlong(cm_data.rootCellp));
1228 if (cm_data.rootCellp == NULL)
1230 *reasonP = "can't find root cell in afsdcell.ini";
1235 #ifdef AFS_FREELANCE_CLIENT
1236 if (cm_freelanceEnabled)
1240 /* Initialize the RPC server for session keys */
1243 afsd_InitServerPreferences();
1247 int afsd_ShutdownCM(void)
1249 cm_ReleaseSCache(cm_data.rootSCachep);
1254 int afsd_InitDaemons(char **reasonP)
1261 /* this should really be in an init daemon from here on down */
1263 if (!cm_freelanceEnabled) {
1266 osi_Log0(afsd_logp, "Loading Root Volume from cell");
1268 code = cm_GetVolumeByName(cm_data.rootCellp, cm_rootVolumeName, cm_rootUserp,
1269 &req, CM_FLAG_CREATE, &cm_data.rootVolumep);
1270 afsi_log("cm_GetVolumeByName code %x root vol %x", code,
1271 (code ? (cm_volume_t *)-1 : cm_data.rootVolumep));
1272 } while (code && --attempts);
1274 *reasonP = "can't find root volume in root cell";
1279 /* compute the root fid */
1280 if (!cm_freelanceEnabled) {
1281 cm_data.rootFid.cell = cm_data.rootCellp->cellID;
1282 cm_data.rootFid.volume = cm_GetROVolumeID(cm_data.rootVolumep);
1283 cm_data.rootFid.vnode = 1;
1284 cm_data.rootFid.unique = 1;
1287 cm_FakeRootFid(&cm_data.rootFid);
1289 code = cm_GetSCache(&cm_data.rootFid, &cm_data.rootSCachep, cm_rootUserp, &req);
1290 afsi_log("cm_GetSCache code %x scache %x", code,
1291 (code ? (cm_scache_t *)-1 : cm_data.rootSCachep));
1293 *reasonP = "unknown error";
1297 cm_InitDaemon(numBkgD);
1298 afsi_log("cm_InitDaemon complete");
1303 int afsd_InitSMB(char **reasonP, void *aMBfunc)
1310 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1311 0, KEY_QUERY_VALUE, &parmKey);
1312 if (code == ERROR_SUCCESS) {
1313 dummyLen = sizeof(DWORD);
1314 code = RegQueryValueEx(parmKey, "StoreAnsiFilenames", NULL, NULL,
1315 (BYTE *) &dwValue, &dummyLen);
1316 if (code == ERROR_SUCCESS)
1317 smb_StoreAnsiFilenames = dwValue ? 1 : 0;
1318 RegCloseKey (parmKey);
1321 /* Do this last so that we don't handle requests before init is done.
1322 * Here we initialize the SMB listener.
1324 smb_Init(afsd_logp, cm_NetbiosName, smb_UseV3, LANadapter, numSvThreads, aMBfunc);
1325 afsi_log("smb_Init complete");
1338 #pragma pack( push, before_imagehlp, 8 )
1339 #include <imagehlp.h>
1340 #pragma pack( pop, before_imagehlp )
1342 #define MAXNAMELEN 1024
1344 void afsd_printStack(HANDLE hThread, CONTEXT *c)
1347 HANDLE hProcess = GetCurrentProcess();
1349 #if defined(_AMD64_)
1351 #elif defined(_X86_)
1355 char functionName[MAXNAMELEN];
1357 IMAGEHLP_MODULE Module;
1361 IMAGEHLP_SYMBOL *pSym;
1363 afsi_log_useTimestamp = 0;
1365 pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
1367 memset( &s, '\0', sizeof s );
1368 if (!SymInitialize(hProcess, NULL, 1) )
1370 afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
1372 SymCleanup( hProcess );
1378 symOptions = SymGetOptions();
1379 symOptions |= SYMOPT_LOAD_LINES;
1380 symOptions &= ~SYMOPT_UNDNAME;
1381 SymSetOptions( symOptions );
1384 * init STACKFRAME for first call
1385 * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
1386 * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
1387 * and good riddance.
1389 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
1390 #error The STACKFRAME initialization in afsd_printStack() for this platform
1391 #error must be properly configured
1392 #elif defined(_AMD64_)
1393 s.AddrPC.Offset = 0;
1394 s.AddrPC.Mode = AddrModeFlat;
1395 s.AddrFrame.Offset = 0;
1396 s.AddrFrame.Mode = AddrModeFlat;
1398 s.AddrPC.Offset = c->Eip;
1399 s.AddrPC.Mode = AddrModeFlat;
1400 s.AddrFrame.Offset = c->Ebp;
1401 s.AddrFrame.Mode = AddrModeFlat;
1404 memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
1405 pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
1406 pSym->MaxNameLength = MAXNAMELEN;
1408 memset( &Line, '\0', sizeof Line );
1409 Line.SizeOfStruct = sizeof Line;
1411 memset( &Module, '\0', sizeof Module );
1412 Module.SizeOfStruct = sizeof Module;
1416 afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
1418 for ( frameNum = 0; ; ++ frameNum )
1421 * get next stack frame (StackWalk(), SymFunctionTableAccess(),
1422 * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
1423 * ERROR_NOACCESS (998), you can assume that either you are done, or
1424 * that the stack is so hosed that the next deeper frame could not be
1427 if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c,
1428 NULL, SymFunctionTableAccess, SymGetModuleBase,
1432 /* display its contents */
1433 afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
1434 frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
1435 s.AddrPC.Offset, s.AddrReturn.Offset,
1436 s.AddrFrame.Offset, s.AddrStack.Offset );
1438 if ( s.AddrPC.Offset == 0 )
1440 afsi_log("(-nosymbols- PC == 0)" );
1444 /* show procedure info from a valid PC */
1445 if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
1447 if ( GetLastError() != ERROR_INVALID_ADDRESS )
1449 afsi_log("SymGetSymFromAddr(): errno = %lu",
1455 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN,
1457 afsi_log("%s", functionName );
1461 afsi_log(" %+ld bytes", (long) offset);
1465 if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
1467 if (GetLastError() != ERROR_INVALID_ADDRESS)
1469 afsi_log("Error: SymGetLineFromAddr(): errno = %lu",
1475 afsi_log(" Line: %s(%lu) %+ld bytes", Line.FileName,
1476 Line.LineNumber, offset);
1480 /* no return address means no deeper stackframe */
1481 if (s.AddrReturn.Offset == 0)
1488 if (GetLastError() != 0)
1490 afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
1493 SymCleanup(hProcess);
1499 static DWORD *afsd_crtDbgBreakCurrent = NULL;
1500 static DWORD afsd_crtDbgBreaks[256];
1503 static EFaultRepRetVal (WINAPI *pReportFault)(LPEXCEPTION_POINTERS pep, DWORD dwMode) = NULL;
1504 static BOOL (WINAPI *pMiniDumpWriteDump)(HANDLE hProcess,DWORD ProcessId,HANDLE hFile,
1505 MINIDUMP_TYPE DumpType,
1506 PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
1507 PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
1508 PMINIDUMP_CALLBACK_INFORMATION CallbackParam) = NULL;
1517 code = GetEnvironmentVariable("TEMP", wd, sizeof(wd));
1518 if ( code == 0 || code > sizeof(wd) )
1520 if (!GetWindowsDirectory(wd, sizeof(wd)))
1523 StringCbCatA(wd, sizeof(wd), "\\afsd.dmp");
1524 return CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1525 CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
1529 GenerateMiniDump(PEXCEPTION_POINTERS ep)
1531 if (IsDebuggerPresent())
1536 // Generate exception to get proper context in dump
1539 RaiseException(DBG_CONTINUE, 0, 0, NULL);
1541 __except(GenerateMiniDump(GetExceptionInformation()), EXCEPTION_CONTINUE_EXECUTION)
1547 MINIDUMP_EXCEPTION_INFORMATION eInfo;
1548 HANDLE hFile = NULL;
1549 HMODULE hDbgHelp = NULL;
1551 hDbgHelp = LoadLibrary("Dbghelp.dll");
1552 if ( hDbgHelp == NULL )
1555 (FARPROC) pMiniDumpWriteDump = GetProcAddress(hDbgHelp, "MiniDumpWriteDump");
1556 if ( pMiniDumpWriteDump == NULL ) {
1557 FreeLibrary(hDbgHelp);
1561 hFile = OpenDumpFile();
1568 DWORD dwMiniDumpType = MiniDumpWithDataSegs;
1570 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1571 0, KEY_QUERY_VALUE, &parmKey);
1572 if (code == ERROR_SUCCESS) {
1573 dummyLen = sizeof(DWORD);
1574 code = RegQueryValueEx(parmKey, "MiniDumpType", NULL, NULL,
1575 (BYTE *) &dwValue, &dummyLen);
1576 if (code == ERROR_SUCCESS)
1577 dwMiniDumpType = dwValue;
1578 RegCloseKey (parmKey);
1581 eInfo.ThreadId = GetCurrentThreadId();
1582 eInfo.ExceptionPointers = ep;
1583 eInfo.ClientPointers = FALSE;
1585 pMiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(),
1586 hFile, dwMiniDumpType, ep ? &eInfo : NULL,
1591 FreeLibrary(hDbgHelp);
1595 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
1599 BOOL allocRequestBrk = FALSE;
1601 HMODULE hLib = NULL;
1603 afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n",
1604 ep->ExceptionRecord->ExceptionCode,
1605 ep->ExceptionRecord->ExceptionAddress);
1608 if (afsd_crtDbgBreakCurrent &&
1609 *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
1611 allocRequestBrk = TRUE;
1612 afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
1616 /* save context if we want to print the stack information */
1617 context = *ep->ContextRecord;
1619 afsd_printStack(GetCurrentThread(), &context);
1621 GenerateMiniDump(ep);
1623 hLib = LoadLibrary("Faultrep.dll");
1625 (FARPROC) pReportFault = GetProcAddress(hLib, "ReportFault");
1627 pReportFault(ep, 0);
1631 if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
1633 afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
1636 if (allocRequestBrk)
1638 afsd_crtDbgBreakCurrent++;
1639 _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
1643 ep->ContextRecord->Eip++;
1645 return EXCEPTION_CONTINUE_EXECUTION;
1649 return EXCEPTION_CONTINUE_SEARCH;
1653 void afsd_SetUnhandledExceptionFilter()
1655 SetUnhandledExceptionFilter(afsd_ExceptionFilter);
1659 void afsd_DbgBreakAllocInit()
1661 memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
1662 afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
1665 void afsd_DbgBreakAdd(DWORD requestNumber)
1668 for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
1670 if (afsd_crtDbgBreaks[i] == -1)
1675 afsd_crtDbgBreaks[i] = requestNumber;
1677 _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);