ae625b85e8ea1c2fe8b4821df8785186305019db
[openafs.git] / src / WINNT / afsd / afsd_init.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
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
8  */
9
10 #include <afs/param.h>
11 #include <afs/stds.h>
12 #include <afs/afs_args.h>
13
14 #include <windows.h>
15 #include <string.h>
16 #include <nb30.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <locale.h>
20 #include <mbctype.h>
21 #include <winsock2.h>
22
23 #include <osi.h>
24 #include "afsd.h"
25 #include <rx\rx.h>
26 #include <rx\rx_null.h>
27 #include <WINNT/syscfg.h>
28
29 #include "smb.h"
30 #include "cm_rpc.h"
31 #include "lanahelper.h"
32 #include <strsafe.h>
33 #include "afsicf.h"
34
35 extern int RXAFSCB_ExecuteRequest(struct rx_call *z_call);
36 extern int RXSTATS_ExecuteRequest(struct rx_call *z_call);
37
38 extern afs_int32 cryptall;
39
40 char AFSConfigKeyName[] =
41         "SYSTEM\\CurrentControlSet\\Services\\TransarcAFSDaemon\\Parameters";
42 char OpenAFSConfigKeyName[] =
43         "SOFTWARE\\OpenAFS\\Client";
44
45 osi_log_t *afsd_logp;
46
47 char cm_rootVolumeName[64];
48 DWORD cm_rootVolumeNameLen;
49 cm_volume_t *cm_rootVolumep = NULL;
50 cm_cell_t *cm_rootCellp = NULL;
51 cm_fid_t cm_rootFid;
52 cm_scache_t *cm_rootSCachep = NULL;
53 char cm_mountRoot[1024];
54 DWORD cm_mountRootLen;
55 int cm_logChunkSize;
56 int cm_chunkSize;
57 #ifdef AFS_FREELANCE_CLIENT
58 char *cm_FakeRootDir;
59 #endif /* freelance */
60
61 int smb_UseV3;
62
63 int LANadapter;
64
65 int numBkgD;
66 int numSvThreads;
67
68 int traceOnPanic = 0;
69
70 int logReady = 0;
71
72 char cm_HostName[200];
73 long cm_HostAddr;
74
75 char cm_NetbiosName[MAX_NB_NAME_LENGTH] = "";
76
77 char cm_CachePath[MAX_PATH];
78 DWORD cm_CachePathLen;
79
80 BOOL isGateway = FALSE;
81
82 BOOL reportSessionStartups = FALSE;
83
84 cm_initparams_v1 cm_initParams;
85
86 char *cm_sysName = 0;
87 unsigned int   cm_sysNameCount = 0;
88 char *cm_sysNameList[MAXNUMSYSNAMES];
89
90 DWORD TraceOption = 0;
91
92 /*
93  * AFSD Initialization Log
94  *
95  * This is distinct from the regular debug logging facility.
96  * Log items go directly to a file, not to an array in memory, so that even
97  * if AFSD crashes, the log can be inspected.
98  */
99
100 HANDLE afsi_file;
101
102 #ifdef AFS_AFSDB_ENV
103 int cm_dnsEnabled = 1;
104 #endif
105
106
107 static int afsi_log_useTimestamp = 1;
108
109 void
110 afsi_log(char *pattern, ...)
111 {
112     char s[256], t[100], d[100], u[512];
113     DWORD zilch;
114     va_list ap;
115     va_start(ap, pattern);
116
117     StringCbVPrintfA(s, sizeof(s), pattern, ap);
118     if ( afsi_log_useTimestamp ) {
119         GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
120         GetDateFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, d, sizeof(d));
121         StringCbPrintfA(u, sizeof(u), "%s %s: %s\n", d, t, s);
122         if (afsi_file != INVALID_HANDLE_VALUE)
123             WriteFile(afsi_file, u, strlen(u), &zilch, NULL);
124 #ifdef NOTSERVICE
125         printf("%s", u);
126 #endif 
127     } else {
128         if (afsi_file != INVALID_HANDLE_VALUE)
129             WriteFile(afsi_file, s, strlen(s), &zilch, NULL);
130     }
131 }
132
133 extern initUpperCaseTable();
134 void afsd_initUpperCaseTable() 
135 {
136     initUpperCaseTable();
137 }
138
139 void
140 afsi_start()
141 {
142     char wd[100];
143     char t[100], u[100], *p, *path;
144     int zilch;
145     int code;
146     DWORD dwLow, dwHigh;
147     HKEY parmKey;
148     DWORD dummyLen;
149     DWORD maxLogSize = 100 * 1024;
150
151     afsi_file = INVALID_HANDLE_VALUE;
152     if (getenv("TEMP"))
153     {
154         StringCbCopyA(wd, sizeof(wd), getenv("TEMP"));
155     }
156     else
157     {
158         code = GetWindowsDirectory(wd, sizeof(wd));
159         if (code == 0) 
160             return;
161     }
162     StringCbCatA(wd, sizeof(wd), "\\afsd_init.log");
163     GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
164     afsi_file = CreateFile(wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
165                            OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
166
167     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSConfigKeyName,
168                          0, KEY_QUERY_VALUE, &parmKey);
169     if (code == ERROR_SUCCESS) {
170         dummyLen = sizeof(maxLogSize);
171         code = RegQueryValueEx(parmKey, "MaxLogSize", NULL, NULL,
172                                 (BYTE *) &maxLogSize, &dummyLen);
173         RegCloseKey (parmKey);
174     }
175
176     if (maxLogSize) {
177         dwLow = GetFileSize( afsi_file, &dwHigh );
178         if ( dwHigh > 0 || dwLow >= maxLogSize ) {
179             CloseHandle(afsi_file);
180             afsi_file = CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
181                                     CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
182         }
183     }
184
185     SetFilePointer(afsi_file, 0, NULL, FILE_END);
186     GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, u, sizeof(u));
187     StringCbCatA(t, sizeof(t), ": Create log file\n");
188     StringCbCatA(u, sizeof(u), ": Created log file\n");
189     WriteFile(afsi_file, t, strlen(t), &zilch, NULL);
190     WriteFile(afsi_file, u, strlen(u), &zilch, NULL);
191     p = "PATH=";
192     path = getenv("PATH");
193     WriteFile(afsi_file, p, strlen(p), &zilch, NULL);
194     WriteFile(afsi_file, path, strlen(path), &zilch, NULL);
195     WriteFile(afsi_file, "\n", 1, &zilch, NULL);
196
197     /* Initialize C RTL Code Page conversion functions */
198     /* All of the path info obtained from the SMB client is in the OEM code page */
199     afsi_log("OEM Code Page = %d", GetOEMCP());
200     afsi_log("locale =  %s", setlocale(LC_ALL,NULL));
201 #ifdef COMMENT
202     /* Two things to look into.  First, should mbstowcs() be performing 
203      * character set translations from OEM to Unicode in smb3.c; 
204      * Second, do we need to set this translation in each function 
205      * due to multi-threading. 
206      */
207     afsi_log("locale -> %s", setlocale(LC_ALL, ".OCP"));
208     afsi_log("_setmbcp = %d -> %d", _setmbcp(_MB_CP_OEM), _getmbcp());
209 #endif /* COMMENT */
210 }
211
212 /*
213  * Standard AFSD trace
214  */
215
216 void afsd_ForceTrace(BOOL flush)
217 {
218     HANDLE handle;
219     int len;
220     char buf[256];
221
222     if (!logReady) 
223         return;
224
225     len = GetTempPath(sizeof(buf)-10, buf);
226     StringCbCopyA(&buf[len], sizeof(buf)-len, "/afsd.log");
227     handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
228                          NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
229     if (handle == INVALID_HANDLE_VALUE) {
230         logReady = 0;
231         osi_panic("Cannot create log file", __FILE__, __LINE__);
232     }
233     osi_LogPrint(afsd_logp, handle);
234     if (flush)
235         FlushFileBuffers(handle);
236     CloseHandle(handle);
237 }
238
239 static void
240 configureBackConnectionHostNames(void)
241 {
242     /* On Windows XP SP2, Windows 2003 SP1, and all future Windows operating systems
243      * there is a restriction on the use of SMB authentication on loopback connections.
244      * There are two work arounds available:
245      * 
246      *   (1) We can disable the check for matching host names.  This does not
247      *   require a reboot:
248      *   [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa]
249      *     "DisableLoopbackCheck"=dword:00000001
250      *
251      *   (2) We can add the AFS SMB/CIFS service name to an approved list.  This
252      *   does require a reboot:
253      *   [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0]
254      *     "BackConnectionHostNames"=multi-sz
255      *
256      * The algorithm will be:
257      *   (1) Check to see if cm_NetbiosName exists in the BackConnectionHostNames list
258      *   (2a) If not, add it to the list.  (This will not take effect until the next reboot.)
259      *   (2b1)    and check to see if DisableLoopbackCheck is set.
260      *   (2b2)    If not set, set the DisableLoopbackCheck value to 0x1 
261      *   (2b3)                and create HKLM\SOFTWARE\OpenAFS\Client  UnsetDisableLoopbackCheck
262      *   (2c) else If cm_NetbiosName exists in the BackConnectionHostNames list,
263      *             check for the UnsetDisableLoopbackCheck value.  
264      *             If set, set the DisableLoopbackCheck flag to 0x0 
265      *             and delete the UnsetDisableLoopbackCheck value
266      */
267     HKEY hkLsa;
268     HKEY hkMSV10;
269     HKEY hkClient;
270     DWORD dwType;
271     DWORD dwSize;
272     DWORD dwValue;
273     PBYTE pHostNames = NULL, pName = NULL;
274     BOOL  bNameFound = FALSE;   
275
276     if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
277                        "SYSTEM\\CurrentControlSet\\Control\\Lsa\\MSV1_0",
278                        0,
279                        KEY_READ|KEY_WRITE,
280                        &hkMSV10) == ERROR_SUCCESS )
281     {
282         if (RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0, &dwType, NULL, &dwSize) == ERROR_SUCCESS) {
283             pHostNames = malloc(dwSize + strlen(cm_NetbiosName) + 1);
284             RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0, &dwType, pHostNames, &dwSize);
285
286             for (pName = pHostNames; *pName ; pName += strlen(pName) + 1)
287             {
288                 if ( !stricmp(pName, cm_NetbiosName) ) {
289                     bNameFound = TRUE;
290                     break;
291                 }   
292             }
293         }
294              
295         if ( !bNameFound ) {
296             int size = strlen(cm_NetbiosName) + 2;
297             if ( !pHostNames ) {
298                 pHostNames = malloc(size);
299                 dwSize = 1;
300             }
301             pName = pHostNames;
302             StringCbCopyA(pName, size, cm_NetbiosName);
303             pName += size - 1;
304             *pName = '\0';  /* add a second nul terminator */
305
306             dwType = REG_MULTI_SZ;
307             dwSize += strlen(cm_NetbiosName) + 1;
308             RegSetValueEx( hkMSV10, "BackConnectionHostNames", 0, dwType, pHostNames, dwSize);
309
310             if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
311                                "SYSTEM\\CurrentControlSet\\Control\\Lsa",
312                                0,
313                                KEY_READ|KEY_WRITE,
314                                &hkLsa) == ERROR_SUCCESS )
315             {
316                 dwSize = sizeof(DWORD);
317                 if ( RegQueryValueEx( hkLsa, "DisableLoopbackCheck", 0, &dwType, &dwValue, &dwSize) != ERROR_SUCCESS ||
318                      dwValue == 0 ) {
319                     dwType = REG_DWORD;
320                     dwSize = sizeof(DWORD);
321                     dwValue = 1;
322                     RegSetValueEx( hkLsa, "DisableLoopbackCheck", 0, dwType, &dwValue, dwSize);
323
324                     if (RegCreateKeyEx( HKEY_LOCAL_MACHINE, 
325                                         "SOFTWARE\\OpenAFS\\Client",
326                                         0,
327                                         NULL,
328                                         REG_OPTION_NON_VOLATILE,
329                                         KEY_READ|KEY_WRITE,
330                                         NULL,
331                                         &hkClient,
332                                         NULL) == ERROR_SUCCESS) {
333
334                         dwType = REG_DWORD;
335                         dwSize = sizeof(DWORD);
336                         dwValue = 1;
337                         RegSetValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, dwType, &dwValue, dwSize);
338                         RegCloseKey(hkClient);
339                     }
340                     RegCloseKey(hkLsa);
341                 }
342             }
343         } else {
344             if (RegCreateKeyEx( HKEY_LOCAL_MACHINE, 
345                                 "SOFTWARE\\OpenAFS\\Client",
346                                 0,
347                                 NULL,
348                                 REG_OPTION_NON_VOLATILE,
349                                 KEY_READ|KEY_WRITE,
350                                 NULL,
351                                 &hkClient,
352                                 NULL) == ERROR_SUCCESS) {
353
354                 dwSize = sizeof(DWORD);
355                 if ( RegQueryValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, &dwType, &dwValue, &dwSize) == ERROR_SUCCESS &&
356                      dwValue == 1 ) {
357                     if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
358                                        "SYSTEM\\CurrentControlSet\\Control\\Lsa",
359                                        0,
360                                        KEY_READ|KEY_WRITE,
361                                        &hkLsa) == ERROR_SUCCESS )
362                     {
363                         RegDeleteValue(hkLsa, "DisableLoopbackCheck");
364                         RegCloseKey(hkLsa);
365                     }
366                 }
367                 RegDeleteValue(hkClient, "RemoveDisableLoopbackCheck");
368                 RegCloseKey(hkClient);
369             }
370         }
371         RegCloseKey(hkMSV10);
372     }
373 }
374
375
376 /*
377  * AFSD Initialization
378  */
379
380 int afsd_InitCM(char **reasonP)
381 {
382     osi_uid_t debugID;
383     long cacheBlocks;
384     long cacheSize;
385     long logChunkSize;
386     long stats;
387     long traceBufSize;
388     long maxcpus;
389     long ltt, ltto;
390     long rx_mtu, rx_nojumbo;
391     long virtualCache;
392     char rootCellName[256];
393     struct rx_service *serverp;
394     static struct rx_securityClass *nullServerSecurityClassp;
395     struct hostent *thp;
396     char *msgBuf;
397     char buf[1024];
398     HKEY parmKey;
399     DWORD dummyLen;
400     DWORD regType;
401     long code;
402     /*int freelanceEnabled;*/
403     WSADATA WSAjunk;
404     lana_number_t lanaNum;
405     int i;
406
407     WSAStartup(0x0101, &WSAjunk);
408
409     afsd_initUpperCaseTable();
410
411     /* setup osidebug server at RPC slot 1000 */
412     osi_LongToUID(1000, &debugID);
413     code = osi_InitDebug(&debugID);
414     afsi_log("osi_InitDebug code %d", code);
415
416     //  osi_LockTypeSetDefault("stat"); /* comment this out for speed *
417     if (code != 0) {
418         *reasonP = "unknown error";
419         return -1;
420     }
421
422     /* who are we ? */
423     gethostname(cm_HostName, sizeof(cm_HostName));
424     afsi_log("gethostname %s", cm_HostName);
425     thp = gethostbyname(cm_HostName);
426     memcpy(&cm_HostAddr, thp->h_addr_list[0], 4);
427
428     /* seed random number generator */
429     srand(ntohl(cm_HostAddr));
430
431     /* Look up configuration parameters in Registry */
432     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSConfigKeyName,
433                          0, KEY_QUERY_VALUE, &parmKey);
434     if (code != ERROR_SUCCESS) {
435         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
436                        | FORMAT_MESSAGE_ALLOCATE_BUFFER,
437                        NULL, code, 0, (LPTSTR)&msgBuf, 0, NULL);
438         StringCbPrintfA(buf, sizeof(buf),
439                          "Failure in configuration while opening Registry: %s",
440                          msgBuf);
441         osi_panic(buf, __FILE__, __LINE__);
442     }
443
444     dummyLen = sizeof(maxcpus);
445     code = RegQueryValueEx(parmKey, "MaxCPUs", NULL, NULL,
446                             (BYTE *) &maxcpus, &dummyLen);
447     if (code == ERROR_SUCCESS) {
448         HANDLE hProcess;
449         DWORD_PTR processAffinityMask, systemAffinityMask;
450
451         hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION,
452                                FALSE, GetCurrentProcessId());
453         if ( hProcess != NULL &&
454              GetProcessAffinityMask(hProcess, &processAffinityMask, &systemAffinityMask) )
455         {
456             int i, n, bits;
457             DWORD_PTR mask, newAffinityMask;
458
459 #if defined(_WIN64)
460             bits = 64;
461 #else
462             bits = 32;
463 #endif
464             for ( i=0, n=0, mask=1, newAffinityMask=0; i<bits && n<maxcpus; i++ ) {
465                 if ( processAffinityMask & mask ) {
466                     newAffinityMask |= mask;
467                     n++;
468                 }
469                 mask *= 2;
470             }
471
472             SetProcessAffinityMask(hProcess, newAffinityMask);
473             CloseHandle(hProcess);
474             afsi_log("CPU Restrictions set to %d cpu(s); %d cpu(s) available", maxcpus, n);
475         } else {
476             afsi_log("CPU Restrictions set to %d cpu(s); unable to access process information", maxcpus);
477         }
478     }
479
480     dummyLen = sizeof(TraceOption);
481     code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
482                             (BYTE *) &TraceOption, &dummyLen);
483     afsi_log("Event Log Tracing = %lX", TraceOption);
484
485     dummyLen = sizeof(traceBufSize);
486     code = RegQueryValueEx(parmKey, "TraceBufferSize", NULL, NULL,
487                             (BYTE *) &traceBufSize, &dummyLen);
488     if (code == ERROR_SUCCESS)
489         afsi_log("Trace Buffer size %d", traceBufSize);
490     else {
491         traceBufSize = CM_CONFIGDEFAULT_TRACEBUFSIZE;
492         afsi_log("Default trace buffer size %d", traceBufSize);
493     }
494
495     /* setup and enable debug log */
496     afsd_logp = osi_LogCreate("afsd", traceBufSize);
497     afsi_log("osi_LogCreate log addr %x", (int)afsd_logp);
498     osi_LogEnable(afsd_logp);
499     logReady = 1;
500
501     osi_Log0(afsd_logp, "Log init");
502
503     dummyLen = sizeof(cacheSize);
504     code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
505                             (BYTE *) &cacheSize, &dummyLen);
506     if (code == ERROR_SUCCESS)
507         afsi_log("Cache size %d", cacheSize);
508     else {
509         cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
510         afsi_log("Default cache size %d", cacheSize);
511     }
512
513     dummyLen = sizeof(logChunkSize);
514     code = RegQueryValueEx(parmKey, "ChunkSize", NULL, NULL,
515                             (BYTE *) &logChunkSize, &dummyLen);
516     if (code == ERROR_SUCCESS) {
517         if (logChunkSize < 12 || logChunkSize > 30) {
518             afsi_log("Invalid chunk size %d, using default",
519                       logChunkSize);
520             logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
521         }
522         afsi_log("Chunk size %d", logChunkSize);
523     } else {
524         logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
525         afsi_log("Default chunk size %d", logChunkSize);
526     }
527     cm_logChunkSize = logChunkSize;
528     cm_chunkSize = 1 << logChunkSize;
529
530     dummyLen = sizeof(numBkgD);
531     code = RegQueryValueEx(parmKey, "Daemons", NULL, NULL,
532                             (BYTE *) &numBkgD, &dummyLen);
533     if (code == ERROR_SUCCESS)
534         afsi_log("%d background daemons", numBkgD);
535     else {
536         numBkgD = CM_CONFIGDEFAULT_DAEMONS;
537         afsi_log("Defaulting to %d background daemons", numBkgD);
538     }
539
540     dummyLen = sizeof(numSvThreads);
541     code = RegQueryValueEx(parmKey, "ServerThreads", NULL, NULL,
542                             (BYTE *) &numSvThreads, &dummyLen);
543     if (code == ERROR_SUCCESS)
544         afsi_log("%d server threads", numSvThreads);
545     else {
546         numSvThreads = CM_CONFIGDEFAULT_SVTHREADS;
547         afsi_log("Defaulting to %d server threads", numSvThreads);
548     }
549
550     dummyLen = sizeof(stats);
551     code = RegQueryValueEx(parmKey, "Stats", NULL, NULL,
552                             (BYTE *) &stats, &dummyLen);
553     if (code == ERROR_SUCCESS)
554         afsi_log("Status cache size %d", stats);
555     else {
556         stats = CM_CONFIGDEFAULT_STATS;
557         afsi_log("Default status cache size %d", stats);
558     }
559
560     dummyLen = sizeof(ltt);
561     code = RegQueryValueEx(parmKey, "LogoffTokenTransfer", NULL, NULL,
562                             (BYTE *) &ltt, &dummyLen);
563     if (code == ERROR_SUCCESS)
564         afsi_log("Logoff token transfer %s",  (ltt ? "on" : "off"));
565     else {
566         ltt = 1;
567         afsi_log("Logoff token transfer on by default");
568     }
569     smb_LogoffTokenTransfer = ltt;
570     afsi_log("Logoff token transfer is currently ignored");
571
572     if (ltt) {
573         dummyLen = sizeof(ltto);
574         code = RegQueryValueEx(parmKey, "LogoffTokenTransferTimeout",
575                                 NULL, NULL, (BYTE *) &ltto, &dummyLen);
576         if (code == ERROR_SUCCESS)
577             afsi_log("Logoff token tranfer timeout %d seconds", ltto);
578         else {
579             ltto = 10;
580             afsi_log("Default logoff token transfer timeout 10 seconds");
581         }
582     } else {
583         ltto = 0;
584     }   
585     smb_LogoffTransferTimeout = ltto;
586     afsi_log("Default logoff token is currently ignored");
587
588     dummyLen = sizeof(cm_rootVolumeName);
589     code = RegQueryValueEx(parmKey, "RootVolume", NULL, NULL,
590                             cm_rootVolumeName, &dummyLen);
591     if (code == ERROR_SUCCESS)
592         afsi_log("Root volume %s", cm_rootVolumeName);
593     else {
594         StringCbCopyA(cm_rootVolumeName, sizeof(cm_rootVolumeName), "root.afs");
595         afsi_log("Default root volume name root.afs");
596     }
597
598     cm_mountRootLen = sizeof(cm_mountRoot);
599     code = RegQueryValueEx(parmKey, "MountRoot", NULL, NULL,
600                             cm_mountRoot, &cm_mountRootLen);
601     if (code == ERROR_SUCCESS) {
602         afsi_log("Mount root %s", cm_mountRoot);
603         cm_mountRootLen = strlen(cm_mountRoot);
604     } else {
605         StringCbCopyA(cm_mountRoot, sizeof(cm_mountRoot), "/afs");
606         cm_mountRootLen = 4;
607         /* Don't log */
608     }
609
610     dummyLen = sizeof(buf);
611     code = RegQueryValueEx(parmKey, "CachePath", NULL, &regType,
612                             buf, &dummyLen);
613     if (code == ERROR_SUCCESS && buf[0]) {
614         if (regType == REG_EXPAND_SZ) {
615             dummyLen = ExpandEnvironmentStrings(buf, cm_CachePath, sizeof(cm_CachePath));
616             if(dummyLen > sizeof(cm_CachePath)) {
617                 afsi_log("Cache path [%s] longer than %d after expanding env strings", buf, sizeof(cm_CachePath));
618                 osi_panic("CachePath too long", __FILE__, __LINE__);
619             }
620         } else {
621             StringCbCopyA(cm_CachePath, sizeof(cm_CachePath), buf);
622         }
623         afsi_log("Cache path %s", cm_CachePath);
624     } else {
625         GetWindowsDirectory(cm_CachePath, sizeof(cm_CachePath));
626         cm_CachePath[2] = 0;    /* get drive letter only */
627         StringCbCatA(cm_CachePath, sizeof(cm_CachePath), "\\AFSCache");
628         afsi_log("Default cache path %s", cm_CachePath);
629     }
630
631     dummyLen = sizeof(virtualCache);
632     code = RegQueryValueEx(parmKey, "NonPersistentCaching", NULL, NULL,
633                             &virtualCache, &dummyLen);
634     if (code == ERROR_SUCCESS && virtualCache) {
635         buf_cacheType = CM_BUF_CACHETYPE_VIRTUAL;
636     } else {
637         buf_cacheType = CM_BUF_CACHETYPE_FILE;
638     }
639     afsi_log("Cache type is %s", ((buf_cacheType == CM_BUF_CACHETYPE_FILE)?"FILE":"VIRTUAL"));
640
641     dummyLen = sizeof(traceOnPanic);
642     code = RegQueryValueEx(parmKey, "TrapOnPanic", NULL, NULL,
643                             (BYTE *) &traceOnPanic, &dummyLen);
644     if (code == ERROR_SUCCESS)
645         afsi_log("Set to %s on panic",
646                   traceOnPanic ? "trap" : "not trap");
647     else {  
648         traceOnPanic = 0;
649         /* Don't log */
650     }
651
652     dummyLen = sizeof(reportSessionStartups);
653     code = RegQueryValueEx(parmKey, "ReportSessionStartups", NULL, NULL,
654                             (BYTE *) &reportSessionStartups, &dummyLen);
655     if (code == ERROR_SUCCESS)
656         afsi_log("Session startups %s be recorded in the Event Log",
657                   reportSessionStartups ? "will" : "will not");
658     else {
659         reportSessionStartups = 0;
660         /* Don't log */
661     }
662
663     for ( i=0; i < MAXNUMSYSNAMES; i++ ) {
664         cm_sysNameList[i] = osi_Alloc(MAXSYSNAME);
665         cm_sysNameList[i][0] = '\0';
666     }
667     cm_sysName = cm_sysNameList[0];
668
669     dummyLen = sizeof(buf);
670     code = RegQueryValueEx(parmKey, "SysName", NULL, NULL, buf, &dummyLen);
671     if (code == ERROR_SUCCESS && buf[0]) {
672         char * p, *q; 
673         afsi_log("Sys name %s", buf);
674
675         for (p = q = buf; p < buf + dummyLen; p++)
676         {
677             if (*p == '\0' || isspace(*p)) {
678                 memcpy(cm_sysNameList[cm_sysNameCount],q,p-q);
679                 cm_sysNameList[cm_sysNameCount][p-q] = '\0';
680                 cm_sysNameCount++;
681
682                 do {
683                     if (*p == '\0')
684                         goto done_sysname;
685                         
686                     p++;
687                 } while (*p == '\0' || isspace(*p));
688                 q = p;
689                 p--;
690             }
691         }
692       done_sysname:
693         StringCbCopyA(cm_sysName, MAXSYSNAME, cm_sysNameList[0]);
694     } else {
695         cm_sysNameCount = 1;
696         StringCbCopyA(cm_sysName, MAXSYSNAME, "i386_nt40");
697         StringCbCopyA(cm_sysNameList[0], MAXSYSNAME, "i386_nt40");
698         afsi_log("Default sys name %s", cm_sysName);
699     }
700
701     dummyLen = sizeof(cryptall);
702     code = RegQueryValueEx(parmKey, "SecurityLevel", NULL, NULL,
703                             (BYTE *) &cryptall, &dummyLen);
704     if (code == ERROR_SUCCESS) {
705         afsi_log("SecurityLevel is %s", cryptall?"crypt":"clear");
706     } else {
707         cryptall = 0;
708         afsi_log("Default SecurityLevel is clear");
709     }
710
711 #ifdef AFS_AFSDB_ENV
712     dummyLen = sizeof(cm_dnsEnabled);
713     code = RegQueryValueEx(parmKey, "UseDNS", NULL, NULL,
714                             (BYTE *) &cm_dnsEnabled, &dummyLen);
715     if (code == ERROR_SUCCESS) {
716         afsi_log("DNS %s be used to find AFS cell servers",
717                   cm_dnsEnabled ? "will" : "will not");
718     }       
719     else {
720         cm_dnsEnabled = 1;   /* default on */
721         afsi_log("Default to use DNS to find AFS cell servers");
722     }
723 #else /* AFS_AFSDB_ENV */
724     afsi_log("AFS not built with DNS support to find AFS cell servers");
725 #endif /* AFS_AFSDB_ENV */
726
727 #ifdef AFS_FREELANCE_CLIENT
728     dummyLen = sizeof(cm_freelanceEnabled);
729     code = RegQueryValueEx(parmKey, "FreelanceClient", NULL, NULL,
730                             (BYTE *) &cm_freelanceEnabled, &dummyLen);
731     if (code == ERROR_SUCCESS) {
732         afsi_log("Freelance client feature %s activated",
733                   cm_freelanceEnabled ? "is" : "is not");
734     }       
735     else {
736         cm_freelanceEnabled = 0;  /* default off */
737     }
738 #endif /* AFS_FREELANCE_CLIENT */
739
740 #ifdef COMMENT
741     /* The netbios name is looked up in lana_GetUNCServerNameEx */
742     dummyLen = sizeof(buf);
743     code = RegQueryValueEx(parmKey, "NetbiosName", NULL, NULL,
744                            (BYTE *) &buf, &dummyLen);
745     if (code == ERROR_SUCCESS) {
746         DWORD len = ExpandEnvironmentStrings(buf, cm_NetbiosName, MAX_NB_NAME_LENGTH);
747         if ( len > 0 && len <= MAX_NB_NAME_LENGTH ) {
748             afsi_log("Explicit NetBios name is used %s", cm_NetbiosName);
749         } else {
750             afsi_log("Unable to Expand Explicit NetBios name: %s", buf);
751             cm_NetbiosName[0] = 0;  /* turn it off */
752         }
753     }
754     else {
755         cm_NetbiosName[0] = 0;   /* default off */
756     }
757 #endif
758
759     dummyLen = sizeof(smb_hideDotFiles);
760     code = RegQueryValueEx(parmKey, "HideDotFiles", NULL, NULL,
761                            (BYTE *) &smb_hideDotFiles, &dummyLen);
762     if (code != ERROR_SUCCESS) {
763         smb_hideDotFiles = 1; /* default on */
764     }
765     afsi_log("Dot files/dirs will %sbe marked hidden",
766               smb_hideDotFiles ? "" : "not ");
767
768     dummyLen = sizeof(smb_maxMpxRequests);
769     code = RegQueryValueEx(parmKey, "MaxMpxRequests", NULL, NULL,
770                            (BYTE *) &smb_maxMpxRequests, &dummyLen);
771     if (code != ERROR_SUCCESS) {
772         smb_maxMpxRequests = 50;
773     }
774     afsi_log("Maximum number of multiplexed sessions is %d", smb_maxMpxRequests);
775
776     dummyLen = sizeof(smb_maxVCPerServer);
777     code = RegQueryValueEx(parmKey, "MaxVCPerServer", NULL, NULL,
778                            (BYTE *) &smb_maxVCPerServer, &dummyLen);
779     if (code != ERROR_SUCCESS) {
780         smb_maxVCPerServer = 100;
781     }
782     afsi_log("Maximum number of VCs per server is %d", smb_maxVCPerServer);
783
784     dummyLen = sizeof(smb_authType);
785     code = RegQueryValueEx(parmKey, "SMBAuthType", NULL, NULL,
786                             (BYTE *) &smb_authType, &dummyLen);
787
788     if (code != ERROR_SUCCESS || 
789          (smb_authType != SMB_AUTH_EXTENDED && smb_authType != SMB_AUTH_NTLM && smb_authType != SMB_AUTH_NONE)) {
790         smb_authType = SMB_AUTH_EXTENDED; /* default is to use extended authentication */
791     }
792     afsi_log("SMB authentication type is %s", ((smb_authType == SMB_AUTH_NONE)?"NONE":((smb_authType == SMB_AUTH_EXTENDED)?"EXTENDED":"NTLM")));
793
794     dummyLen = sizeof(rx_nojumbo);
795     code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
796                            (BYTE *) &rx_nojumbo, &dummyLen);
797     if (code != ERROR_SUCCESS) {
798         rx_nojumbo = 0;
799     }
800     if (rx_nojumbo)
801         afsi_log("RX Jumbograms are disabled");
802
803     dummyLen = sizeof(rx_mtu);
804     code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
805                            (BYTE *) &rx_mtu, &dummyLen);
806     if (code != ERROR_SUCCESS || !rx_mtu) {
807         rx_mtu = -1;
808     }
809     if (rx_mtu != -1)
810         afsi_log("RX maximum MTU is %d", rx_mtu);
811
812     dummyLen = sizeof(ConnDeadtimeout);
813     code = RegQueryValueEx(parmKey, "ConnDeadTimeout", NULL, NULL,
814                            (BYTE *) &ConnDeadtimeout, &dummyLen);
815     afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
816
817     dummyLen = sizeof(HardDeadtimeout);
818     code = RegQueryValueEx(parmKey, "HardDeadTimeout", NULL, NULL,
819                            (BYTE *) &HardDeadtimeout, &dummyLen);
820     afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
821
822     RegCloseKey (parmKey);
823
824     /* Call lanahelper to get Netbios name, lan adapter number and gateway flag */
825     if(SUCCEEDED(code = lana_GetUncServerNameEx(cm_NetbiosName, &lanaNum, &isGateway, LANA_NETBIOS_NAME_FULL))) {
826         LANadapter = (lanaNum == LANA_INVALID)? -1: lanaNum;
827
828         if (LANadapter != -1)
829             afsi_log("LAN adapter number %d", LANadapter);
830         else
831             afsi_log("LAN adapter number not determined");
832
833         if (isGateway)
834             afsi_log("Set for gateway service");
835
836         afsi_log("Using >%s< as SMB server name", cm_NetbiosName);
837     } else {
838         /* something went horribly wrong.  We can't proceed without a netbios name */
839         StringCbPrintfA(buf,sizeof(buf),"Netbios name could not be determined: %li", code);
840         osi_panic(buf, __FILE__, __LINE__);
841     }
842
843     /* setup early variables */
844     /* These both used to be configurable. */
845     smb_UseV3 = 1;
846     buf_bufferSize = CM_CONFIGDEFAULT_BLOCKSIZE;
847
848     /* turn from 1024 byte units into memory blocks */
849     cacheBlocks = (cacheSize * 1024) / buf_bufferSize;
850         
851     /* get network related info */
852     cm_noIPAddr = CM_MAXINTERFACE_ADDR;
853     code = syscfg_GetIFInfo(&cm_noIPAddr,
854                              cm_IPAddr, cm_SubnetMask,
855                              cm_NetMtu, cm_NetFlags);
856
857     if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
858         afsi_log("syscfg_GetIFInfo error code %d", code);
859     else
860         afsi_log("First Network address %x SubnetMask %x",
861                   cm_IPAddr[0], cm_SubnetMask[0]);
862
863     /*
864      * Save client configuration for GetCacheConfig requests
865      */
866     cm_initParams.nChunkFiles = 0;
867     cm_initParams.nStatCaches = stats;
868     cm_initParams.nDataCaches = 0;
869     cm_initParams.nVolumeCaches = 0;
870     cm_initParams.firstChunkSize = cm_chunkSize;
871     cm_initParams.otherChunkSize = cm_chunkSize;
872     cm_initParams.cacheSize = cacheSize;
873     cm_initParams.setTime = 0;
874     cm_initParams.memCache = 0;
875
876     /* Set RX parameters before initializing RX */
877     if ( rx_nojumbo ) {
878         rx_SetNoJumbo();
879         afsi_log("rx_SetNoJumbo successful");
880     }
881
882     if ( rx_mtu != -1 ) {
883         rx_SetMaxMTU(rx_mtu);
884         afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
885     }
886
887     /* Open Microsoft Firewall to allow in port 7001 */
888     icf_CheckAndAddAFSPorts(AFS_PORTSET_CLIENT);
889
890     /* Ensure the AFS Netbios Name is registered to allow loopback access */
891     configureBackConnectionHostNames();
892
893     /* initialize RX, and tell it to listen to port 7001, which is used for
894      * callback RPC messages.
895      */
896     code = rx_Init(htons(7001));
897     afsi_log("rx_Init code %x", code);
898     if (code != 0) {
899         *reasonP = "afsd: failed to init rx client on port 7001";
900         return -1;
901     }
902
903     /* Initialize the RPC server for session keys */
904     RpcInit();
905
906     /* create an unauthenticated service #1 for callbacks */
907     nullServerSecurityClassp = rxnull_NewServerSecurityObject();
908     serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
909                              RXAFSCB_ExecuteRequest);
910     afsi_log("rx_NewService addr %x", (int)serverp);
911     if (serverp == NULL) {
912         *reasonP = "unknown error";
913         return -1;
914     }
915
916     nullServerSecurityClassp = rxnull_NewServerSecurityObject();
917     serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
918                              &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
919     afsi_log("rx_NewService addr %x", (int)serverp);
920     if (serverp == NULL) {
921         *reasonP = "unknown error";
922         return -1;
923     }
924         
925     /* start server threads, *not* donating this one to the pool */
926     rx_StartServer(0);
927     afsi_log("rx_StartServer");
928
929     /* init user daemon, and other packages */
930     cm_InitUser();
931
932     cm_InitACLCache(2*stats);
933
934     cm_InitConn();
935
936     cm_InitCell();
937         
938     cm_InitServer();
939         
940     cm_InitVolume();
941
942     cm_InitIoctl();
943         
944     smb_InitIoctl();
945         
946     cm_InitCallback();
947         
948     cm_InitSCache(stats);
949         
950     code = cm_InitDCache(0, cacheBlocks);
951     afsi_log("cm_InitDCache code %x", code);
952     if (code != 0) {
953         *reasonP = "error initializing cache";
954         return -1;
955     }
956
957 #ifdef AFS_AFSDB_ENV
958 #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
959     if (cm_InitDNS(cm_dnsEnabled) == -1)
960         cm_dnsEnabled = 0;  /* init failed, so deactivate */
961     afsi_log("cm_InitDNS %d", cm_dnsEnabled);
962 #endif
963 #endif
964
965     code = cm_GetRootCellName(rootCellName);
966     afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s", 
967               code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
968     if (code != 0 && !cm_freelanceEnabled) 
969     {
970         *reasonP = "can't find root cell name in afsd.ini";
971         return -1;
972     }   
973     else if (cm_freelanceEnabled)
974         cm_rootCellp = NULL;
975
976     if (code == 0 && !cm_freelanceEnabled) 
977     {
978         cm_rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
979         afsi_log("cm_GetCell addr %x", (int)cm_rootCellp);
980         if (cm_rootCellp == NULL) 
981         {
982             *reasonP = "can't find root cell in afsdcell.ini";
983             return -1;
984         }
985     }
986
987 #ifdef AFS_FREELANCE_CLIENT
988     if (cm_freelanceEnabled)
989         cm_InitFreelance();
990 #endif
991     return 0;
992 }
993
994 int afsd_InitDaemons(char **reasonP)
995 {
996     long code;
997     cm_req_t req;
998
999     cm_InitReq(&req);
1000
1001     /* this should really be in an init daemon from here on down */
1002
1003     if (!cm_freelanceEnabled) {
1004                 osi_Log0(afsd_logp, "Loading Root Volume from cell");
1005         code = cm_GetVolumeByName(cm_rootCellp, cm_rootVolumeName, cm_rootUserp,
1006                                   &req, CM_FLAG_CREATE, &cm_rootVolumep);
1007         afsi_log("cm_GetVolumeByName code %x root vol %x", code,
1008                  (code ? (cm_volume_t *)-1 : cm_rootVolumep));
1009         if (code != 0) {
1010             *reasonP = "can't find root volume in root cell";
1011             return -1;
1012         }
1013     }
1014
1015     /* compute the root fid */
1016     if (!cm_freelanceEnabled) {
1017         cm_rootFid.cell = cm_rootCellp->cellID;
1018         cm_rootFid.volume = cm_GetROVolumeID(cm_rootVolumep);
1019         cm_rootFid.vnode = 1;
1020         cm_rootFid.unique = 1;
1021     }
1022     else
1023         cm_FakeRootFid(&cm_rootFid);
1024         
1025     code = cm_GetSCache(&cm_rootFid, &cm_rootSCachep, cm_rootUserp, &req);
1026     afsi_log("cm_GetSCache code %x scache %x", code,
1027              (code ? (cm_scache_t *)-1 : cm_rootSCachep));
1028     if (code != 0) {
1029         *reasonP = "unknown error";
1030         return -1;
1031     }
1032
1033     cm_InitDaemon(numBkgD);
1034     afsi_log("cm_InitDaemon");
1035
1036     return 0;
1037 }
1038
1039 int afsd_InitSMB(char **reasonP, void *aMBfunc)
1040 {
1041     HKEY parmKey;
1042     DWORD dummyLen;
1043     DWORD dwValue;
1044     DWORD code;
1045
1046     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, OpenAFSConfigKeyName,
1047                          0, KEY_QUERY_VALUE, &parmKey);
1048     if (code == ERROR_SUCCESS) {
1049         dummyLen = sizeof(DWORD);
1050         code = RegQueryValueEx(parmKey, "StoreAnsiFilenames", NULL, NULL,
1051                                 (BYTE *) &dwValue, &dummyLen);
1052         if (code == ERROR_SUCCESS)
1053             smb_StoreAnsiFilenames = dwValue ? 1 : 0;
1054         RegCloseKey (parmKey);
1055     }
1056
1057     /* Do this last so that we don't handle requests before init is done.
1058      * Here we initialize the SMB listener.
1059      */
1060     smb_Init(afsd_logp, cm_NetbiosName, smb_UseV3, LANadapter, numSvThreads, aMBfunc);
1061     afsi_log("smb_Init complete");
1062
1063     return 0;
1064 }
1065
1066 #ifdef ReadOnly
1067 #undef ReadOnly
1068 #endif
1069
1070 #ifdef File
1071 #undef File
1072 #endif
1073
1074 #pragma pack( push, before_imagehlp, 8 )
1075 #include <imagehlp.h>
1076 #pragma pack( pop, before_imagehlp )
1077
1078 #define MAXNAMELEN 1024
1079
1080 void afsd_printStack(HANDLE hThread, CONTEXT *c)
1081 {
1082     HANDLE hProcess = GetCurrentProcess();
1083     int frameNum;
1084     DWORD offset;
1085     DWORD symOptions;
1086     char functionName[MAXNAMELEN];
1087   
1088     IMAGEHLP_MODULE Module;
1089     IMAGEHLP_LINE Line;
1090   
1091     STACKFRAME s;
1092     IMAGEHLP_SYMBOL *pSym;
1093   
1094     afsi_log_useTimestamp = 0;
1095   
1096     pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
1097   
1098     memset( &s, '\0', sizeof s );
1099     if (!SymInitialize(hProcess, NULL, 1) )
1100     {
1101         afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
1102       
1103         SymCleanup( hProcess );
1104         GlobalFree(pSym);
1105       
1106         return;
1107     }
1108   
1109     symOptions = SymGetOptions();
1110     symOptions |= SYMOPT_LOAD_LINES;
1111     symOptions &= ~SYMOPT_UNDNAME;
1112     SymSetOptions( symOptions );
1113   
1114     /*
1115      * init STACKFRAME for first call
1116      * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
1117      * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
1118      * and good riddance.
1119      */
1120 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
1121 #error The STACKFRAME initialization in afsd_printStack() for this platform
1122 #error must be properly configured
1123 #else
1124     s.AddrPC.Offset = c->Eip;
1125     s.AddrPC.Mode = AddrModeFlat;
1126     s.AddrFrame.Offset = c->Ebp;
1127     s.AddrFrame.Mode = AddrModeFlat;
1128 #endif
1129
1130     memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
1131     pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
1132     pSym->MaxNameLength = MAXNAMELEN;
1133   
1134     memset( &Line, '\0', sizeof Line );
1135     Line.SizeOfStruct = sizeof Line;
1136   
1137     memset( &Module, '\0', sizeof Module );
1138     Module.SizeOfStruct = sizeof Module;
1139   
1140     offset = 0;
1141   
1142     afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
1143   
1144     for ( frameNum = 0; ; ++ frameNum )
1145     {
1146         /*
1147          * get next stack frame (StackWalk(), SymFunctionTableAccess(), 
1148          * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
1149          * ERROR_NOACCESS (998), you can assume that either you are done, or
1150          * that the stack is so hosed that the next deeper frame could not be
1151          * found.
1152          */
1153         if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c, 
1154                           NULL, SymFunctionTableAccess, SymGetModuleBase, 
1155                           NULL ) )
1156             break;
1157       
1158         /* display its contents */
1159         afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
1160                  frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
1161                  s.AddrPC.Offset, s.AddrReturn.Offset,
1162                  s.AddrFrame.Offset, s.AddrStack.Offset );
1163       
1164         if ( s.AddrPC.Offset == 0 )
1165         {
1166             afsi_log("(-nosymbols- PC == 0)" );
1167         }
1168         else
1169         { 
1170             /* show procedure info from a valid PC */
1171             if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
1172             {
1173                 if ( GetLastError() != ERROR_INVALID_ADDRESS )
1174                 {
1175                     afsi_log("SymGetSymFromAddr(): errno = %lu", 
1176                              GetLastError());
1177                 }
1178             }
1179             else
1180             {
1181                 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN, 
1182                                      UNDNAME_NAME_ONLY);
1183                 afsi_log("%s", functionName );
1184
1185                 if ( offset != 0 )
1186                 {
1187                     afsi_log(" %+ld bytes", (long) offset);
1188                 }
1189             }
1190
1191             if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
1192             {
1193                 if (GetLastError() != ERROR_INVALID_ADDRESS)
1194                 {
1195                     afsi_log("Error: SymGetLineFromAddr(): errno = %lu", 
1196                              GetLastError());
1197                 }
1198             }
1199             else
1200             {
1201                 afsi_log("    Line: %s(%lu) %+ld bytes", Line.FileName, 
1202                          Line.LineNumber, offset);
1203             }
1204         }
1205       
1206         /* no return address means no deeper stackframe */
1207         if (s.AddrReturn.Offset == 0)
1208         {
1209             SetLastError(0);
1210             break;
1211         }
1212     }
1213   
1214     if (GetLastError() != 0)
1215     {
1216         afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
1217     }
1218   
1219     SymCleanup(hProcess);
1220     GlobalFree(pSym);
1221 }
1222
1223 #ifdef _DEBUG
1224 static DWORD *afsd_crtDbgBreakCurrent = NULL;
1225 static DWORD afsd_crtDbgBreaks[256];
1226 #endif
1227
1228 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
1229 {
1230     CONTEXT context;
1231 #ifdef _DEBUG  
1232     BOOL allocRequestBrk = FALSE;
1233 #endif 
1234   
1235     afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n", 
1236              ep->ExceptionRecord->ExceptionCode, 
1237              ep->ExceptionRecord->ExceptionAddress);
1238            
1239 #ifdef _DEBUG
1240     if (afsd_crtDbgBreakCurrent && 
1241         *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
1242     { 
1243         allocRequestBrk = TRUE;
1244         afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
1245     }
1246 #endif
1247            
1248     /* save context if we want to print the stack information */
1249     context = *ep->ContextRecord;
1250            
1251     afsd_printStack(GetCurrentThread(), &context);
1252            
1253     if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
1254     {
1255         afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
1256     
1257 #ifdef _DEBUG
1258         if (allocRequestBrk)
1259         {
1260             afsd_crtDbgBreakCurrent++;
1261             _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
1262         }
1263 #endif         
1264     
1265         ep->ContextRecord->Eip++;
1266         return EXCEPTION_CONTINUE_EXECUTION;
1267     }
1268     else
1269     {
1270         return EXCEPTION_CONTINUE_SEARCH;
1271     }
1272 }
1273   
1274 void afsd_SetUnhandledExceptionFilter()
1275 {
1276     SetUnhandledExceptionFilter(afsd_ExceptionFilter);
1277 }
1278   
1279 #ifdef _DEBUG
1280 void afsd_DbgBreakAllocInit()
1281 {
1282     memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
1283     afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
1284 }
1285   
1286 void afsd_DbgBreakAdd(DWORD requestNumber)
1287 {
1288     int i;
1289     for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
1290         {
1291         if (afsd_crtDbgBreaks[i] == -1)
1292             {
1293             break;
1294             }
1295         }
1296     afsd_crtDbgBreaks[i] = requestNumber;
1297
1298     _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);
1299 }
1300 #endif