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