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>
24 #include <rx\rx_null.h>
26 #include <WINNT/syscfg.h>
30 #include "lanahelper.h"
32 extern int RXAFSCB_ExecuteRequest(struct rx_call *z_call);
33 extern int RXSTATS_ExecuteRequest(struct rx_call *z_call);
35 extern afs_int32 cryptall;
37 char AFSConfigKeyName[] =
38 "SYSTEM\\CurrentControlSet\\Services\\TransarcAFSDaemon\\Parameters";
42 char cm_rootVolumeName[64];
43 DWORD cm_rootVolumeNameLen;
44 cm_volume_t *cm_rootVolumep = NULL;
45 cm_cell_t *cm_rootCellp = NULL;
47 cm_scache_t *cm_rootSCachep;
48 char cm_mountRoot[1024];
49 DWORD cm_mountRootLen;
52 #ifdef AFS_FREELANCE_CLIENT
54 #endif /* freelance */
67 char cm_HostName[200];
70 char cm_NetbiosName[MAX_NB_NAME_LENGTH];
72 char cm_CachePath[200];
73 DWORD cm_CachePathLen;
75 BOOL isGateway = FALSE;
77 BOOL reportSessionStartups = FALSE;
79 cm_initparams_v1 cm_initParams;
82 * AFSD Initialization Log
84 * This is distinct from the regular debug logging facility.
85 * Log items go directly to a file, not to an array in memory, so that even
86 * if AFSD crashes, the log can be inspected.
92 int cm_dnsEnabled = 1;
95 char cm_NetBiosName[32];
101 char t[100], u[100], *p, *path;
105 afsi_file = INVALID_HANDLE_VALUE;
108 strcpy(wd, getenv("TEMP"));
112 code = GetWindowsDirectory(wd, sizeof(wd));
113 if (code == 0) return;
115 strcat(wd, "\\afsd_init.log");
116 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
117 afsi_file = CreateFile(wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
118 OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
119 SetFilePointer(afsi_file, 0, NULL, FILE_END);
120 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, u, sizeof(u));
121 strcat(t, ": Create log file\n");
122 strcat(u, ": Created log file\n");
123 WriteFile(afsi_file, t, strlen(t), &zilch, NULL);
124 WriteFile(afsi_file, u, strlen(u), &zilch, NULL);
126 path = getenv("PATH");
127 WriteFile(afsi_file, p, strlen(p), &zilch, NULL);
128 WriteFile(afsi_file, path, strlen(path), &zilch, NULL);
129 WriteFile(afsi_file, "\n", 1, &zilch, NULL);
132 static int afsi_log_useTimestamp = 1;
135 afsi_log(char *pattern, ...)
137 char s[100], t[100], d[100], u[300];
140 va_start(ap, pattern);
142 vsprintf(s, pattern, ap);
143 if ( afsi_log_useTimestamp ) {
144 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
145 GetDateFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, d, sizeof(d));
146 sprintf(u, "%s %s: %s\n", d, t, s);
147 if (afsi_file != INVALID_HANDLE_VALUE)
148 WriteFile(afsi_file, u, strlen(u), &zilch, NULL);
153 if (afsi_file != INVALID_HANDLE_VALUE)
154 WriteFile(afsi_file, s, strlen(s), &zilch, NULL);
159 * Standard AFSD trace
162 void afsd_ForceTrace(BOOL flush)
171 len = GetTempPath(sizeof(buf)-10, buf);
172 strcpy(&buf[len], "/afsd.log");
173 handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
174 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
175 if (handle == INVALID_HANDLE_VALUE) {
177 osi_panic("Cannot create log file", __FILE__, __LINE__);
179 osi_LogPrint(afsd_logp, handle);
181 FlushFileBuffers(handle);
186 * AFSD Initialization
189 int afsd_InitCM(char **reasonP)
198 long rx_mtu, rx_nojumbo;
199 char rootCellName[256];
200 struct rx_service *serverp;
201 static struct rx_securityClass *nullServerSecurityClassp;
208 /*int freelanceEnabled;*/
210 lana_number_t lanaNum;
212 WSAStartup(0x0101, &WSAjunk);
214 /* setup osidebug server at RPC slot 1000 */
215 osi_LongToUID(1000, &debugID);
216 code = osi_InitDebug(&debugID);
217 afsi_log("osi_InitDebug code %d", code);
219 // osi_LockTypeSetDefault("stat"); /* comment this out for speed *
221 *reasonP = "unknown error";
226 gethostname(cm_HostName, sizeof(cm_HostName));
227 afsi_log("gethostname %s", cm_HostName);
228 thp = gethostbyname(cm_HostName);
229 memcpy(&cm_HostAddr, thp->h_addr_list[0], 4);
231 /* seed random number generator */
232 srand(ntohl(cm_HostAddr));
234 /* Look up configuration parameters in Registry */
235 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSConfigKeyName,
236 0, KEY_QUERY_VALUE, &parmKey);
237 if (code != ERROR_SUCCESS) {
238 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
239 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
240 NULL, code, 0, (LPTSTR)&msgBuf, 0, NULL);
242 "Failure in configuration while opening Registry: %s",
244 osi_panic(buf, __FILE__, __LINE__);
247 dummyLen = sizeof(traceBufSize);
248 code = RegQueryValueEx(parmKey, "TraceBufferSize", NULL, NULL,
249 (BYTE *) &traceBufSize, &dummyLen);
250 if (code == ERROR_SUCCESS)
251 afsi_log("Trace Buffer size %d", traceBufSize);
253 traceBufSize = CM_CONFIGDEFAULT_TRACEBUFSIZE;
254 afsi_log("Default trace buffer size %d", traceBufSize);
257 /* setup and enable debug log */
258 afsd_logp = osi_LogCreate("afsd", traceBufSize);
259 afsi_log("osi_LogCreate log addr %x", (int)afsd_logp);
260 osi_LogEnable(afsd_logp);
263 osi_Log0(afsd_logp, "Log init");
265 dummyLen = sizeof(cacheSize);
266 code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
267 (BYTE *) &cacheSize, &dummyLen);
268 if (code == ERROR_SUCCESS)
269 afsi_log("Cache size %d", cacheSize);
271 cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
272 afsi_log("Default cache size %d", cacheSize);
275 dummyLen = sizeof(logChunkSize);
276 code = RegQueryValueEx(parmKey, "ChunkSize", NULL, NULL,
277 (BYTE *) &logChunkSize, &dummyLen);
278 if (code == ERROR_SUCCESS) {
279 if (logChunkSize < 12 || logChunkSize > 30) {
280 afsi_log("Invalid chunk size %d, using default",
282 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
284 afsi_log("Chunk size %d", logChunkSize);
286 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
287 afsi_log("Default chunk size %d", logChunkSize);
289 cm_logChunkSize = logChunkSize;
290 cm_chunkSize = 1 << logChunkSize;
292 dummyLen = sizeof(numBkgD);
293 code = RegQueryValueEx(parmKey, "Daemons", NULL, NULL,
294 (BYTE *) &numBkgD, &dummyLen);
295 if (code == ERROR_SUCCESS)
296 afsi_log("%d background daemons", numBkgD);
298 numBkgD = CM_CONFIGDEFAULT_DAEMONS;
299 afsi_log("Defaulting to %d background daemons", numBkgD);
302 dummyLen = sizeof(numSvThreads);
303 code = RegQueryValueEx(parmKey, "ServerThreads", NULL, NULL,
304 (BYTE *) &numSvThreads, &dummyLen);
305 if (code == ERROR_SUCCESS)
306 afsi_log("%d server threads", numSvThreads);
308 numSvThreads = CM_CONFIGDEFAULT_SVTHREADS;
309 afsi_log("Defaulting to %d server threads", numSvThreads);
312 dummyLen = sizeof(stats);
313 code = RegQueryValueEx(parmKey, "Stats", NULL, NULL,
314 (BYTE *) &stats, &dummyLen);
315 if (code == ERROR_SUCCESS)
316 afsi_log("Status cache size %d", stats);
318 stats = CM_CONFIGDEFAULT_STATS;
319 afsi_log("Default status cache size %d", stats);
322 dummyLen = sizeof(ltt);
323 code = RegQueryValueEx(parmKey, "LogoffTokenTransfer", NULL, NULL,
324 (BYTE *) <t, &dummyLen);
325 if (code == ERROR_SUCCESS)
326 afsi_log("Logoff token transfer %s", (ltt ? "on" : "off"));
329 afsi_log("Logoff token transfer on by default");
331 smb_LogoffTokenTransfer = ltt;
334 dummyLen = sizeof(ltto);
335 code = RegQueryValueEx(parmKey, "LogoffTokenTransferTimeout",
336 NULL, NULL, (BYTE *) <to, &dummyLen);
337 if (code == ERROR_SUCCESS)
338 afsi_log("Logoff token tranfer timeout %d seconds",
342 afsi_log("Default logoff token transfer timeout 10 seconds");
345 smb_LogoffTransferTimeout = ltto;
347 dummyLen = sizeof(cm_rootVolumeName);
348 code = RegQueryValueEx(parmKey, "RootVolume", NULL, NULL,
349 cm_rootVolumeName, &dummyLen);
350 if (code == ERROR_SUCCESS)
351 afsi_log("Root volume %s", cm_rootVolumeName);
353 strcpy(cm_rootVolumeName, "root.afs");
354 afsi_log("Default root volume name root.afs");
357 cm_mountRootLen = sizeof(cm_mountRoot);
358 code = RegQueryValueEx(parmKey, "Mountroot", NULL, NULL,
359 cm_mountRoot, &cm_mountRootLen);
360 if (code == ERROR_SUCCESS) {
361 afsi_log("Mount root %s", cm_mountRoot);
362 cm_mountRootLen = strlen(cm_mountRoot);
364 strcpy(cm_mountRoot, "/afs");
369 dummyLen = sizeof(cm_CachePath);
370 code = RegQueryValueEx(parmKey, "CachePath", NULL, NULL,
371 cm_CachePath, &dummyLen);
372 if (code == ERROR_SUCCESS)
373 afsi_log("Cache path %s", cm_CachePath);
375 GetWindowsDirectory(cm_CachePath, sizeof(cm_CachePath));
376 cm_CachePath[2] = 0; /* get drive letter only */
377 strcat(cm_CachePath, "\\AFSCache");
378 afsi_log("Default cache path %s", cm_CachePath);
381 dummyLen = sizeof(traceOnPanic);
382 code = RegQueryValueEx(parmKey, "TrapOnPanic", NULL, NULL,
383 (BYTE *) &traceOnPanic, &dummyLen);
384 if (code == ERROR_SUCCESS)
385 afsi_log("Set to %s on panic",
386 traceOnPanic ? "trap" : "not trap");
392 dummyLen = sizeof(reportSessionStartups);
393 code = RegQueryValueEx(parmKey, "ReportSessionStartups", NULL, NULL,
394 (BYTE *) &reportSessionStartups, &dummyLen);
395 if (code == ERROR_SUCCESS)
396 afsi_log("Session startups %s be recorded in the Event Log",
397 reportSessionStartups ? "will" : "will not");
399 reportSessionStartups = 0;
403 dummyLen = sizeof(cm_sysName);
404 code = RegQueryValueEx(parmKey, "SysName", NULL, NULL,
405 cm_sysName, &dummyLen);
406 if (code == ERROR_SUCCESS)
407 afsi_log("Sys name %s", cm_sysName);
409 strcat(cm_sysName, "i386_nt40");
410 afsi_log("Default sys name %s", cm_sysName);
413 dummyLen = sizeof(cryptall);
414 code = RegQueryValueEx(parmKey, "SecurityLevel", NULL, NULL,
415 (BYTE *) &cryptall, &dummyLen);
416 if (code == ERROR_SUCCESS)
417 afsi_log("SecurityLevel is %s", cryptall?"crypt":"clear");
419 cryptall = rxkad_clear;
420 afsi_log("Default SecurityLevel is clear");
424 dummyLen = sizeof(cm_dnsEnabled);
425 code = RegQueryValueEx(parmKey, "UseDNS", NULL, NULL,
426 (BYTE *) &cm_dnsEnabled, &dummyLen);
427 if (code == ERROR_SUCCESS) {
428 afsi_log("DNS %s be used to find AFS cell servers",
429 cm_dnsEnabled ? "will" : "will not");
432 cm_dnsEnabled = 1; /* default on */
433 afsi_log("Default to use DNS to find AFS cell servers");
435 #else /* AFS_AFSDB_ENV */
436 afsi_log("AFS not built with DNS support to find AFS cell servers");
437 #endif /* AFS_AFSDB_ENV */
439 #ifdef AFS_FREELANCE_CLIENT
440 dummyLen = sizeof(cm_freelanceEnabled);
441 code = RegQueryValueEx(parmKey, "FreelanceClient", NULL, NULL,
442 (BYTE *) &cm_freelanceEnabled, &dummyLen);
443 if (code == ERROR_SUCCESS) {
444 afsi_log("Freelance client feature %s activated",
445 cm_freelanceEnabled ? "is" : "is not");
448 cm_freelanceEnabled = 0; /* default off */
450 #endif /* AFS_FREELANCE_CLIENT */
452 dummyLen = sizeof(buf);
453 code = RegQueryValueEx(parmKey, "NetbiosName", NULL, NULL,
454 (BYTE *) &buf, &dummyLen);
455 if (code == ERROR_SUCCESS) {
456 DWORD len = ExpandEnvironmentStrings(buf, cm_NetBiosName, MAX_NB_NAME_LENGTH);
457 if ( len > 0 && len <= MAX_NB_NAME_LENGTH ) {
458 afsi_log("Explicit NetBios name is used %s", cm_NetBiosName);
460 afsi_log("Unable to Expand Explicit NetBios name: %s", buf);
461 cm_NetBiosName[0] = 0; /* turn it off */
465 cm_NetBiosName[0] = 0; /* default off */
468 dummyLen = sizeof(smb_hideDotFiles);
469 code = RegQueryValueEx(parmKey, "HideDotFiles", NULL, NULL,
470 (BYTE *) &smb_hideDotFiles, &dummyLen);
471 if (code != ERROR_SUCCESS) {
472 smb_hideDotFiles = 1; /* default on */
474 afsi_log("Dot files/dirs will %sbe marked hidden",
475 smb_hideDotFiles ? "" : "not ");
477 dummyLen = sizeof(smb_maxMpxRequests);
478 code = RegQueryValueEx(parmKey, "MaxMpxRequests", NULL, NULL,
479 (BYTE *) &smb_maxMpxRequests, &dummyLen);
480 if (code != ERROR_SUCCESS) {
481 smb_maxMpxRequests = 50;
483 afsi_log("Maximum number of multiplexed sessions is %d", smb_maxMpxRequests);
485 dummyLen = sizeof(smb_maxVCPerServer);
486 code = RegQueryValueEx(parmKey, "MaxVCPerServer", NULL, NULL,
487 (BYTE *) &smb_maxVCPerServer, &dummyLen);
488 if (code != ERROR_SUCCESS) {
489 smb_maxVCPerServer = 100;
491 afsi_log("Maximum number of VCs per server is %d", smb_maxVCPerServer);
493 dummyLen = sizeof(rx_nojumbo);
494 code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
495 (BYTE *) &rx_nojumbo, &dummyLen);
496 if (code != ERROR_SUCCESS) {
500 afsi_log("RX Jumbograms are disabled");
502 dummyLen = sizeof(rx_mtu);
503 code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
504 (BYTE *) &rx_mtu, &dummyLen);
505 if (code != ERROR_SUCCESS || !rx_mtu) {
509 afsi_log("RX maximum MTU is %d", rx_mtu);
511 RegCloseKey (parmKey);
513 /* Call lanahelper to get Netbios name, lan adapter number and gateway flag */
514 if(SUCCEEDED(code = lana_GetUncServerNameEx(cm_NetbiosName, &lanaNum, &isGateway, LANA_NETBIOS_NAME_FULL))) {
515 LANadapter = (lanaNum == LANA_INVALID)? -1: lanaNum;
518 afsi_log("LAN adapter number %d", LANadapter);
520 afsi_log("LAN adapter number not determined");
523 afsi_log("Set for gateway service");
525 afsi_log("Using >%s< as SMB server name", cm_NetbiosName);
527 /* something went horribly wrong. We can't proceed without a netbios name */
528 sprintf(buf,"Netbios name could not be determined: %li", code);
529 osi_panic(buf, __FILE__, __LINE__);
532 /* setup early variables */
533 /* These both used to be configurable. */
535 buf_bufferSize = CM_CONFIGDEFAULT_BLOCKSIZE;
537 /* turn from 1024 byte units into memory blocks */
538 cacheBlocks = (cacheSize * 1024) / buf_bufferSize;
540 /* get network related info */
541 cm_noIPAddr = CM_MAXINTERFACE_ADDR;
542 code = syscfg_GetIFInfo(&cm_noIPAddr,
543 cm_IPAddr, cm_SubnetMask,
544 cm_NetMtu, cm_NetFlags);
546 if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
547 afsi_log("syscfg_GetIFInfo error code %d", code);
549 afsi_log("First Network address %x SubnetMask %x",
550 cm_IPAddr[0], cm_SubnetMask[0]);
553 * Save client configuration for GetCacheConfig requests
555 cm_initParams.nChunkFiles = 0;
556 cm_initParams.nStatCaches = stats;
557 cm_initParams.nDataCaches = 0;
558 cm_initParams.nVolumeCaches = 0;
559 cm_initParams.firstChunkSize = cm_chunkSize;
560 cm_initParams.otherChunkSize = cm_chunkSize;
561 cm_initParams.cacheSize = cacheSize;
562 cm_initParams.setTime = 0;
563 cm_initParams.memCache = 0;
565 /* Set RX parameters before initializing RX */
568 afsi_log("rx_SetNoJumbo successful");
571 if ( rx_mtu != -1 ) {
572 rx_SetMaxMTU(rx_mtu);
573 afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
576 /* Open Microsoft Firewall to allow in port 7001 */
580 TCHAR* value = TEXT("7001:UDP:*:Enabled:AFS Cache Manager Callback");
581 if (RegCreateKeyEx (HKEY_LOCAL_MACHINE,
582 "SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\DomainProfile\\GloballyOpenP",
583 0, TEXT("container"), 0, KEY_SET_VALUE, NULL, &hk, &dwDisp) == ERROR_SUCCESS)
585 RegSetValueEx (hk, TEXT("7001:UDP"), 0, REG_SZ, (PBYTE)value, sizeof(TCHAR) * (1+lstrlen(value)));
588 if (RegCreateKeyEx (HKEY_LOCAL_MACHINE,
589 "SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\StandardProfile\\GloballyOpenP",
590 0, TEXT("container"), 0, KEY_SET_VALUE, NULL, &hk, &dwDisp) == ERROR_SUCCESS)
592 RegSetValueEx (hk, TEXT("7001:UDP"), 0, REG_SZ, (PBYTE)value, sizeof(TCHAR) * (1+lstrlen(value)));
597 /* initialize RX, and tell it to listen to port 7001, which is used for
598 * callback RPC messages.
600 code = rx_Init(htons(7001));
601 afsi_log("rx_Init code %x", code);
603 *reasonP = "afsd: failed to init rx client on port 7001";
607 /* Initialize the RPC server for session keys */
610 /* create an unauthenticated service #1 for callbacks */
611 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
612 serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
613 RXAFSCB_ExecuteRequest);
614 afsi_log("rx_NewService addr %x", (int)serverp);
615 if (serverp == NULL) {
616 *reasonP = "unknown error";
620 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
621 serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
622 &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
623 afsi_log("rx_NewService addr %x", (int)serverp);
624 if (serverp == NULL) {
625 *reasonP = "unknown error";
629 /* start server threads, *not* donating this one to the pool */
631 afsi_log("rx_StartServer");
633 /* init user daemon, and other packages */
636 cm_InitACLCache(2*stats);
652 cm_InitSCache(stats);
654 code = cm_InitDCache(0, cacheBlocks);
655 afsi_log("cm_InitDCache code %x", code);
657 *reasonP = "error initializing cache";
662 #if !defined(_WIN32_WINNT) || _WIN32_WINNT < 0x500
663 if (cm_InitDNS(cm_dnsEnabled) == -1)
664 cm_dnsEnabled = 0; /* init failed, so deactivate */
665 afsi_log("cm_InitDNS %d", cm_dnsEnabled);
669 code = cm_GetRootCellName(rootCellName);
670 afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s",
671 code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
672 if (code != 0 && !cm_freelanceEnabled)
674 *reasonP = "can't find root cell name in afsd.ini";
677 else if (cm_freelanceEnabled)
680 if (code == 0 && !cm_freelanceEnabled)
682 cm_rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
683 afsi_log("cm_GetCell addr %x", (int)cm_rootCellp);
684 if (cm_rootCellp == NULL)
686 *reasonP = "can't find root cell in afsdcell.ini";
691 #ifdef AFS_FREELANCE_CLIENT
692 if (cm_freelanceEnabled)
699 int afsd_InitDaemons(char **reasonP)
706 /* this should really be in an init daemon from here on down */
708 if (!cm_freelanceEnabled) {
709 code = cm_GetVolumeByName(cm_rootCellp, cm_rootVolumeName, cm_rootUserp,
710 &req, CM_FLAG_CREATE, &cm_rootVolumep);
711 afsi_log("cm_GetVolumeByName code %x root vol %x", code,
712 (code ? (cm_volume_t *)-1 : cm_rootVolumep));
714 *reasonP = "can't find root volume in root cell";
719 /* compute the root fid */
720 if (!cm_freelanceEnabled) {
721 cm_rootFid.cell = cm_rootCellp->cellID;
722 cm_rootFid.volume = cm_GetROVolumeID(cm_rootVolumep);
723 cm_rootFid.vnode = 1;
724 cm_rootFid.unique = 1;
727 cm_FakeRootFid(&cm_rootFid);
729 code = cm_GetSCache(&cm_rootFid, &cm_rootSCachep, cm_rootUserp, &req);
730 afsi_log("cm_GetSCache code %x scache %x", code,
731 (code ? (cm_scache_t *)-1 : cm_rootSCachep));
733 *reasonP = "unknown error";
737 cm_InitDaemon(numBkgD);
738 afsi_log("cm_InitDaemon");
743 int afsd_InitSMB(char **reasonP, void *aMBfunc)
745 /* Do this last so that we don't handle requests before init is done.
746 * Here we initialize the SMB listener.
748 smb_Init(afsd_logp, cm_NetbiosName, smb_UseV3, LANadapter, numSvThreads, aMBfunc);
749 afsi_log("smb_Init");
762 #pragma pack( push, before_imagehlp, 8 )
763 #include <imagehlp.h>
764 #pragma pack( pop, before_imagehlp )
766 #define MAXNAMELEN 1024
768 void afsd_printStack(HANDLE hThread, CONTEXT *c)
770 HANDLE hProcess = GetCurrentProcess();
774 char functionName[MAXNAMELEN];
776 IMAGEHLP_MODULE Module;
780 IMAGEHLP_SYMBOL *pSym;
782 afsi_log_useTimestamp = 0;
784 pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
786 memset( &s, '\0', sizeof s );
787 if (!SymInitialize(hProcess, NULL, 1) )
789 afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
791 SymCleanup( hProcess );
797 symOptions = SymGetOptions();
798 symOptions |= SYMOPT_LOAD_LINES;
799 symOptions &= ~SYMOPT_UNDNAME;
800 SymSetOptions( symOptions );
803 * init STACKFRAME for first call
804 * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
805 * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
808 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
809 #error The STACKFRAME initialization in afsd_printStack() for this platform
810 #error must be properly configured
812 s.AddrPC.Offset = c->Eip;
813 s.AddrPC.Mode = AddrModeFlat;
814 s.AddrFrame.Offset = c->Ebp;
815 s.AddrFrame.Mode = AddrModeFlat;
818 memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
819 pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
820 pSym->MaxNameLength = MAXNAMELEN;
822 memset( &Line, '\0', sizeof Line );
823 Line.SizeOfStruct = sizeof Line;
825 memset( &Module, '\0', sizeof Module );
826 Module.SizeOfStruct = sizeof Module;
830 afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
832 for ( frameNum = 0; ; ++ frameNum )
835 * get next stack frame (StackWalk(), SymFunctionTableAccess(),
836 * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
837 * ERROR_NOACCESS (998), you can assume that either you are done, or
838 * that the stack is so hosed that the next deeper frame could not be
841 if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c,
842 NULL, SymFunctionTableAccess, SymGetModuleBase,
846 /* display its contents */
847 afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
848 frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
849 s.AddrPC.Offset, s.AddrReturn.Offset,
850 s.AddrFrame.Offset, s.AddrStack.Offset );
852 if ( s.AddrPC.Offset == 0 )
854 afsi_log("(-nosymbols- PC == 0)" );
858 /* show procedure info from a valid PC */
859 if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
861 if ( GetLastError() != ERROR_INVALID_ADDRESS )
863 afsi_log("SymGetSymFromAddr(): errno = %lu",
869 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN,
871 afsi_log("%s", functionName );
875 afsi_log(" %+ld bytes", (long) offset);
879 if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
881 if (GetLastError() != ERROR_INVALID_ADDRESS)
883 afsi_log("Error: SymGetLineFromAddr(): errno = %lu",
889 afsi_log(" Line: %s(%lu) %+ld bytes", Line.FileName,
890 Line.LineNumber, offset);
894 /* no return address means no deeper stackframe */
895 if (s.AddrReturn.Offset == 0)
902 if (GetLastError() != 0)
904 afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
907 SymCleanup(hProcess);
912 static DWORD *afsd_crtDbgBreakCurrent = NULL;
913 static DWORD afsd_crtDbgBreaks[256];
916 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
920 BOOL allocRequestBrk = FALSE;
923 afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n",
924 ep->ExceptionRecord->ExceptionCode,
925 ep->ExceptionRecord->ExceptionAddress);
928 if (afsd_crtDbgBreakCurrent &&
929 *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
931 allocRequestBrk = TRUE;
932 afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
936 /* save context if we want to print the stack information */
937 context = *ep->ContextRecord;
939 afsd_printStack(GetCurrentThread(), &context);
941 if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
943 afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
948 afsd_crtDbgBreakCurrent++;
949 _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
953 ep->ContextRecord->Eip++;
954 return EXCEPTION_CONTINUE_EXECUTION;
958 return EXCEPTION_CONTINUE_SEARCH;
962 void afsd_SetUnhandledExceptionFilter()
964 SetUnhandledExceptionFilter(afsd_ExceptionFilter);
968 void afsd_DbgBreakAllocInit()
970 memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
971 afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
974 void afsd_DbgBreakAdd(DWORD requestNumber)
977 for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
979 if (afsd_crtDbgBreaks[i] == -1)
984 afsd_crtDbgBreaks[i] = requestNumber;
986 _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);