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