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