2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 #include <afs/param.h>
12 #include <afs/afs_args.h>
27 #include <rx\rx_null.h>
28 #include <WINNT/syscfg.h>
29 #include <WINNT/afsreg.h>
33 #include "lanahelper.h"
35 #include "cm_memmap.h"
37 extern int RXAFSCB_ExecuteRequest(struct rx_call *z_call);
38 extern int RXSTATS_ExecuteRequest(struct rx_call *z_call);
40 extern afs_int32 cryptall;
41 extern int cm_enableServerLocks;
45 cm_config_data_t cm_data;
47 char cm_rootVolumeName[VL_MAXNAMELEN];
48 DWORD cm_rootVolumeNameLen;
49 char cm_mountRoot[1024];
50 DWORD cm_mountRootLen;
53 #ifdef AFS_FREELANCE_CLIENT
55 #endif /* freelance */
68 char cm_HostName[200];
70 unsigned short cm_callbackport = CM_DEFAULT_CALLBACKPORT;
72 char cm_NetbiosName[MAX_NB_NAME_LENGTH] = "";
74 char cm_CachePath[MAX_PATH];
75 DWORD cm_CachePathLen;
76 DWORD cm_ValidateCache = 1;
78 BOOL isGateway = FALSE;
80 BOOL reportSessionStartups = FALSE;
82 cm_initparams_v1 cm_initParams;
85 unsigned int cm_sysNameCount = 0;
86 char *cm_sysNameList[MAXNUMSYSNAMES];
88 DWORD TraceOption = 0;
91 * AFSD Initialization Log
93 * This is distinct from the regular debug logging facility.
94 * Log items go directly to a file, not to an array in memory, so that even
95 * if AFSD crashes, the log can be inspected.
101 int cm_dnsEnabled = 1;
105 static int afsi_log_useTimestamp = 1;
108 afsi_log(char *pattern, ...)
110 char s[256], t[100], d[100], u[512];
113 va_start(ap, pattern);
115 StringCbVPrintfA(s, sizeof(s), pattern, ap);
116 if ( afsi_log_useTimestamp ) {
117 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
118 GetDateFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, d, sizeof(d));
119 StringCbPrintfA(u, sizeof(u), "%s %s: %s\n", d, t, s);
120 if (afsi_file != INVALID_HANDLE_VALUE)
121 WriteFile(afsi_file, u, (DWORD)strlen(u), &zilch, NULL);
126 if (afsi_file != INVALID_HANDLE_VALUE)
127 WriteFile(afsi_file, s, (DWORD)strlen(s), &zilch, NULL);
131 extern initUpperCaseTable();
132 void afsd_initUpperCaseTable()
134 initUpperCaseTable();
141 char t[100], u[100], *p, *path;
147 DWORD maxLogSize = 100 * 1024;
149 afsi_file = INVALID_HANDLE_VALUE;
150 code = GetEnvironmentVariable("TEMP", wd, sizeof(wd));
151 if ( code == 0 || code > sizeof(wd) )
153 code = GetWindowsDirectory(wd, sizeof(wd));
157 StringCbCatA(wd, sizeof(wd), "\\afsd_init.log");
158 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
159 afsi_file = CreateFile(wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
160 OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
162 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
163 0, KEY_QUERY_VALUE, &parmKey);
164 if (code == ERROR_SUCCESS) {
165 dummyLen = sizeof(maxLogSize);
166 code = RegQueryValueEx(parmKey, "MaxLogSize", NULL, NULL,
167 (BYTE *) &maxLogSize, &dummyLen);
168 RegCloseKey (parmKey);
172 dwLow = GetFileSize( afsi_file, &dwHigh );
173 if ( dwHigh > 0 || dwLow >= maxLogSize ) {
174 CloseHandle(afsi_file);
175 afsi_file = CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
176 CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
180 SetFilePointer(afsi_file, 0, NULL, FILE_END);
181 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, u, sizeof(u));
182 StringCbCatA(t, sizeof(t), ": Create log file\n");
183 StringCbCatA(u, sizeof(u), ": Created log file\n");
184 WriteFile(afsi_file, t, (DWORD)strlen(t), &zilch, NULL);
185 WriteFile(afsi_file, u, (DWORD)strlen(u), &zilch, NULL);
187 code = GetEnvironmentVariable("PATH", NULL, 0);
189 code = GetEnvironmentVariable("PATH", path, code);
190 WriteFile(afsi_file, p, (DWORD)strlen(p), &zilch, NULL);
191 WriteFile(afsi_file, path, (DWORD)strlen(path), &zilch, NULL);
192 WriteFile(afsi_file, "\n", (DWORD)1, &zilch, NULL);
195 /* Initialize C RTL Code Page conversion functions */
196 /* All of the path info obtained from the SMB client is in the OEM code page */
197 afsi_log("OEM Code Page = %d", GetOEMCP());
198 afsi_log("locale = %s", setlocale(LC_ALL,NULL));
200 /* Two things to look into. First, should mbstowcs() be performing
201 * character set translations from OEM to Unicode in smb3.c;
202 * Second, do we need to set this translation in each function
203 * due to multi-threading.
205 afsi_log("locale -> %s", setlocale(LC_ALL, ".OCP"));
206 afsi_log("_setmbcp = %d -> %d", _setmbcp(_MB_CP_OEM), _getmbcp());
211 * Standard AFSD trace
214 void afsd_ForceTrace(BOOL flush)
223 len = GetTempPath(sizeof(buf)-10, buf);
224 StringCbCopyA(&buf[len], sizeof(buf)-len, "/afsd.log");
225 handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
226 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
227 if (handle == INVALID_HANDLE_VALUE) {
229 osi_panic("Cannot create log file", __FILE__, __LINE__);
231 osi_LogPrint(afsd_logp, handle);
233 FlushFileBuffers(handle);
238 configureBackConnectionHostNames(void)
240 /* On Windows XP SP2, Windows 2003 SP1, and all future Windows operating systems
241 * there is a restriction on the use of SMB authentication on loopback connections.
242 * There are two work arounds available:
244 * (1) We can disable the check for matching host names. This does not
246 * [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa]
247 * "DisableLoopbackCheck"=dword:00000001
249 * (2) We can add the AFS SMB/CIFS service name to an approved list. This
250 * does require a reboot:
251 * [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0]
252 * "BackConnectionHostNames"=multi-sz
254 * The algorithm will be:
255 * (1) Check to see if cm_NetbiosName exists in the BackConnectionHostNames list
256 * (2a) If not, add it to the list. (This will not take effect until the next reboot.)
257 * (2b1) and check to see if DisableLoopbackCheck is set.
258 * (2b2) If not set, set the DisableLoopbackCheck value to 0x1
259 * (2b3) and create HKLM\SOFTWARE\OpenAFS\Client UnsetDisableLoopbackCheck
260 * (2c) else If cm_NetbiosName exists in the BackConnectionHostNames list,
261 * check for the UnsetDisableLoopbackCheck value.
262 * If set, set the DisableLoopbackCheck flag to 0x0
263 * and delete the UnsetDisableLoopbackCheck value
265 * Starting in Longhorn Beta 1, an entry in the BackConnectionHostNames value will
266 * force Windows to use the loopback authentication mechanism for the specified
275 PBYTE pHostNames = NULL, pName = NULL;
276 BOOL bNameFound = FALSE;
278 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
279 "SYSTEM\\CurrentControlSet\\Control\\Lsa\\MSV1_0",
282 &hkMSV10) == ERROR_SUCCESS )
284 if (RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0,
285 &dwType, NULL, &dwSize) == ERROR_SUCCESS) {
286 dwSize += strlen(cm_NetbiosName) + 1;
287 pHostNames = malloc(dwSize);
288 if (RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0, &dwType,
289 pHostNames, &dwSize) == ERROR_SUCCESS) {
290 for (pName = pHostNames; *pName ; pName += strlen(pName) + 1)
292 if ( !stricmp(pName, cm_NetbiosName) ) {
301 size_t size = strlen(cm_NetbiosName) + 2;
303 pHostNames = malloc(size);
307 StringCbCopyA(pName, size, cm_NetbiosName);
309 *pName = '\0'; /* add a second nul terminator */
311 dwType = REG_MULTI_SZ;
312 RegSetValueEx( hkMSV10, "BackConnectionHostNames", 0, dwType, pHostNames, dwSize);
314 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
315 "SYSTEM\\CurrentControlSet\\Control\\Lsa",
318 &hkLsa) == ERROR_SUCCESS )
320 dwSize = sizeof(DWORD);
321 if ( RegQueryValueEx( hkLsa, "DisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) != ERROR_SUCCESS ||
324 dwSize = sizeof(DWORD);
326 RegSetValueEx( hkLsa, "DisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
328 if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
329 AFSREG_CLT_OPENAFS_SUBKEY,
332 REG_OPTION_NON_VOLATILE,
336 NULL) == ERROR_SUCCESS) {
339 dwSize = sizeof(DWORD);
341 RegSetValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
342 RegCloseKey(hkClient);
348 if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
349 AFSREG_CLT_OPENAFS_SUBKEY,
352 REG_OPTION_NON_VOLATILE,
356 NULL) == ERROR_SUCCESS) {
358 dwSize = sizeof(DWORD);
359 if ( RegQueryValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) == ERROR_SUCCESS &&
361 if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
362 "SYSTEM\\CurrentControlSet\\Control\\Lsa",
365 &hkLsa) == ERROR_SUCCESS )
367 RegDeleteValue(hkLsa, "DisableLoopbackCheck");
371 RegDeleteValue(hkClient, "RemoveDisableLoopbackCheck");
372 RegCloseKey(hkClient);
375 RegCloseKey(hkMSV10);
384 static void afsd_InitServerPreferences(void)
387 DWORD dwType, dwSize;
391 DWORD dwHostSize = 256;
393 struct sockaddr_in saddr;
396 if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
397 AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\VLDB",
399 KEY_READ|KEY_QUERY_VALUE,
400 &hkPrefs) == ERROR_SUCCESS) {
402 RegQueryInfoKey( hkPrefs,
405 NULL, /* lpReserved */
406 NULL, /* lpcSubKeys */
407 NULL, /* lpcMaxSubKeyLen */
408 NULL, /* lpcMaxClassLen */
409 &dwPrefs, /* lpcValues */
410 NULL, /* lpcMaxValueNameLen */
411 NULL, /* lpcMaxValueLen */
412 NULL, /* lpcbSecurityDescriptor */
413 NULL /* lpftLastWriteTime */
416 for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
418 dwSize = sizeof(DWORD);
421 if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
422 &dwType, (LPBYTE)&dwRank, &dwSize))
424 afsi_log("RegEnumValue(hkPrefs) failed");
428 afsi_log("VLDB Server Preference: %s = %d",szHost, dwRank);
430 if (isdigit(szHost[0]))
432 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
436 if ((pEntry = gethostbyname (szHost)) == NULL)
439 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
441 saddr.sin_family = AF_INET;
442 dwRank += (rand() & 0x000f);
444 tsp = cm_FindServer(&saddr, CM_SERVER_VLDB);
445 if ( tsp ) /* an existing server - ref count increased */
447 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
449 /* set preferences for an existing vlserver */
450 cm_ChangeRankCellVLServer(tsp);
451 cm_PutServer(tsp); /* decrease refcount */
453 else /* add a new server without a cell */
455 tsp = cm_NewServer(&saddr, CM_SERVER_VLDB, NULL); /* refcount = 1 */
456 tsp->ipRank = (USHORT)dwRank;
460 RegCloseKey(hkPrefs);
463 if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
464 AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\File",
466 KEY_READ|KEY_QUERY_VALUE,
467 &hkPrefs) == ERROR_SUCCESS) {
469 RegQueryInfoKey( hkPrefs,
472 NULL, /* lpReserved */
473 NULL, /* lpcSubKeys */
474 NULL, /* lpcMaxSubKeyLen */
475 NULL, /* lpcMaxClassLen */
476 &dwPrefs, /* lpcValues */
477 NULL, /* lpcMaxValueNameLen */
478 NULL, /* lpcMaxValueLen */
479 NULL, /* lpcbSecurityDescriptor */
480 NULL /* lpftLastWriteTime */
483 for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
485 dwSize = sizeof(DWORD);
488 if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
489 &dwType, (LPBYTE)&dwRank, &dwSize))
491 afsi_log("RegEnumValue(hkPrefs) failed");
495 afsi_log("File Server Preference: %s = %d",szHost, dwRank);
497 if (isdigit(szHost[0]))
499 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
503 if ((pEntry = gethostbyname (szHost)) == NULL)
506 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
508 saddr.sin_family = AF_INET;
509 dwRank += (rand() & 0x000f);
511 tsp = cm_FindServer(&saddr, CM_SERVER_FILE);
512 if ( tsp ) /* an existing server - ref count increased */
514 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
516 /* find volumes which might have RO copy
517 /* on server and change the ordering of
520 cm_ChangeRankVolume(tsp);
521 cm_PutServer(tsp); /* decrease refcount */
523 else /* add a new server without a cell */
525 tsp = cm_NewServer(&saddr, CM_SERVER_FILE, NULL); /* refcount = 1 */
526 tsp->ipRank = (USHORT)dwRank;
530 RegCloseKey(hkPrefs);
536 * AFSD Initialization
539 int afsd_InitCM(char **reasonP)
542 afs_uint64 cacheBlocks;
547 DWORD rx_enable_peer_stats = 0;
548 DWORD rx_enable_process_stats = 0;
553 long virtualCache = 0;
554 char rootCellName[256];
555 struct rx_service *serverp;
556 static struct rx_securityClass *nullServerSecurityClassp;
564 /*int freelanceEnabled;*/
566 lana_number_t lanaNum;
569 int cm_noIPAddr; /* number of client network interfaces */
570 int cm_IPAddr[CM_MAXINTERFACE_ADDR]; /* client's IP address in host order */
571 int cm_SubnetMask[CM_MAXINTERFACE_ADDR];/* client's subnet mask in host order*/
572 int cm_NetMtu[CM_MAXINTERFACE_ADDR]; /* client's MTU sizes */
573 int cm_NetFlags[CM_MAXINTERFACE_ADDR]; /* network flags */
575 WSAStartup(0x0101, &WSAjunk);
577 afsd_initUpperCaseTable();
578 init_et_to_sys_error();
580 /* setup osidebug server at RPC slot 1000 */
581 osi_LongToUID(1000, &debugID);
582 code = osi_InitDebug(&debugID);
583 afsi_log("osi_InitDebug code %d", code);
585 // osi_LockTypeSetDefault("stat"); /* comment this out for speed */
587 if (code == RPC_S_NO_PROTSEQS)
588 *reasonP = "No RPC Protocol Sequences registered. Check HKLM\\SOFTWARE\\Microsoft\\RPC\\ClientProtocols";
590 *reasonP = "unknown error";
595 gethostname(cm_HostName, sizeof(cm_HostName));
596 afsi_log("gethostname %s", cm_HostName);
597 thp = gethostbyname(cm_HostName);
598 memcpy(&cm_HostAddr, thp->h_addr_list[0], 4);
600 /* seed random number generator */
601 srand(ntohl(cm_HostAddr));
603 /* Look up configuration parameters in Registry */
604 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
605 0, KEY_QUERY_VALUE, &parmKey);
606 if (code != ERROR_SUCCESS) {
607 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
608 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
609 NULL, code, 0, (LPTSTR)&msgBuf, 0, NULL);
610 StringCbPrintfA(buf, sizeof(buf),
611 "Failure in configuration while opening Registry: %s",
613 osi_panic(buf, __FILE__, __LINE__);
616 dummyLen = sizeof(maxcpus);
617 code = RegQueryValueEx(parmKey, "MaxCPUs", NULL, NULL,
618 (BYTE *) &maxcpus, &dummyLen);
619 if (code == ERROR_SUCCESS) {
621 DWORD_PTR processAffinityMask, systemAffinityMask;
623 hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION,
624 FALSE, GetCurrentProcessId());
625 if ( hProcess != NULL &&
626 GetProcessAffinityMask(hProcess, &processAffinityMask, &systemAffinityMask) )
629 DWORD_PTR mask, newAffinityMask;
636 for ( i=0, n=0, mask=1, newAffinityMask=0; i<bits && n<maxcpus; i++ ) {
637 if ( processAffinityMask & mask ) {
638 newAffinityMask |= mask;
644 SetProcessAffinityMask(hProcess, newAffinityMask);
645 CloseHandle(hProcess);
646 afsi_log("CPU Restrictions set to %d cpu(s); %d cpu(s) available", maxcpus, n);
648 afsi_log("CPU Restrictions set to %d cpu(s); unable to access process information", maxcpus);
652 dummyLen = sizeof(TraceOption);
653 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
654 (BYTE *) &TraceOption, &dummyLen);
655 afsi_log("Trace Options = %lX", TraceOption);
657 dummyLen = sizeof(traceBufSize);
658 code = RegQueryValueEx(parmKey, "TraceBufferSize", NULL, NULL,
659 (BYTE *) &traceBufSize, &dummyLen);
660 if (code == ERROR_SUCCESS)
661 afsi_log("Trace Buffer size %d", traceBufSize);
663 traceBufSize = CM_CONFIGDEFAULT_TRACEBUFSIZE;
664 afsi_log("Default trace buffer size %d", traceBufSize);
667 /* setup and enable debug log */
668 afsd_logp = osi_LogCreate("afsd", traceBufSize);
669 afsi_log("osi_LogCreate log addr %x", PtrToUlong(afsd_logp));
670 if ((TraceOption & 0x8)
675 osi_LogEnable(afsd_logp);
679 osi_Log0(afsd_logp, "Log init");
681 dummyLen = sizeof(cacheSize);
682 code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
683 (BYTE *) &cacheSize, &dummyLen);
684 if (code == ERROR_SUCCESS)
685 afsi_log("Cache size %d", cacheSize);
687 cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
688 afsi_log("Default cache size %d", cacheSize);
691 dummyLen = sizeof(logChunkSize);
692 code = RegQueryValueEx(parmKey, "ChunkSize", NULL, NULL,
693 (BYTE *) &logChunkSize, &dummyLen);
694 if (code == ERROR_SUCCESS) {
695 if (logChunkSize < 12 || logChunkSize > 30) {
696 afsi_log("Invalid chunk size %d, using default",
698 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
700 afsi_log("Chunk size %d", logChunkSize);
702 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
703 afsi_log("Default chunk size %d", logChunkSize);
705 cm_logChunkSize = logChunkSize;
706 cm_chunkSize = 1 << logChunkSize;
708 dummyLen = sizeof(numBkgD);
709 code = RegQueryValueEx(parmKey, "Daemons", NULL, NULL,
710 (BYTE *) &numBkgD, &dummyLen);
711 if (code == ERROR_SUCCESS)
712 afsi_log("%d background daemons", numBkgD);
714 numBkgD = CM_CONFIGDEFAULT_DAEMONS;
715 afsi_log("Defaulting to %d background daemons", numBkgD);
718 dummyLen = sizeof(numSvThreads);
719 code = RegQueryValueEx(parmKey, "ServerThreads", NULL, NULL,
720 (BYTE *) &numSvThreads, &dummyLen);
721 if (code == ERROR_SUCCESS)
722 afsi_log("%d server threads", numSvThreads);
724 numSvThreads = CM_CONFIGDEFAULT_SVTHREADS;
725 afsi_log("Defaulting to %d server threads", numSvThreads);
728 dummyLen = sizeof(stats);
729 code = RegQueryValueEx(parmKey, "Stats", NULL, NULL,
730 (BYTE *) &stats, &dummyLen);
731 if (code == ERROR_SUCCESS)
732 afsi_log("Status cache size %d", stats);
734 stats = CM_CONFIGDEFAULT_STATS;
735 afsi_log("Default status cache size %d", stats);
738 dummyLen = sizeof(ltt);
739 code = RegQueryValueEx(parmKey, "LogoffTokenTransfer", NULL, NULL,
740 (BYTE *) <t, &dummyLen);
741 if (code != ERROR_SUCCESS)
743 smb_LogoffTokenTransfer = ltt;
744 afsi_log("Logoff token transfer %s", (ltt ? "on" : "off"));
747 dummyLen = sizeof(ltto);
748 code = RegQueryValueEx(parmKey, "LogoffTokenTransferTimeout",
749 NULL, NULL, (BYTE *) <to, &dummyLen);
750 if (code != ERROR_SUCCESS)
755 smb_LogoffTransferTimeout = ltto;
756 afsi_log("Logoff token transfer timeout %d seconds", ltto);
758 dummyLen = sizeof(cm_rootVolumeName);
759 code = RegQueryValueEx(parmKey, "RootVolume", NULL, NULL,
760 cm_rootVolumeName, &dummyLen);
761 if (code == ERROR_SUCCESS)
762 afsi_log("Root volume %s", cm_rootVolumeName);
764 StringCbCopyA(cm_rootVolumeName, sizeof(cm_rootVolumeName), "root.afs");
765 afsi_log("Default root volume name root.afs");
768 cm_mountRootLen = sizeof(cm_mountRoot);
769 code = RegQueryValueEx(parmKey, "MountRoot", NULL, NULL,
770 cm_mountRoot, &cm_mountRootLen);
771 if (code == ERROR_SUCCESS) {
772 afsi_log("Mount root %s", cm_mountRoot);
773 cm_mountRootLen = (DWORD)strlen(cm_mountRoot);
775 StringCbCopyA(cm_mountRoot, sizeof(cm_mountRoot), "/afs");
780 dummyLen = sizeof(buf);
781 code = RegQueryValueEx(parmKey, "CachePath", NULL, ®Type,
783 if (code == ERROR_SUCCESS && buf[0]) {
784 if (regType == REG_EXPAND_SZ) {
785 dummyLen = ExpandEnvironmentStrings(buf, cm_CachePath, sizeof(cm_CachePath));
786 if (dummyLen > sizeof(cm_CachePath)) {
787 afsi_log("Cache path [%s] longer than %d after expanding env strings", buf, sizeof(cm_CachePath));
788 osi_panic("CachePath too long", __FILE__, __LINE__);
791 StringCbCopyA(cm_CachePath, sizeof(cm_CachePath), buf);
793 afsi_log("Cache path %s", cm_CachePath);
795 dummyLen = ExpandEnvironmentStrings("%TEMP%\\AFSCache", cm_CachePath, sizeof(cm_CachePath));
796 if (dummyLen > sizeof(cm_CachePath)) {
797 afsi_log("Cache path [%%TEMP%%\\AFSCache] longer than %d after expanding env strings",
798 sizeof(cm_CachePath));
799 osi_panic("CachePath too long", __FILE__, __LINE__);
801 afsi_log("Default cache path %s", cm_CachePath);
804 dummyLen = sizeof(virtualCache);
805 code = RegQueryValueEx(parmKey, "NonPersistentCaching", NULL, NULL,
806 (LPBYTE)&virtualCache, &dummyLen);
807 afsi_log("Cache type is %s", (virtualCache?"VIRTUAL":"FILE"));
810 dummyLen = sizeof(cm_ValidateCache);
811 code = RegQueryValueEx(parmKey, "ValidateCache", NULL, NULL,
812 (LPBYTE)&cm_ValidateCache, &dummyLen);
813 if ( cm_ValidateCache < 0 || cm_ValidateCache > 2 )
814 cm_ValidateCache = 1;
815 switch (cm_ValidateCache) {
817 afsi_log("Cache Validation disabled");
820 afsi_log("Cache Validation on Startup");
823 afsi_log("Cache Validation on Startup and Shutdown");
828 dummyLen = sizeof(traceOnPanic);
829 code = RegQueryValueEx(parmKey, "TrapOnPanic", NULL, NULL,
830 (BYTE *) &traceOnPanic, &dummyLen);
831 if (code != ERROR_SUCCESS)
832 traceOnPanic = 1; /* log */
833 afsi_log("Set to %s on panic", traceOnPanic ? "trap" : "not trap");
835 dummyLen = sizeof(reportSessionStartups);
836 code = RegQueryValueEx(parmKey, "ReportSessionStartups", NULL, NULL,
837 (BYTE *) &reportSessionStartups, &dummyLen);
838 if (code == ERROR_SUCCESS)
839 afsi_log("Session startups %s be recorded in the Event Log",
840 reportSessionStartups ? "will" : "will not");
842 reportSessionStartups = 0;
846 for ( i=0; i < MAXNUMSYSNAMES; i++ ) {
847 cm_sysNameList[i] = osi_Alloc(MAXSYSNAME);
848 cm_sysNameList[i][0] = '\0';
850 cm_sysName = cm_sysNameList[0];
852 dummyLen = sizeof(buf);
853 code = RegQueryValueEx(parmKey, "SysName", NULL, NULL, buf, &dummyLen);
854 if (code != ERROR_SUCCESS || !buf[0]) {
856 StringCbCopyA(buf, sizeof(buf), "ia64_win64");
857 #elif defined(_AMD64_)
858 StringCbCopyA(buf, sizeof(buf), "amd64_win64 x86_win32 i386_w2k");
859 #else /* assume x86 32-bit */
860 StringCbCopyA(buf, sizeof(buf), "x86_win32 i386_w2k i386_nt40");
863 afsi_log("Sys name %s", buf);
865 /* breakup buf into individual search string entries */
866 for (p = q = buf; p < buf + dummyLen; p++)
868 if (*p == '\0' || isspace(*p)) {
869 memcpy(cm_sysNameList[cm_sysNameCount],q,p-q);
870 cm_sysNameList[cm_sysNameCount][p-q] = '\0';
877 } while (*p == '\0' || isspace(*p));
883 StringCbCopyA(cm_sysName, MAXSYSNAME, cm_sysNameList[0]);
885 dummyLen = sizeof(cryptall);
886 code = RegQueryValueEx(parmKey, "SecurityLevel", NULL, NULL,
887 (BYTE *) &cryptall, &dummyLen);
888 if (code == ERROR_SUCCESS) {
889 afsi_log("SecurityLevel is %s", cryptall?"crypt":"clear");
892 afsi_log("Default SecurityLevel is clear");
896 LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_ON);
898 LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_OFF);
901 dummyLen = sizeof(cm_dnsEnabled);
902 code = RegQueryValueEx(parmKey, "UseDNS", NULL, NULL,
903 (BYTE *) &cm_dnsEnabled, &dummyLen);
904 if (code == ERROR_SUCCESS) {
905 afsi_log("DNS %s be used to find AFS cell servers",
906 cm_dnsEnabled ? "will" : "will not");
909 cm_dnsEnabled = 1; /* default on */
910 afsi_log("Default to use DNS to find AFS cell servers");
912 #else /* AFS_AFSDB_ENV */
913 afsi_log("AFS not built with DNS support to find AFS cell servers");
914 #endif /* AFS_AFSDB_ENV */
916 #ifdef AFS_FREELANCE_CLIENT
917 dummyLen = sizeof(cm_freelanceEnabled);
918 code = RegQueryValueEx(parmKey, "FreelanceClient", NULL, NULL,
919 (BYTE *) &cm_freelanceEnabled, &dummyLen);
920 if (code == ERROR_SUCCESS) {
921 afsi_log("Freelance client feature %s activated",
922 cm_freelanceEnabled ? "is" : "is not");
925 cm_freelanceEnabled = 1; /* default on */
927 #endif /* AFS_FREELANCE_CLIENT */
929 dummyLen = sizeof(smb_hideDotFiles);
930 code = RegQueryValueEx(parmKey, "HideDotFiles", NULL, NULL,
931 (BYTE *) &smb_hideDotFiles, &dummyLen);
932 if (code != ERROR_SUCCESS) {
933 smb_hideDotFiles = 1; /* default on */
935 afsi_log("Dot files/dirs will %sbe marked hidden",
936 smb_hideDotFiles ? "" : "not ");
938 dummyLen = sizeof(smb_maxMpxRequests);
939 code = RegQueryValueEx(parmKey, "MaxMpxRequests", NULL, NULL,
940 (BYTE *) &smb_maxMpxRequests, &dummyLen);
941 if (code != ERROR_SUCCESS) {
942 smb_maxMpxRequests = 50;
944 afsi_log("Maximum number of multiplexed sessions is %d", smb_maxMpxRequests);
946 dummyLen = sizeof(smb_maxVCPerServer);
947 code = RegQueryValueEx(parmKey, "MaxVCPerServer", NULL, NULL,
948 (BYTE *) &smb_maxVCPerServer, &dummyLen);
949 if (code != ERROR_SUCCESS) {
950 smb_maxVCPerServer = 100;
952 afsi_log("Maximum number of VCs per server is %d", smb_maxVCPerServer);
954 dummyLen = sizeof(smb_authType);
955 code = RegQueryValueEx(parmKey, "SMBAuthType", NULL, NULL,
956 (BYTE *) &smb_authType, &dummyLen);
958 if (code != ERROR_SUCCESS ||
959 (smb_authType != SMB_AUTH_EXTENDED && smb_authType != SMB_AUTH_NTLM && smb_authType != SMB_AUTH_NONE)) {
960 smb_authType = SMB_AUTH_EXTENDED; /* default is to use extended authentication */
962 afsi_log("SMB authentication type is %s", ((smb_authType == SMB_AUTH_NONE)?"NONE":((smb_authType == SMB_AUTH_EXTENDED)?"EXTENDED":"NTLM")));
964 dummyLen = sizeof(rx_nojumbo);
965 code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
966 (BYTE *) &rx_nojumbo, &dummyLen);
967 if (code != ERROR_SUCCESS) {
971 afsi_log("RX Jumbograms are disabled");
973 dummyLen = sizeof(rx_mtu);
974 code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
975 (BYTE *) &rx_mtu, &dummyLen);
976 if (code != ERROR_SUCCESS || !rx_mtu) {
980 afsi_log("RX maximum MTU is %d", rx_mtu);
982 dummyLen = sizeof(rx_enable_peer_stats);
983 code = RegQueryValueEx(parmKey, "RxEnablePeerStats", NULL, NULL,
984 (BYTE *) &rx_enable_peer_stats, &dummyLen);
985 if (code != ERROR_SUCCESS) {
986 rx_enable_peer_stats = 0;
988 if (rx_enable_peer_stats)
989 afsi_log("RX Peer Statistics gathering is enabled");
991 dummyLen = sizeof(rx_enable_process_stats);
992 code = RegQueryValueEx(parmKey, "RxEnableProcessStats", NULL, NULL,
993 (BYTE *) &rx_enable_process_stats, &dummyLen);
994 if (code != ERROR_SUCCESS) {
995 rx_enable_process_stats = 0;
997 if (rx_enable_process_stats)
998 afsi_log("RX Process Statistics gathering is enabled");
1000 dummyLen = sizeof(ConnDeadtimeout);
1001 code = RegQueryValueEx(parmKey, "ConnDeadTimeout", NULL, NULL,
1002 (BYTE *) &ConnDeadtimeout, &dummyLen);
1003 afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
1005 dummyLen = sizeof(HardDeadtimeout);
1006 code = RegQueryValueEx(parmKey, "HardDeadTimeout", NULL, NULL,
1007 (BYTE *) &HardDeadtimeout, &dummyLen);
1008 afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
1010 dummyLen = sizeof(DWORD);
1011 code = RegQueryValueEx(parmKey, "daemonCheckDownInterval", NULL, NULL,
1012 (BYTE *) &dwValue, &dummyLen);
1013 if (code == ERROR_SUCCESS)
1014 cm_daemonCheckDownInterval = dwValue;
1015 afsi_log("daemonCheckDownInterval is %d", cm_daemonCheckDownInterval);
1017 dummyLen = sizeof(DWORD);
1018 code = RegQueryValueEx(parmKey, "daemonCheckUpInterval", NULL, NULL,
1019 (BYTE *) &dwValue, &dummyLen);
1020 if (code == ERROR_SUCCESS)
1021 cm_daemonCheckUpInterval = dwValue;
1022 afsi_log("daemonCheckUpInterval is %d", cm_daemonCheckUpInterval);
1024 dummyLen = sizeof(DWORD);
1025 code = RegQueryValueEx(parmKey, "daemonCheckVolInterval", NULL, NULL,
1026 (BYTE *) &dwValue, &dummyLen);
1027 if (code == ERROR_SUCCESS)
1028 cm_daemonCheckVolInterval = dwValue;
1029 afsi_log("daemonCheckVolInterval is %d", cm_daemonCheckVolInterval);
1031 dummyLen = sizeof(DWORD);
1032 code = RegQueryValueEx(parmKey, "daemonCheckCBInterval", NULL, NULL,
1033 (BYTE *) &dwValue, &dummyLen);
1034 if (code == ERROR_SUCCESS)
1035 cm_daemonCheckCBInterval = dwValue;
1036 afsi_log("daemonCheckCBInterval is %d", cm_daemonCheckCBInterval);
1038 dummyLen = sizeof(DWORD);
1039 code = RegQueryValueEx(parmKey, "daemonCheckLockInterval", NULL, NULL,
1040 (BYTE *) &dwValue, &dummyLen);
1041 if (code == ERROR_SUCCESS)
1042 cm_daemonCheckLockInterval = dwValue;
1043 afsi_log("daemonCheckLockInterval is %d", cm_daemonCheckLockInterval);
1045 dummyLen = sizeof(DWORD);
1046 code = RegQueryValueEx(parmKey, "daemonCheckTokenInterval", NULL, NULL,
1047 (BYTE *) &dwValue, &dummyLen);
1048 if (code == ERROR_SUCCESS)
1049 cm_daemonTokenCheckInterval = dwValue;
1050 afsi_log("daemonCheckTokenInterval is %d", cm_daemonTokenCheckInterval);
1052 dummyLen = sizeof(DWORD);
1053 code = RegQueryValueEx(parmKey, "CallBackPort", NULL, NULL,
1054 (BYTE *) &dwValue, &dummyLen);
1055 if (code == ERROR_SUCCESS) {
1056 cm_callbackport = (unsigned short) dwValue;
1058 afsi_log("CM CallBackPort is %u", cm_callbackport);
1060 dummyLen = sizeof(DWORD);
1061 code = RegQueryValueEx(parmKey, "EnableServerLocks", NULL, NULL,
1062 (BYTE *) &dwValue, &dummyLen);
1063 if (code == ERROR_SUCCESS) {
1064 cm_enableServerLocks = (unsigned short) dwValue;
1066 switch (cm_enableServerLocks) {
1068 afsi_log("EnableServerLocks: never");
1071 afsi_log("EnableServerLocks: always");
1075 afsi_log("EnableServerLocks: server requested");
1078 RegCloseKey (parmKey);
1080 /* Call lanahelper to get Netbios name, lan adapter number and gateway flag */
1081 if (SUCCEEDED(code = lana_GetUncServerNameEx(cm_NetbiosName, &lanaNum, &isGateway, LANA_NETBIOS_NAME_FULL))) {
1082 LANadapter = (lanaNum == LANA_INVALID)? -1: lanaNum;
1084 if (LANadapter != -1)
1085 afsi_log("LAN adapter number %d", LANadapter);
1087 afsi_log("LAN adapter number not determined");
1090 afsi_log("Set for gateway service");
1092 afsi_log("Using >%s< as SMB server name", cm_NetbiosName);
1094 /* something went horribly wrong. We can't proceed without a netbios name */
1095 StringCbPrintfA(buf,sizeof(buf),"Netbios name could not be determined: %li", code);
1096 osi_panic(buf, __FILE__, __LINE__);
1099 cacheBlocks = ((afs_uint64)cacheSize * 1024) / CM_CONFIGDEFAULT_BLOCKSIZE;
1101 /* get network related info */
1102 cm_noIPAddr = CM_MAXINTERFACE_ADDR;
1103 code = syscfg_GetIFInfo(&cm_noIPAddr,
1104 cm_IPAddr, cm_SubnetMask,
1105 cm_NetMtu, cm_NetFlags);
1107 if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
1108 afsi_log("syscfg_GetIFInfo error code %d", code);
1110 afsi_log("First Network address %x SubnetMask %x",
1111 cm_IPAddr[0], cm_SubnetMask[0]);
1114 * Save client configuration for GetCacheConfig requests
1116 cm_initParams.nChunkFiles = 0;
1117 cm_initParams.nStatCaches = stats;
1118 cm_initParams.nDataCaches = (afs_uint32)(cacheBlocks > 0xFFFFFFFF ? 0xFFFFFFFF : cacheBlocks);
1119 cm_initParams.nVolumeCaches = stats/2;
1120 cm_initParams.firstChunkSize = cm_chunkSize;
1121 cm_initParams.otherChunkSize = cm_chunkSize;
1122 cm_initParams.cacheSize = cacheSize;
1123 cm_initParams.setTime = 0;
1124 cm_initParams.memCache = 1;
1126 /* Ensure the AFS Netbios Name is registered to allow loopback access */
1127 configureBackConnectionHostNames();
1129 /* init user daemon, and other packages */
1142 code = cm_InitMappedMemory(virtualCache, cm_CachePath, stats, cm_chunkSize, cacheBlocks);
1143 afsi_log("cm_InitMappedMemory code %x", code);
1145 *reasonP = "error initializing cache file";
1149 #ifdef AFS_AFSDB_ENV
1150 #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
1151 if (cm_InitDNS(cm_dnsEnabled) == -1)
1152 cm_dnsEnabled = 0; /* init failed, so deactivate */
1153 afsi_log("cm_InitDNS %d", cm_dnsEnabled);
1157 /* Set RX parameters before initializing RX */
1160 afsi_log("rx_SetNoJumbo successful");
1163 if ( rx_mtu != -1 ) {
1164 rx_SetMaxMTU(rx_mtu);
1165 afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
1168 /* initialize RX, and tell it to listen to the callbackport,
1169 * which is used for callback RPC messages.
1171 code = rx_Init(htons(cm_callbackport));
1172 afsi_log("rx_Init code %x", code);
1174 *reasonP = "afsd: failed to init rx client on port 7001";
1178 /* create an unauthenticated service #1 for callbacks */
1179 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1180 serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
1181 RXAFSCB_ExecuteRequest);
1182 afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1183 if (serverp == NULL) {
1184 *reasonP = "unknown error";
1188 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1189 serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
1190 &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
1191 afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1192 if (serverp == NULL) {
1193 *reasonP = "unknown error";
1197 /* start server threads, *not* donating this one to the pool */
1199 afsi_log("rx_StartServer");
1201 if (rx_enable_peer_stats)
1202 rx_enablePeerRPCStats();
1204 if (rx_enable_process_stats)
1205 rx_enableProcessRPCStats();
1207 code = cm_GetRootCellName(rootCellName);
1208 afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s",
1209 code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
1210 if (code != 0 && !cm_freelanceEnabled)
1212 *reasonP = "can't find root cell name in afsd.ini";
1215 else if (cm_freelanceEnabled)
1216 cm_data.rootCellp = NULL;
1218 if (code == 0 && !cm_freelanceEnabled)
1220 cm_data.rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
1221 afsi_log("cm_GetCell addr %x", PtrToUlong(cm_data.rootCellp));
1222 if (cm_data.rootCellp == NULL)
1224 *reasonP = "can't find root cell in afsdcell.ini";
1229 #ifdef AFS_FREELANCE_CLIENT
1230 if (cm_freelanceEnabled)
1234 /* Initialize the RPC server for session keys */
1238 afsd_InitServerPreferences();
1243 int afsd_InitDaemons(char **reasonP)
1250 /* this should really be in an init daemon from here on down */
1252 if (!cm_freelanceEnabled) {
1253 osi_Log0(afsd_logp, "Loading Root Volume from cell");
1254 code = cm_GetVolumeByName(cm_data.rootCellp, cm_rootVolumeName, cm_rootUserp,
1255 &req, CM_FLAG_CREATE, &cm_data.rootVolumep);
1256 afsi_log("cm_GetVolumeByName code %x root vol %x", code,
1257 (code ? (cm_volume_t *)-1 : cm_data.rootVolumep));
1259 *reasonP = "can't find root volume in root cell";
1264 /* compute the root fid */
1265 if (!cm_freelanceEnabled) {
1266 cm_data.rootFid.cell = cm_data.rootCellp->cellID;
1267 cm_data.rootFid.volume = cm_GetROVolumeID(cm_data.rootVolumep);
1268 cm_data.rootFid.vnode = 1;
1269 cm_data.rootFid.unique = 1;
1272 cm_FakeRootFid(&cm_data.rootFid);
1274 code = cm_GetSCache(&cm_data.rootFid, &cm_data.rootSCachep, cm_rootUserp, &req);
1275 afsi_log("cm_GetSCache code %x scache %x", code,
1276 (code ? (cm_scache_t *)-1 : cm_data.rootSCachep));
1278 *reasonP = "unknown error";
1282 cm_InitDaemon(numBkgD);
1283 afsi_log("cm_InitDaemon complete");
1288 int afsd_InitSMB(char **reasonP, void *aMBfunc)
1295 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1296 0, KEY_QUERY_VALUE, &parmKey);
1297 if (code == ERROR_SUCCESS) {
1298 dummyLen = sizeof(DWORD);
1299 code = RegQueryValueEx(parmKey, "StoreAnsiFilenames", NULL, NULL,
1300 (BYTE *) &dwValue, &dummyLen);
1301 if (code == ERROR_SUCCESS)
1302 smb_StoreAnsiFilenames = dwValue ? 1 : 0;
1303 RegCloseKey (parmKey);
1306 /* Do this last so that we don't handle requests before init is done.
1307 * Here we initialize the SMB listener.
1309 smb_Init(afsd_logp, cm_NetbiosName, smb_UseV3, LANadapter, numSvThreads, aMBfunc);
1310 afsi_log("smb_Init complete");
1323 #pragma pack( push, before_imagehlp, 8 )
1324 #include <imagehlp.h>
1325 #pragma pack( pop, before_imagehlp )
1327 #define MAXNAMELEN 1024
1329 void afsd_printStack(HANDLE hThread, CONTEXT *c)
1332 HANDLE hProcess = GetCurrentProcess();
1334 #if defined(_AMD64_)
1336 #elif defined(_X86_)
1340 char functionName[MAXNAMELEN];
1342 IMAGEHLP_MODULE Module;
1346 IMAGEHLP_SYMBOL *pSym;
1348 afsi_log_useTimestamp = 0;
1350 pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
1352 memset( &s, '\0', sizeof s );
1353 if (!SymInitialize(hProcess, NULL, 1) )
1355 afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
1357 SymCleanup( hProcess );
1363 symOptions = SymGetOptions();
1364 symOptions |= SYMOPT_LOAD_LINES;
1365 symOptions &= ~SYMOPT_UNDNAME;
1366 SymSetOptions( symOptions );
1369 * init STACKFRAME for first call
1370 * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
1371 * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
1372 * and good riddance.
1374 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
1375 #error The STACKFRAME initialization in afsd_printStack() for this platform
1376 #error must be properly configured
1377 #elif defined(_AMD64_)
1378 s.AddrPC.Offset = 0;
1379 s.AddrPC.Mode = AddrModeFlat;
1380 s.AddrFrame.Offset = 0;
1381 s.AddrFrame.Mode = AddrModeFlat;
1383 s.AddrPC.Offset = c->Eip;
1384 s.AddrPC.Mode = AddrModeFlat;
1385 s.AddrFrame.Offset = c->Ebp;
1386 s.AddrFrame.Mode = AddrModeFlat;
1389 memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
1390 pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
1391 pSym->MaxNameLength = MAXNAMELEN;
1393 memset( &Line, '\0', sizeof Line );
1394 Line.SizeOfStruct = sizeof Line;
1396 memset( &Module, '\0', sizeof Module );
1397 Module.SizeOfStruct = sizeof Module;
1401 afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
1403 for ( frameNum = 0; ; ++ frameNum )
1406 * get next stack frame (StackWalk(), SymFunctionTableAccess(),
1407 * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
1408 * ERROR_NOACCESS (998), you can assume that either you are done, or
1409 * that the stack is so hosed that the next deeper frame could not be
1412 if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c,
1413 NULL, SymFunctionTableAccess, SymGetModuleBase,
1417 /* display its contents */
1418 afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
1419 frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
1420 s.AddrPC.Offset, s.AddrReturn.Offset,
1421 s.AddrFrame.Offset, s.AddrStack.Offset );
1423 if ( s.AddrPC.Offset == 0 )
1425 afsi_log("(-nosymbols- PC == 0)" );
1429 /* show procedure info from a valid PC */
1430 if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
1432 if ( GetLastError() != ERROR_INVALID_ADDRESS )
1434 afsi_log("SymGetSymFromAddr(): errno = %lu",
1440 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN,
1442 afsi_log("%s", functionName );
1446 afsi_log(" %+ld bytes", (long) offset);
1450 if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
1452 if (GetLastError() != ERROR_INVALID_ADDRESS)
1454 afsi_log("Error: SymGetLineFromAddr(): errno = %lu",
1460 afsi_log(" Line: %s(%lu) %+ld bytes", Line.FileName,
1461 Line.LineNumber, offset);
1465 /* no return address means no deeper stackframe */
1466 if (s.AddrReturn.Offset == 0)
1473 if (GetLastError() != 0)
1475 afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
1478 SymCleanup(hProcess);
1484 static DWORD *afsd_crtDbgBreakCurrent = NULL;
1485 static DWORD afsd_crtDbgBreaks[256];
1488 static EFaultRepRetVal (WINAPI *pReportFault)(LPEXCEPTION_POINTERS pep, DWORD dwMode) = NULL;
1489 static BOOL (WINAPI *pMiniDumpWriteDump)(HANDLE hProcess,DWORD ProcessId,HANDLE hFile,
1490 MINIDUMP_TYPE DumpType,
1491 PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
1492 PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
1493 PMINIDUMP_CALLBACK_INFORMATION CallbackParam) = NULL;
1502 code = GetEnvironmentVariable("TEMP", wd, sizeof(wd));
1503 if ( code == 0 || code > sizeof(wd) )
1505 if (!GetWindowsDirectory(wd, sizeof(wd)))
1508 StringCbCatA(wd, sizeof(wd), "\\afsd.dmp");
1509 return CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1510 CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
1514 GenerateMiniDump(PEXCEPTION_POINTERS ep)
1518 // Generate exception to get proper context in dump
1521 RaiseException(DBG_CONTINUE, 0, 0, NULL);
1523 __except(GenerateMiniDump(GetExceptionInformation()), EXCEPTION_CONTINUE_EXECUTION)
1529 MINIDUMP_EXCEPTION_INFORMATION eInfo;
1530 HANDLE hFile = NULL;
1531 HMODULE hDbgHelp = NULL;
1533 hDbgHelp = LoadLibrary("Dbghelp.dll");
1534 if ( hDbgHelp == NULL )
1537 (FARPROC) pMiniDumpWriteDump = GetProcAddress(hDbgHelp, "MiniDumpWriteDump");
1538 if ( pMiniDumpWriteDump == NULL ) {
1539 FreeLibrary(hDbgHelp);
1543 hFile = OpenDumpFile();
1550 DWORD dwMiniDumpType = MiniDumpNormal;
1552 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1553 0, KEY_QUERY_VALUE, &parmKey);
1554 if (code == ERROR_SUCCESS) {
1555 dummyLen = sizeof(DWORD);
1556 code = RegQueryValueEx(parmKey, "MiniDumpType", NULL, NULL,
1557 (BYTE *) &dwValue, &dummyLen);
1558 if (code == ERROR_SUCCESS)
1559 dwMiniDumpType = dwValue ? 1 : 0;
1560 RegCloseKey (parmKey);
1563 eInfo.ThreadId = GetCurrentThreadId();
1564 eInfo.ExceptionPointers = ep;
1565 eInfo.ClientPointers = FALSE;
1567 pMiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(),
1568 hFile, dwMiniDumpType, ep ? &eInfo : NULL,
1573 FreeLibrary(hDbgHelp);
1577 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
1581 BOOL allocRequestBrk = FALSE;
1583 HMODULE hLib = NULL;
1585 afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n",
1586 ep->ExceptionRecord->ExceptionCode,
1587 ep->ExceptionRecord->ExceptionAddress);
1590 if (afsd_crtDbgBreakCurrent &&
1591 *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
1593 allocRequestBrk = TRUE;
1594 afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
1598 /* save context if we want to print the stack information */
1599 context = *ep->ContextRecord;
1601 afsd_printStack(GetCurrentThread(), &context);
1603 GenerateMiniDump(ep);
1605 hLib = LoadLibrary("Faultrep.dll");
1607 (FARPROC) pReportFault = GetProcAddress(hLib, "ReportFault");
1609 pReportFault(ep, 0);
1613 if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
1615 afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
1618 if (allocRequestBrk)
1620 afsd_crtDbgBreakCurrent++;
1621 _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
1625 ep->ContextRecord->Eip++;
1627 return EXCEPTION_CONTINUE_EXECUTION;
1631 return EXCEPTION_CONTINUE_SEARCH;
1635 void afsd_SetUnhandledExceptionFilter()
1637 SetUnhandledExceptionFilter(afsd_ExceptionFilter);
1641 void afsd_DbgBreakAllocInit()
1643 memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
1644 afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
1647 void afsd_DbgBreakAdd(DWORD requestNumber)
1650 for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
1652 if (afsd_crtDbgBreaks[i] == -1)
1657 afsd_crtDbgBreaks[i] = requestNumber;
1659 _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);