e5f5431730d98d8619c1eed472af2b998ec1e427
[openafs.git] / src / WINNT / afsd / afsd_init.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afs/param.h>
11 #include <afs/stds.h>
12 #include <afs/afs_args.h>
13
14 #include <windows.h>
15 #include <string.h>
16 #include <nb30.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <locale.h>
20 #include <mbctype.h>
21 #include <winsock2.h>
22 #include <ErrorRep.h>
23
24 #include <osi.h>
25 #include "afsd.h"
26 #ifdef USE_BPLUS
27 #include "cm_btree.h"
28 #endif
29 #include <rx\rx.h>
30 #include <rx\rx_null.h>
31 #include <WINNT/syscfg.h>
32 #include <WINNT/afsreg.h>
33
34 #include "smb.h"
35 #include "cm_rpc.h"
36 #include "lanahelper.h"
37 #include <strsafe.h>
38 #include "cm_memmap.h"
39
40 extern int RXAFSCB_ExecuteRequest(struct rx_call *z_call);
41 extern int RXSTATS_ExecuteRequest(struct rx_call *z_call);
42
43 extern afs_int32 cryptall;
44 extern int cm_enableServerLocks;
45 extern int cm_followBackupPath;
46 extern int cm_deleteReadOnly;
47 #ifdef USE_BPLUS
48 extern afs_int32 cm_BPlusTrees;
49 #endif
50 extern afs_int32 cm_OfflineROIsValid;
51 extern afs_int32 cm_giveUpAllCBs;
52 extern const char **smb_ExecutableExtensions;
53
54 osi_log_t *afsd_logp;
55
56 cm_config_data_t        cm_data;
57
58 char cm_rootVolumeName[VL_MAXNAMELEN];
59 DWORD cm_rootVolumeNameLen;
60 char cm_mountRoot[1024];
61 DWORD cm_mountRootLen;
62 int cm_logChunkSize;
63 int cm_chunkSize;
64 #ifdef AFS_FREELANCE_CLIENT
65 char *cm_FakeRootDir;
66 #endif /* freelance */
67
68 int smb_UseV3 = 1;
69
70 int LANadapter;
71
72 int numBkgD;
73 int numSvThreads;
74 long rx_mtu = -1;
75 int traceOnPanic = 0;
76
77 int logReady = 0;
78
79 char cm_HostName[200];
80 long cm_HostAddr;
81 unsigned short cm_callbackport = CM_DEFAULT_CALLBACKPORT;
82
83 char cm_NetbiosName[MAX_NB_NAME_LENGTH] = "";
84
85 char cm_CachePath[MAX_PATH];
86 DWORD cm_CachePathLen;
87 DWORD cm_ValidateCache = 1;
88
89 BOOL reportSessionStartups = FALSE;
90
91 cm_initparams_v1 cm_initParams;
92
93 char *cm_sysName = 0;
94 unsigned int   cm_sysNameCount = 0;
95 char *cm_sysNameList[MAXNUMSYSNAMES];
96
97 DWORD TraceOption = 0;
98
99 /*
100  * AFSD Initialization Log
101  *
102  * This is distinct from the regular debug logging facility.
103  * Log items go directly to a file, not to an array in memory, so that even
104  * if AFSD crashes, the log can be inspected.
105  */
106
107 HANDLE afsi_file;
108
109 #ifdef AFS_AFSDB_ENV
110 int cm_dnsEnabled = 1;
111 #endif
112
113
114 static int afsi_log_useTimestamp = 1;
115
116 void
117 afsi_log(char *pattern, ...)
118 {
119     char s[256], t[100], d[100], u[512];
120     DWORD zilch;
121     va_list ap;
122     va_start(ap, pattern);
123
124     StringCbVPrintfA(s, sizeof(s), pattern, ap);
125     if ( afsi_log_useTimestamp ) {
126         GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
127         GetDateFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, d, sizeof(d));
128         StringCbPrintfA(u, sizeof(u), "%s %s: %s\r\n", d, t, s);
129         if (afsi_file != INVALID_HANDLE_VALUE)
130             WriteFile(afsi_file, u, (DWORD)strlen(u), &zilch, NULL);
131 #ifdef NOTSERVICE
132         printf("%s", u);
133 #endif 
134     } else {
135         if (afsi_file != INVALID_HANDLE_VALUE)
136             WriteFile(afsi_file, s, (DWORD)strlen(s), &zilch, NULL);
137     }
138 }
139
140 extern initUpperCaseTable();
141 void afsd_initUpperCaseTable() 
142 {
143     initUpperCaseTable();
144 }
145
146 void
147 afsi_start()
148 {
149     char wd[MAX_PATH+1];
150     char t[100], u[100], *p, *path;
151     int zilch;
152     DWORD code;
153     DWORD dwLow, dwHigh;
154     HKEY parmKey;
155     DWORD dummyLen;
156     DWORD maxLogSize = 100 * 1024;
157
158     afsi_file = INVALID_HANDLE_VALUE;
159     code = GetTempPath(sizeof(wd)-15, wd);
160     if ( code == 0 || code > (sizeof(wd)-15) )
161         return;         /* unable to create a log */
162
163     StringCbCatA(wd, sizeof(wd), "\\afsd_init.log");
164     GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
165     afsi_file = CreateFile(wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
166                            OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
167
168     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
169                          0, KEY_QUERY_VALUE, &parmKey);
170     if (code == ERROR_SUCCESS) {
171         dummyLen = sizeof(maxLogSize);
172         code = RegQueryValueEx(parmKey, "MaxLogSize", NULL, NULL,
173                                 (BYTE *) &maxLogSize, &dummyLen);
174         RegCloseKey (parmKey);
175     }
176
177     if (maxLogSize) {
178         dwLow = GetFileSize( afsi_file, &dwHigh );
179         if ( dwHigh > 0 || dwLow >= maxLogSize ) {
180             CloseHandle(afsi_file);
181             afsi_file = CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
182                                     CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
183         }
184     }
185
186     SetFilePointer(afsi_file, 0, NULL, FILE_END);
187     GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, u, sizeof(u));
188     StringCbCatA(t, sizeof(t), ": Create log file\r\n");
189     StringCbCatA(u, sizeof(u), ": Created log file\r\n");
190     WriteFile(afsi_file, t, (DWORD)strlen(t), &zilch, NULL);
191     WriteFile(afsi_file, u, (DWORD)strlen(u), &zilch, NULL);
192     p = "PATH=";
193     code = GetEnvironmentVariable("PATH", NULL, 0);
194     path = malloc(code);
195     code = GetEnvironmentVariable("PATH", path, code);
196     WriteFile(afsi_file, p, (DWORD)strlen(p), &zilch, NULL);
197     WriteFile(afsi_file, path, (DWORD)strlen(path), &zilch, NULL);
198     WriteFile(afsi_file, "\r\n", (DWORD)1, &zilch, NULL);
199     free(path);
200
201     /* Initialize C RTL Code Page conversion functions */
202     /* All of the path info obtained from the SMB client is in the OEM code page */
203     afsi_log("OEM Code Page = %d", GetOEMCP());
204     afsi_log("locale =  %s", setlocale(LC_ALL,NULL));
205 #ifdef COMMENT
206     /* Two things to look into.  First, should mbstowcs() be performing 
207      * character set translations from OEM to Unicode in smb3.c; 
208      * Second, do we need to set this translation in each function 
209      * due to multi-threading. 
210      */
211     afsi_log("locale -> %s", setlocale(LC_ALL, ".OCP"));
212     afsi_log("_setmbcp = %d -> %d", _setmbcp(_MB_CP_OEM), _getmbcp());
213 #endif /* COMMENT */
214 }
215
216 /*
217  * Standard AFSD trace
218  */
219
220 void afsd_ForceTrace(BOOL flush)
221 {
222     HANDLE handle;
223     int len;
224     char buf[256];
225
226     if (!logReady) 
227         return;
228
229     len = GetTempPath(sizeof(buf)-10, buf);
230     StringCbCopyA(&buf[len], sizeof(buf)-len, "/afsd.log");
231     handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
232                          NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
233     if (handle == INVALID_HANDLE_VALUE) {
234         logReady = 0;
235         osi_panic("Cannot create log file", __FILE__, __LINE__);
236     }
237     osi_LogPrint(afsd_logp, handle);
238     if (flush)
239         FlushFileBuffers(handle);
240     CloseHandle(handle);
241 }
242
243 static void
244 configureBackConnectionHostNames(void)
245 {
246     /* On Windows XP SP2, Windows 2003 SP1, and all future Windows operating systems
247      * there is a restriction on the use of SMB authentication on loopback connections.
248      * There are two work arounds available:
249      * 
250      *   (1) We can disable the check for matching host names.  This does not
251      *   require a reboot:
252      *   [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa]
253      *     "DisableLoopbackCheck"=dword:00000001
254      *
255      *   (2) We can add the AFS SMB/CIFS service name to an approved list.  This
256      *   does require a reboot:
257      *   [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0]
258      *     "BackConnectionHostNames"=multi-sz
259      *
260      * The algorithm will be:
261      *   (1) Check to see if cm_NetbiosName exists in the BackConnectionHostNames list
262      *   (2a) If not, add it to the list.  (This will not take effect until the next reboot.)
263      *   (2b1)    and check to see if DisableLoopbackCheck is set.
264      *   (2b2)    If not set, set the DisableLoopbackCheck value to 0x1 
265      *   (2b3)                and create HKLM\SOFTWARE\OpenAFS\Client  UnsetDisableLoopbackCheck
266      *   (2c) else If cm_NetbiosName exists in the BackConnectionHostNames list,
267      *             check for the UnsetDisableLoopbackCheck value.  
268      *             If set, set the DisableLoopbackCheck flag to 0x0 
269      *             and delete the UnsetDisableLoopbackCheck value
270      *
271      * Starting in Longhorn Beta 1, an entry in the BackConnectionHostNames value will
272      * force Windows to use the loopback authentication mechanism for the specified 
273      * services.
274      */
275     HKEY hkLsa;
276     HKEY hkMSV10;
277     HKEY hkClient;
278     DWORD dwType;
279     DWORD dwSize, dwAllocSize;
280     DWORD dwValue;
281     PBYTE pHostNames = NULL, pName = NULL;
282     BOOL  bNameFound = FALSE;   
283
284     if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
285                        "SYSTEM\\CurrentControlSet\\Control\\Lsa\\MSV1_0",
286                        0,
287                        KEY_READ|KEY_WRITE,
288                        &hkMSV10) == ERROR_SUCCESS )
289     {
290         if ((RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0, 
291                              &dwType, NULL, &dwAllocSize) == ERROR_SUCCESS) &&
292             (dwType == REG_MULTI_SZ)) 
293         {
294             dwAllocSize += 1 /* in case the source string is not nul terminated */
295                 + strlen(cm_NetbiosName) + 2;
296             pHostNames = malloc(dwAllocSize);
297             dwSize = dwAllocSize;
298             if (RegQueryValueEx( hkMSV10, "BackConnectionHostNames", 0, &dwType, 
299                                  pHostNames, &dwSize) == ERROR_SUCCESS) 
300             {
301                 for (pName = pHostNames; 
302                      (pName - pHostNames < dwSize) && *pName ; 
303                      pName += strlen(pName) + 1)
304                 {
305                     if ( !stricmp(pName, cm_NetbiosName) ) {
306                         bNameFound = TRUE;
307                         break;
308                     }   
309                 }
310             }
311         }
312              
313         if ( !bNameFound ) {
314             size_t size = strlen(cm_NetbiosName) + 2;
315             if ( !pHostNames ) {
316                 pHostNames = malloc(size);
317                 pName = pHostNames;
318             }
319             StringCbCopyA(pName, size, cm_NetbiosName);
320             pName += size - 1;
321             *pName = '\0';  /* add a second nul terminator */
322
323             dwType = REG_MULTI_SZ;
324             dwSize = pName - pHostNames + 1;
325             RegSetValueEx( hkMSV10, "BackConnectionHostNames", 0, dwType, pHostNames, dwSize);
326
327             if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
328                                "SYSTEM\\CurrentControlSet\\Control\\Lsa",
329                                0,
330                                KEY_READ|KEY_WRITE,
331                                &hkLsa) == ERROR_SUCCESS )
332             {
333                 dwSize = sizeof(DWORD);
334                 if ( RegQueryValueEx( hkLsa, "DisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) != ERROR_SUCCESS ||
335                      dwValue == 0 ) {
336                     dwType = REG_DWORD;
337                     dwSize = sizeof(DWORD);
338                     dwValue = 1;
339                     RegSetValueEx( hkLsa, "DisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
340
341                     if (RegCreateKeyEx( HKEY_LOCAL_MACHINE, 
342                                         AFSREG_CLT_OPENAFS_SUBKEY,
343                                         0,
344                                         NULL,
345                                         REG_OPTION_NON_VOLATILE,
346                                         KEY_READ|KEY_WRITE,
347                                         NULL,
348                                         &hkClient,
349                                         NULL) == ERROR_SUCCESS) {
350
351                         dwType = REG_DWORD;
352                         dwSize = sizeof(DWORD);
353                         dwValue = 1;
354                         RegSetValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, dwType, (LPBYTE)&dwValue, dwSize);
355                         RegCloseKey(hkClient);
356                     }
357                     RegCloseKey(hkLsa);
358                 }
359             }
360         } else {
361             if (RegCreateKeyEx( HKEY_LOCAL_MACHINE, 
362                                 AFSREG_CLT_OPENAFS_SUBKEY,
363                                 0,
364                                 NULL,
365                                 REG_OPTION_NON_VOLATILE,
366                                 KEY_READ|KEY_WRITE,
367                                 NULL,
368                                 &hkClient,
369                                 NULL) == ERROR_SUCCESS) {
370
371                 dwSize = sizeof(DWORD);
372                 if ( RegQueryValueEx( hkClient, "RemoveDisableLoopbackCheck", 0, &dwType, (LPBYTE)&dwValue, &dwSize) == ERROR_SUCCESS &&
373                      dwValue == 1 ) {
374                     if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
375                                        "SYSTEM\\CurrentControlSet\\Control\\Lsa",
376                                        0,
377                                        KEY_READ|KEY_WRITE,
378                                        &hkLsa) == ERROR_SUCCESS )
379                     {
380                         RegDeleteValue(hkLsa, "DisableLoopbackCheck");
381                         RegCloseKey(hkLsa);
382                     }
383                 }
384                 RegDeleteValue(hkClient, "RemoveDisableLoopbackCheck");
385                 RegCloseKey(hkClient);
386             }
387         }
388         RegCloseKey(hkMSV10);
389     }
390
391     if (pHostNames)
392         free(pHostNames);
393 }
394
395
396 static void afsd_InitServerPreferences(void)
397 {
398     HKEY hkPrefs = 0;
399     DWORD dwType, dwSize;
400     DWORD dwPrefs = 0;
401     DWORD dwIndex;
402     TCHAR szHost[256];
403     DWORD dwHostSize = 256;
404     DWORD dwRank;
405     struct sockaddr_in  saddr;
406     cm_server_t       *tsp;
407
408     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
409                       AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\VLDB",
410                       0,
411                       KEY_READ|KEY_QUERY_VALUE,
412                       &hkPrefs) == ERROR_SUCCESS) {
413
414         RegQueryInfoKey( hkPrefs,
415                          NULL,  /* lpClass */
416                          NULL,  /* lpcClass */
417                          NULL,  /* lpReserved */
418                          NULL,  /* lpcSubKeys */
419                          NULL,  /* lpcMaxSubKeyLen */
420                          NULL,  /* lpcMaxClassLen */
421                          &dwPrefs, /* lpcValues */
422                          NULL,  /* lpcMaxValueNameLen */
423                          NULL,  /* lpcMaxValueLen */
424                          NULL,  /* lpcbSecurityDescriptor */
425                          NULL   /* lpftLastWriteTime */
426                          );
427
428         for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
429
430             dwSize = sizeof(DWORD);
431             dwHostSize = 256;
432
433             if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
434                               &dwType, (LPBYTE)&dwRank, &dwSize))
435             {
436                 afsi_log("RegEnumValue(hkPrefs) failed");
437                 continue;
438             }
439
440             afsi_log("VLDB Server Preference: %s = %d",szHost, dwRank);
441
442             if (isdigit(szHost[0]))
443             {
444                 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
445                     continue;
446             } else {
447                 HOSTENT *pEntry;
448                 if ((pEntry = gethostbyname (szHost)) == NULL)
449                     continue;
450
451                 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
452             }
453             saddr.sin_family = AF_INET;
454             dwRank += (rand() & 0x000f);
455
456             tsp = cm_FindServer(&saddr, CM_SERVER_VLDB);
457             if ( tsp )          /* an existing server - ref count increased */
458             {
459                 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
460
461                 /* set preferences for an existing vlserver */
462                 cm_ChangeRankCellVLServer(tsp);
463                 cm_PutServer(tsp);  /* decrease refcount */
464             }
465             else        /* add a new server without a cell */
466             {
467                 tsp = cm_NewServer(&saddr, CM_SERVER_VLDB, NULL, CM_FLAG_NOPROBE); /* refcount = 1 */
468                 tsp->ipRank = (USHORT)dwRank;
469             }
470         }
471
472         RegCloseKey(hkPrefs);
473     }
474
475     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
476                       AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\File",
477                       0,
478                       KEY_READ|KEY_QUERY_VALUE,
479                       &hkPrefs) == ERROR_SUCCESS) {
480
481         RegQueryInfoKey( hkPrefs,
482                          NULL,  /* lpClass */
483                          NULL,  /* lpcClass */
484                          NULL,  /* lpReserved */
485                          NULL,  /* lpcSubKeys */
486                          NULL,  /* lpcMaxSubKeyLen */
487                          NULL,  /* lpcMaxClassLen */
488                          &dwPrefs, /* lpcValues */
489                          NULL,  /* lpcMaxValueNameLen */
490                          NULL,  /* lpcMaxValueLen */
491                          NULL,  /* lpcbSecurityDescriptor */
492                          NULL   /* lpftLastWriteTime */
493                          );
494
495         for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
496
497             dwSize = sizeof(DWORD);
498             dwHostSize = 256;
499
500             if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
501                               &dwType, (LPBYTE)&dwRank, &dwSize))
502             {
503                 afsi_log("RegEnumValue(hkPrefs) failed");
504                 continue;
505             }
506
507             afsi_log("File Server Preference: %s = %d",szHost, dwRank);
508
509             if (isdigit(szHost[0]))
510             {
511                 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
512                     continue;
513             } else {
514                 HOSTENT *pEntry;
515                 if ((pEntry = gethostbyname (szHost)) == NULL)
516                     continue;
517
518                 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
519             }
520             saddr.sin_family = AF_INET;
521             dwRank += (rand() & 0x000f);
522
523             tsp = cm_FindServer(&saddr, CM_SERVER_FILE);
524             if ( tsp )          /* an existing server - ref count increased */
525             {
526                 tsp->ipRank = (USHORT)dwRank; /* no need to protect by mutex*/
527
528                 /* find volumes which might have RO copy 
529                 /* on server and change the ordering of 
530                  * their RO list 
531                  */
532                 cm_ChangeRankVolume(tsp);
533                 cm_PutServer(tsp);  /* decrease refcount */
534             }
535             else        /* add a new server without a cell */
536             {
537                 tsp = cm_NewServer(&saddr, CM_SERVER_FILE, NULL, CM_FLAG_NOPROBE); /* refcount = 1 */
538                 tsp->ipRank = (USHORT)dwRank;
539             }
540         }
541
542         RegCloseKey(hkPrefs);
543     }
544 }
545
546 /*
547  * AFSD Initialization
548  */
549
550 int afsd_InitCM(char **reasonP)
551 {
552     osi_uid_t debugID;
553     afs_uint64 cacheBlocks;
554     DWORD cacheSize;
555     DWORD blockSize;
556     long logChunkSize;
557     DWORD stats;
558     DWORD dwValue;
559     DWORD rx_enable_peer_stats = 0;
560     DWORD rx_enable_process_stats = 0;
561     long traceBufSize;
562     long maxcpus;
563     long ltt, ltto;
564     long rx_nojumbo;
565     long virtualCache = 0;
566     char rootCellName[256];
567     struct rx_service *serverp;
568     static struct rx_securityClass *nullServerSecurityClassp;
569     struct hostent *thp;
570     char *msgBuf;
571     char buf[1024];
572     HKEY parmKey;
573     DWORD dummyLen;
574     DWORD regType;
575     long code;
576     /*int freelanceEnabled;*/
577     WSADATA WSAjunk;
578     int i;
579     char *p, *q; 
580     int cm_noIPAddr;         /* number of client network interfaces */
581     int cm_IPAddr[CM_MAXINTERFACE_ADDR];    /* client's IP address in host order */
582     int cm_SubnetMask[CM_MAXINTERFACE_ADDR];/* client's subnet mask in host order*/
583     int cm_NetMtu[CM_MAXINTERFACE_ADDR];    /* client's MTU sizes */
584     int cm_NetFlags[CM_MAXINTERFACE_ADDR];  /* network flags */
585
586     WSAStartup(0x0101, &WSAjunk);
587
588     afsd_initUpperCaseTable();
589     init_et_to_sys_error();
590
591     /* setup osidebug server at RPC slot 1000 */
592     osi_LongToUID(1000, &debugID);
593     code = osi_InitDebug(&debugID);
594     afsi_log("osi_InitDebug code %d", code);
595
596     //  osi_LockTypeSetDefault("stat"); /* comment this out for speed */
597     if (code != 0) {
598         if (code == RPC_S_NO_PROTSEQS)
599             *reasonP = "No RPC Protocol Sequences registered.  Check HKLM\\SOFTWARE\\Microsoft\\RPC\\ClientProtocols";
600         else
601             *reasonP = "unknown error";
602         return -1;
603     }
604
605     /* who are we ? */
606     gethostname(cm_HostName, sizeof(cm_HostName));
607     afsi_log("gethostname %s", cm_HostName);
608     thp = gethostbyname(cm_HostName);
609     memcpy(&cm_HostAddr, thp->h_addr_list[0], 4);
610
611     /* seed random number generator */
612     srand(ntohl(cm_HostAddr));
613
614     /* Look up configuration parameters in Registry */
615     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
616                          0, KEY_QUERY_VALUE, &parmKey);
617     if (code != ERROR_SUCCESS) {
618         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
619                        | FORMAT_MESSAGE_ALLOCATE_BUFFER,
620                        NULL, code, 0, (LPTSTR)&msgBuf, 0, NULL);
621         StringCbPrintfA(buf, sizeof(buf),
622                          "Failure in configuration while opening Registry: %s",
623                          msgBuf);
624         osi_panic(buf, __FILE__, __LINE__);
625     }
626
627     dummyLen = sizeof(maxcpus);
628     code = RegQueryValueEx(parmKey, "MaxCPUs", NULL, NULL,
629                             (BYTE *) &maxcpus, &dummyLen);
630     if (code == ERROR_SUCCESS) {
631         HANDLE hProcess;
632         DWORD_PTR processAffinityMask, systemAffinityMask;
633
634         hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION,
635                                FALSE, GetCurrentProcessId());
636         if ( hProcess != NULL &&
637              GetProcessAffinityMask(hProcess, &processAffinityMask, &systemAffinityMask) )
638         {
639             int i, n, bits;
640             DWORD_PTR mask, newAffinityMask;
641
642 #if defined(_WIN64)
643             bits = 64;
644 #else
645             bits = 32;
646 #endif
647             for ( i=0, n=0, mask=1, newAffinityMask=0; i<bits && n<maxcpus; i++ ) {
648                 if ( processAffinityMask & mask ) {
649                     newAffinityMask |= mask;
650                     n++;
651                 }
652                 mask *= 2;
653             }
654
655             SetProcessAffinityMask(hProcess, newAffinityMask);
656             CloseHandle(hProcess);
657             afsi_log("CPU Restrictions set to %d cpu(s); %d cpu(s) available", maxcpus, n);
658         } else {
659             afsi_log("CPU Restrictions set to %d cpu(s); unable to access process information", maxcpus);
660         }
661     }
662
663     dummyLen = sizeof(TraceOption);
664     code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
665                             (BYTE *) &TraceOption, &dummyLen);
666     afsi_log("Trace Options = %lX", TraceOption);
667
668     dummyLen = sizeof(traceBufSize);
669     code = RegQueryValueEx(parmKey, "TraceBufferSize", NULL, NULL,
670                             (BYTE *) &traceBufSize, &dummyLen);
671     if (code == ERROR_SUCCESS)
672         afsi_log("Trace Buffer size %d", traceBufSize);
673     else {
674         traceBufSize = CM_CONFIGDEFAULT_TRACEBUFSIZE;
675         afsi_log("Default trace buffer size %d", traceBufSize);
676     }
677
678     /* setup and enable debug log */
679     afsd_logp = osi_LogCreate("afsd", traceBufSize);
680     afsi_log("osi_LogCreate log addr %x", PtrToUlong(afsd_logp));
681     if ((TraceOption & 0x8)
682 #ifdef DEBUG
683          || 1
684 #endif
685          ) {
686         osi_LogEnable(afsd_logp);
687     }
688     logReady = 1;
689
690     osi_Log0(afsd_logp, "Log init");
691
692     dummyLen = sizeof(cacheSize);
693     code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
694                             (BYTE *) &cacheSize, &dummyLen);
695     if (code == ERROR_SUCCESS)
696         afsi_log("Cache size %d", cacheSize);
697     else {
698         cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
699         afsi_log("Default cache size %d", cacheSize);
700     }
701
702     dummyLen = sizeof(logChunkSize);
703     code = RegQueryValueEx(parmKey, "ChunkSize", NULL, NULL,
704                             (BYTE *) &logChunkSize, &dummyLen);
705     if (code == ERROR_SUCCESS) {
706         if (logChunkSize < 12 || logChunkSize > 30) {
707             afsi_log("Invalid chunk size %d, using default",
708                       logChunkSize);
709             logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
710         }
711     } else {
712         logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
713     }
714     cm_logChunkSize = logChunkSize;
715     cm_chunkSize = 1 << logChunkSize;
716     afsi_log("Chunk size %u (%d)", cm_chunkSize, cm_logChunkSize);
717
718     dummyLen = sizeof(blockSize);
719     code = RegQueryValueEx(parmKey, "blockSize", NULL, NULL,
720                             (BYTE *) &blockSize, &dummyLen);
721     if (code == ERROR_SUCCESS) {
722         if (blockSize < 1 || 
723             (blockSize > 1024 && (blockSize % CM_CONFIGDEFAULT_BLOCKSIZE != 0))) 
724         {
725             afsi_log("Invalid block size %u specified, using default", blockSize);
726             blockSize = CM_CONFIGDEFAULT_BLOCKSIZE;
727         } else {
728             /* 
729              * if the blockSize is less than 1024 we permit the blockSize to be
730              * specified in multiples of the default blocksize
731              */
732             if (blockSize <= 1024)
733                 blockSize *= CM_CONFIGDEFAULT_BLOCKSIZE;
734         }
735     } else {
736         blockSize = CM_CONFIGDEFAULT_BLOCKSIZE;
737     }
738     if (blockSize > cm_chunkSize) {
739         afsi_log("Block size (%d) cannot be larger than Chunk size (%d).", 
740                   blockSize, cm_chunkSize);
741         blockSize = cm_chunkSize;
742     }
743     if (cm_chunkSize % blockSize != 0) {
744         afsi_log("Block size (%d) must be a factor of Chunk size (%d).",
745                   blockSize, cm_chunkSize);
746         blockSize = CM_CONFIGDEFAULT_BLOCKSIZE;
747     }
748     afsi_log("Block size %u", blockSize);
749
750     dummyLen = sizeof(numBkgD);
751     code = RegQueryValueEx(parmKey, "Daemons", NULL, NULL,
752                             (BYTE *) &numBkgD, &dummyLen);
753     if (code == ERROR_SUCCESS) {
754         if (numBkgD > CM_MAX_DAEMONS)
755             numBkgD = CM_MAX_DAEMONS;
756         afsi_log("%d background daemons", numBkgD);
757     } else {
758         numBkgD = CM_CONFIGDEFAULT_DAEMONS;
759         afsi_log("Defaulting to %d background daemons", numBkgD);
760     }
761
762     dummyLen = sizeof(numSvThreads);
763     code = RegQueryValueEx(parmKey, "ServerThreads", NULL, NULL,
764                             (BYTE *) &numSvThreads, &dummyLen);
765     if (code == ERROR_SUCCESS)
766         afsi_log("%d server threads", numSvThreads);
767     else {
768         numSvThreads = CM_CONFIGDEFAULT_SVTHREADS;
769         afsi_log("Defaulting to %d server threads", numSvThreads);
770     }
771
772     dummyLen = sizeof(stats);
773     code = RegQueryValueEx(parmKey, "Stats", NULL, NULL,
774                             (BYTE *) &stats, &dummyLen);
775     if (code == ERROR_SUCCESS)
776         afsi_log("Status cache size %d", stats);
777     else {
778         stats = CM_CONFIGDEFAULT_STATS;
779         afsi_log("Default status cache size %d", stats);
780     }
781
782     dummyLen = sizeof(ltt);
783     code = RegQueryValueEx(parmKey, "LogoffTokenTransfer", NULL, NULL,
784                             (BYTE *) &ltt, &dummyLen);
785     if (code != ERROR_SUCCESS)
786         ltt = 1;
787     smb_LogoffTokenTransfer = ltt;
788     afsi_log("Logoff token transfer %s",  (ltt ? "on" : "off"));
789
790     if (ltt) {
791         dummyLen = sizeof(ltto);
792         code = RegQueryValueEx(parmKey, "LogoffTokenTransferTimeout",
793                                 NULL, NULL, (BYTE *) &ltto, &dummyLen);
794         if (code != ERROR_SUCCESS)
795             ltto = 120;
796     } else {
797         ltto = 0;
798     }   
799     smb_LogoffTransferTimeout = ltto;
800     afsi_log("Logoff token transfer timeout %d seconds", ltto);
801
802     dummyLen = sizeof(cm_rootVolumeName);
803     code = RegQueryValueEx(parmKey, "RootVolume", NULL, NULL,
804                             cm_rootVolumeName, &dummyLen);
805     if (code == ERROR_SUCCESS)
806         afsi_log("Root volume %s", cm_rootVolumeName);
807     else {
808         StringCbCopyA(cm_rootVolumeName, sizeof(cm_rootVolumeName), "root.afs");
809         afsi_log("Default root volume name root.afs");
810     }
811
812     cm_mountRootLen = sizeof(cm_mountRoot);
813     code = RegQueryValueEx(parmKey, "MountRoot", NULL, NULL,
814                             cm_mountRoot, &cm_mountRootLen);
815     if (code == ERROR_SUCCESS) {
816         afsi_log("Mount root %s", cm_mountRoot);
817         cm_mountRootLen = (DWORD)strlen(cm_mountRoot);
818     } else {
819         StringCbCopyA(cm_mountRoot, sizeof(cm_mountRoot), "/afs");
820         cm_mountRootLen = 4;
821         /* Don't log */
822     }
823
824     dummyLen = sizeof(buf);
825     code = RegQueryValueEx(parmKey, "CachePath", NULL, &regType,
826                             buf, &dummyLen);
827     if (code == ERROR_SUCCESS && buf[0]) {
828         if (regType == REG_EXPAND_SZ) {
829             dummyLen = ExpandEnvironmentStrings(buf, cm_CachePath, sizeof(cm_CachePath));
830             if (dummyLen > sizeof(cm_CachePath)) {
831                 afsi_log("Cache path [%s] longer than %d after expanding env strings", buf, sizeof(cm_CachePath));
832                 osi_panic("CachePath too long", __FILE__, __LINE__);
833             }
834         } else {
835             StringCbCopyA(cm_CachePath, sizeof(cm_CachePath), buf);
836         }
837         afsi_log("Cache path %s", cm_CachePath);
838     } else {
839         dummyLen = ExpandEnvironmentStrings("%TEMP%\\AFSCache", cm_CachePath, sizeof(cm_CachePath));
840         if (dummyLen > sizeof(cm_CachePath)) {
841             afsi_log("Cache path [%%TEMP%%\\AFSCache] longer than %d after expanding env strings", 
842                      sizeof(cm_CachePath));
843             osi_panic("CachePath too long", __FILE__, __LINE__);
844         }
845         afsi_log("Default cache path %s", cm_CachePath);
846     }
847
848     dummyLen = sizeof(virtualCache);
849     code = RegQueryValueEx(parmKey, "NonPersistentCaching", NULL, NULL,
850                             (LPBYTE)&virtualCache, &dummyLen);
851     afsi_log("Cache type is %s", (virtualCache?"VIRTUAL":"FILE"));
852
853     if (!virtualCache) {
854         dummyLen = sizeof(cm_ValidateCache);
855         code = RegQueryValueEx(parmKey, "ValidateCache", NULL, NULL,
856                                (LPBYTE)&cm_ValidateCache, &dummyLen);
857         if ( cm_ValidateCache < 0 || cm_ValidateCache > 2 )
858             cm_ValidateCache = 1;
859         switch (cm_ValidateCache) {
860         case 0:
861             afsi_log("Cache Validation disabled");
862             break;
863         case 1:
864             afsi_log("Cache Validation on Startup");
865             break;
866         case 2:
867             afsi_log("Cache Validation on Startup and Shutdown");
868             break;
869         }
870     }
871
872     dummyLen = sizeof(traceOnPanic);
873     code = RegQueryValueEx(parmKey, "TrapOnPanic", NULL, NULL,
874                             (BYTE *) &traceOnPanic, &dummyLen);
875     if (code != ERROR_SUCCESS)
876         traceOnPanic = 1;              /* log */
877     afsi_log("Set to %s on panic", traceOnPanic ? "trap" : "not trap");
878
879     dummyLen = sizeof(reportSessionStartups);
880     code = RegQueryValueEx(parmKey, "ReportSessionStartups", NULL, NULL,
881                             (BYTE *) &reportSessionStartups, &dummyLen);
882     if (code == ERROR_SUCCESS)
883         afsi_log("Session startups %s be recorded in the Event Log",
884                   reportSessionStartups ? "will" : "will not");
885     else {
886         reportSessionStartups = 0;
887         /* Don't log */
888     }
889
890     for ( i=0; i < MAXNUMSYSNAMES; i++ ) {
891         cm_sysNameList[i] = osi_Alloc(MAXSYSNAME);
892         cm_sysNameList[i][0] = '\0';
893     }
894     cm_sysName = cm_sysNameList[0];
895
896     dummyLen = sizeof(buf);
897     code = RegQueryValueEx(parmKey, "SysName", NULL, NULL, buf, &dummyLen);
898     if (code != ERROR_SUCCESS || !buf[0]) {
899 #if defined(_IA64_)
900         StringCbCopyA(buf, sizeof(buf), "ia64_win64");
901 #elif defined(_AMD64_)
902         StringCbCopyA(buf, sizeof(buf), "amd64_win64 x86_win32 i386_w2k");
903 #else /* assume x86 32-bit */
904         StringCbCopyA(buf, sizeof(buf), "x86_win32 i386_w2k i386_nt40");
905 #endif
906     }
907     afsi_log("Sys name %s", buf); 
908
909     /* breakup buf into individual search string entries */
910     for (p = q = buf; p < buf + dummyLen; p++)
911     {
912         if (*p == '\0' || isspace(*p)) {
913             memcpy(cm_sysNameList[cm_sysNameCount],q,p-q);
914             cm_sysNameList[cm_sysNameCount][p-q] = '\0';
915             cm_sysNameCount++;
916
917             do {
918                 if (*p == '\0')
919                     goto done_sysname;
920                 p++;
921             } while (*p == '\0' || isspace(*p));
922             q = p;
923             p--;
924         }
925     }
926   done_sysname:
927     StringCbCopyA(cm_sysName, MAXSYSNAME, cm_sysNameList[0]);
928
929     dummyLen = sizeof(cryptall);
930     code = RegQueryValueEx(parmKey, "SecurityLevel", NULL, NULL,
931                             (BYTE *) &cryptall, &dummyLen);
932     if (code == ERROR_SUCCESS) {
933         afsi_log("SecurityLevel is %s", cryptall?"crypt":"clear");
934     } else {
935         cryptall = 0;
936         afsi_log("Default SecurityLevel is clear");
937     }
938
939     if (cryptall)
940         LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_ON);
941     else
942         LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_OFF);
943
944 #ifdef AFS_AFSDB_ENV
945     dummyLen = sizeof(cm_dnsEnabled);
946     code = RegQueryValueEx(parmKey, "UseDNS", NULL, NULL,
947                             (BYTE *) &cm_dnsEnabled, &dummyLen);
948     if (code == ERROR_SUCCESS) {
949         afsi_log("DNS %s be used to find AFS cell servers",
950                   cm_dnsEnabled ? "will" : "will not");
951     }       
952     else {
953         cm_dnsEnabled = 1;   /* default on */
954         afsi_log("Default to use DNS to find AFS cell servers");
955     }
956 #else /* AFS_AFSDB_ENV */
957     afsi_log("AFS not built with DNS support to find AFS cell servers");
958 #endif /* AFS_AFSDB_ENV */
959
960 #ifdef AFS_FREELANCE_CLIENT
961     dummyLen = sizeof(cm_freelanceEnabled);
962     code = RegQueryValueEx(parmKey, "FreelanceClient", NULL, NULL,
963                             (BYTE *) &cm_freelanceEnabled, &dummyLen);
964     if (code == ERROR_SUCCESS) {
965         afsi_log("Freelance client feature %s activated",
966                   cm_freelanceEnabled ? "is" : "is not");
967     }       
968     else {
969         cm_freelanceEnabled = 1;  /* default on */
970     }
971 #endif /* AFS_FREELANCE_CLIENT */
972
973     dummyLen = sizeof(smb_hideDotFiles);
974     code = RegQueryValueEx(parmKey, "HideDotFiles", NULL, NULL,
975                            (BYTE *) &smb_hideDotFiles, &dummyLen);
976     if (code != ERROR_SUCCESS) {
977         smb_hideDotFiles = 1; /* default on */
978     }
979     afsi_log("Dot files/dirs will %sbe marked hidden",
980               smb_hideDotFiles ? "" : "not ");
981
982     dummyLen = sizeof(smb_maxMpxRequests);
983     code = RegQueryValueEx(parmKey, "MaxMpxRequests", NULL, NULL,
984                            (BYTE *) &smb_maxMpxRequests, &dummyLen);
985     if (code != ERROR_SUCCESS) {
986         smb_maxMpxRequests = 50;
987     }
988     afsi_log("Maximum number of multiplexed sessions is %d", smb_maxMpxRequests);
989
990     dummyLen = sizeof(smb_maxVCPerServer);
991     code = RegQueryValueEx(parmKey, "MaxVCPerServer", NULL, NULL,
992                            (BYTE *) &smb_maxVCPerServer, &dummyLen);
993     if (code != ERROR_SUCCESS) {
994         smb_maxVCPerServer = 100;
995     }
996     afsi_log("Maximum number of VCs per server is %d", smb_maxVCPerServer);
997
998     dummyLen = sizeof(smb_authType);
999     code = RegQueryValueEx(parmKey, "SMBAuthType", NULL, NULL,
1000                             (BYTE *) &smb_authType, &dummyLen);
1001
1002     if (code != ERROR_SUCCESS || 
1003          (smb_authType != SMB_AUTH_EXTENDED && smb_authType != SMB_AUTH_NTLM && smb_authType != SMB_AUTH_NONE)) {
1004         smb_authType = SMB_AUTH_EXTENDED; /* default is to use extended authentication */
1005     }
1006     afsi_log("SMB authentication type is %s", ((smb_authType == SMB_AUTH_NONE)?"NONE":((smb_authType == SMB_AUTH_EXTENDED)?"EXTENDED":"NTLM")));
1007
1008     dummyLen = sizeof(rx_nojumbo);
1009     code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
1010                            (BYTE *) &rx_nojumbo, &dummyLen);
1011     if (code != ERROR_SUCCESS) {
1012         rx_nojumbo = 0;
1013     }
1014     if (rx_nojumbo)
1015         afsi_log("RX Jumbograms are disabled");
1016
1017     dummyLen = sizeof(rx_extraPackets);
1018     code = RegQueryValueEx(parmKey, "RxExtraPackets", NULL, NULL,
1019                            (BYTE *) &rx_extraPackets, &dummyLen);
1020     if (code != ERROR_SUCCESS) {
1021         rx_extraPackets = 120;
1022     }
1023     if (rx_extraPackets)
1024         afsi_log("RX extraPackets is %d", rx_extraPackets);
1025
1026     dummyLen = sizeof(rx_mtu);
1027     code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
1028                            (BYTE *) &rx_mtu, &dummyLen);
1029     if (code != ERROR_SUCCESS || !rx_mtu) {
1030         rx_mtu = -1;
1031     }
1032     if (rx_mtu != -1)
1033         afsi_log("RX maximum MTU is %d", rx_mtu);
1034
1035     dummyLen = sizeof(rx_enable_peer_stats);
1036     code = RegQueryValueEx(parmKey, "RxEnablePeerStats", NULL, NULL,
1037                            (BYTE *) &rx_enable_peer_stats, &dummyLen);
1038     if (code != ERROR_SUCCESS) {
1039         rx_enable_peer_stats = 0;
1040     }
1041     if (rx_enable_peer_stats)
1042         afsi_log("RX Peer Statistics gathering is enabled");
1043
1044     dummyLen = sizeof(rx_enable_process_stats);
1045     code = RegQueryValueEx(parmKey, "RxEnableProcessStats", NULL, NULL,
1046                            (BYTE *) &rx_enable_process_stats, &dummyLen);
1047     if (code != ERROR_SUCCESS) {
1048         rx_enable_process_stats = 0;
1049     }
1050     if (rx_enable_process_stats)
1051         afsi_log("RX Process Statistics gathering is enabled");
1052
1053     dummyLen = sizeof(dwValue);
1054     dwValue = 0;
1055     code = RegQueryValueEx(parmKey, "RxEnableHotThread", NULL, NULL,
1056                             (BYTE *) &dwValue, &dummyLen);
1057      if (code != ERROR_SUCCESS || dwValue != 0) {
1058          rx_EnableHotThread();
1059          afsi_log("RX Hot Thread is enabled");
1060      }
1061      else
1062          afsi_log("RX Hot Thread is disabled");
1063
1064     dummyLen = sizeof(DWORD);
1065     code = RegQueryValueEx(parmKey, "CallBackPort", NULL, NULL,
1066                            (BYTE *) &dwValue, &dummyLen);
1067     if (code == ERROR_SUCCESS) {
1068         cm_callbackport = (unsigned short) dwValue;
1069     }
1070     afsi_log("CM CallBackPort is %u", cm_callbackport);
1071
1072     dummyLen = sizeof(DWORD);
1073     code = RegQueryValueEx(parmKey, "EnableServerLocks", NULL, NULL,
1074                            (BYTE *) &dwValue, &dummyLen);
1075     if (code == ERROR_SUCCESS) {
1076         cm_enableServerLocks = (unsigned short) dwValue;
1077     } 
1078     switch (cm_enableServerLocks) {
1079     case 0:
1080         afsi_log("EnableServerLocks: never");
1081         break;
1082     case 2:
1083         afsi_log("EnableServerLocks: always");
1084         break;
1085     case 1:
1086     default:
1087         afsi_log("EnableServerLocks: server requested");
1088         break;
1089     }
1090
1091     dummyLen = sizeof(DWORD);
1092     code = RegQueryValueEx(parmKey, "DeleteReadOnly", NULL, NULL,
1093                            (BYTE *) &dwValue, &dummyLen);
1094     if (code == ERROR_SUCCESS) {
1095         cm_deleteReadOnly = (unsigned short) dwValue;
1096     } 
1097     afsi_log("CM DeleteReadOnly is %u", cm_deleteReadOnly);
1098     
1099 #ifdef USE_BPLUS
1100     dummyLen = sizeof(DWORD);
1101     code = RegQueryValueEx(parmKey, "BPlusTrees", NULL, NULL,
1102                            (BYTE *) &dwValue, &dummyLen);
1103     if (code == ERROR_SUCCESS) {
1104         cm_BPlusTrees = (unsigned short) dwValue;
1105     } 
1106     afsi_log("CM BPlusTrees is %u", cm_BPlusTrees);
1107
1108     if (cm_BPlusTrees && !cm_InitBPlusDir()) {
1109         cm_BPlusTrees = 0;
1110         afsi_log("CM BPlusTree initialization failure; disabled for this session");
1111     }
1112 #else
1113     afsi_log("CM BPlusTrees is not supported");
1114 #endif
1115
1116     if ((RegQueryValueEx( parmKey, "PrefetchExecutableExtensions", 0, 
1117                           &regType, NULL, &dummyLen) == ERROR_SUCCESS) &&
1118          (regType == REG_MULTI_SZ)) 
1119     {
1120         char * pSz;
1121         dummyLen += 3; /* in case the source string is not nul terminated */
1122         pSz = malloc(dummyLen);
1123         if ((RegQueryValueEx( parmKey, "PrefetchExecutableExtensions", 0, &regType, 
1124                              pSz, &dummyLen) == ERROR_SUCCESS) &&
1125              (regType == REG_MULTI_SZ))
1126         {
1127             int cnt;
1128             char * p;
1129
1130             for (cnt = 0, p = pSz; (p - pSz < dummyLen) && *p; cnt++, p += strlen(p) + 1);
1131
1132             smb_ExecutableExtensions = malloc(sizeof(char *) * (cnt+1));
1133
1134             for (cnt = 0, p = pSz; (p - pSz < dummyLen) && *p; cnt++, p += strlen(p) + 1)
1135             {
1136                 smb_ExecutableExtensions[cnt] = p;
1137                 afsi_log("PrefetchExecutableExtension: \"%s\"", p);
1138             }
1139             smb_ExecutableExtensions[cnt] = NULL;
1140         }
1141         
1142         if (!smb_ExecutableExtensions)
1143             free(pSz);
1144     }
1145     if (!smb_ExecutableExtensions)
1146         afsi_log("No PrefetchExecutableExtensions");
1147
1148     dummyLen = sizeof(DWORD);
1149     code = RegQueryValueEx(parmKey, "OfflineReadOnlyIsValid", NULL, NULL,
1150                            (BYTE *) &dwValue, &dummyLen);
1151     if (code == ERROR_SUCCESS) {
1152         cm_OfflineROIsValid = (unsigned short) dwValue;
1153     } 
1154     afsi_log("CM OfflineReadOnlyIsValid is %u", cm_deleteReadOnly);
1155     
1156     dummyLen = sizeof(DWORD);
1157     code = RegQueryValueEx(parmKey, "GiveUpAllCallBacks", NULL, NULL,
1158                            (BYTE *) &dwValue, &dummyLen);
1159     if (code == ERROR_SUCCESS) {
1160         cm_giveUpAllCBs = (unsigned short) dwValue;
1161     } 
1162     afsi_log("CM GiveUpAllCallBacks is %u", cm_giveUpAllCBs);
1163
1164     dummyLen = sizeof(DWORD);
1165     code = RegQueryValueEx(parmKey, "FollowBackupPath", NULL, NULL,
1166                            (BYTE *) &dwValue, &dummyLen);
1167     if (code == ERROR_SUCCESS) {
1168         cm_followBackupPath = (unsigned short) dwValue;
1169     } 
1170     afsi_log("CM FollowBackupPath is %u", cm_followBackupPath);
1171
1172     RegCloseKey (parmKey);
1173
1174     cacheBlocks = ((afs_uint64)cacheSize * 1024) / blockSize;
1175         
1176     /* get network related info */
1177     cm_noIPAddr = CM_MAXINTERFACE_ADDR;
1178     code = syscfg_GetIFInfo(&cm_noIPAddr,
1179                              cm_IPAddr, cm_SubnetMask,
1180                              cm_NetMtu, cm_NetFlags);
1181
1182     if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
1183         afsi_log("syscfg_GetIFInfo error code %d", code);
1184     else
1185         afsi_log("First Network address %x SubnetMask %x",
1186                   cm_IPAddr[0], cm_SubnetMask[0]);
1187
1188     /*
1189      * Save client configuration for GetCacheConfig requests
1190      */
1191     cm_initParams.nChunkFiles = 0;
1192     cm_initParams.nStatCaches = stats;
1193     cm_initParams.nDataCaches = (afs_uint32)(cacheBlocks > 0xFFFFFFFF ? 0xFFFFFFFF : cacheBlocks);
1194     cm_initParams.nVolumeCaches = stats/2;
1195     cm_initParams.firstChunkSize = cm_chunkSize;
1196     cm_initParams.otherChunkSize = cm_chunkSize;
1197     cm_initParams.cacheSize = cacheSize;
1198     cm_initParams.setTime = 0;
1199     cm_initParams.memCache = 1;
1200
1201     /* Ensure the AFS Netbios Name is registered to allow loopback access */
1202     configureBackConnectionHostNames();
1203
1204     /* init user daemon, and other packages */
1205     cm_InitUser();
1206
1207     cm_InitConn();
1208
1209     cm_InitServer();
1210         
1211     cm_InitIoctl();
1212         
1213     smb_InitIoctl();
1214         
1215     cm_InitCallback();
1216
1217     code = cm_InitMappedMemory(virtualCache, cm_CachePath, stats, cm_chunkSize, cacheBlocks, blockSize);
1218     afsi_log("cm_InitMappedMemory code %x", code);
1219     if (code != 0) {
1220         *reasonP = "error initializing cache file";
1221         return -1;
1222     }
1223
1224 #ifdef AFS_AFSDB_ENV
1225 #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
1226     if (cm_InitDNS(cm_dnsEnabled) == -1)
1227         cm_dnsEnabled = 0;  /* init failed, so deactivate */
1228     afsi_log("cm_InitDNS %d", cm_dnsEnabled);
1229 #endif
1230 #endif
1231
1232     /* Set RX parameters before initializing RX */
1233     if ( rx_nojumbo ) {
1234         rx_SetNoJumbo();
1235         afsi_log("rx_SetNoJumbo successful");
1236     }
1237
1238     if ( rx_mtu != -1 ) {
1239         rx_SetMaxMTU(rx_mtu);
1240         afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
1241     }
1242
1243     /* initialize RX, and tell it to listen to the callbackport, 
1244      * which is used for callback RPC messages.
1245      */
1246     code = rx_Init(htons(cm_callbackport));
1247     if (code != 0) {
1248         afsi_log("rx_Init code %x - retrying with a random port number", code);
1249         code = rx_Init(0);
1250     }
1251     afsi_log("rx_Init code %x", code);
1252     if (code != 0) {
1253         *reasonP = "afsd: failed to init rx client";
1254         return -1;
1255     }
1256
1257     /* create an unauthenticated service #1 for callbacks */
1258     nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1259     serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
1260                              RXAFSCB_ExecuteRequest);
1261     afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1262     if (serverp == NULL) {
1263         *reasonP = "unknown error";
1264         return -1;
1265     }
1266
1267     nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1268     serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
1269                              &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
1270     afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1271     if (serverp == NULL) {
1272         *reasonP = "unknown error";
1273         return -1;
1274     }
1275         
1276     /* start server threads, *not* donating this one to the pool */
1277     rx_StartServer(0);
1278     afsi_log("rx_StartServer");
1279
1280     if (rx_enable_peer_stats)
1281         rx_enablePeerRPCStats();
1282
1283     if (rx_enable_process_stats)
1284         rx_enableProcessRPCStats();
1285
1286     code = cm_GetRootCellName(rootCellName);
1287     afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s", 
1288               code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
1289     if (code != 0 && !cm_freelanceEnabled) 
1290     {
1291         *reasonP = "can't find root cell name in " AFS_CELLSERVDB;
1292         return -1;
1293     }   
1294     else if (cm_freelanceEnabled)
1295         cm_data.rootCellp = NULL;
1296
1297     if (code == 0 && !cm_freelanceEnabled) 
1298     {
1299         cm_data.rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
1300         afsi_log("cm_GetCell addr %x", PtrToUlong(cm_data.rootCellp));
1301         if (cm_data.rootCellp == NULL) 
1302         {
1303             *reasonP = "can't find root cell in " AFS_CELLSERVDB;
1304             return -1;
1305         }
1306     }
1307
1308 #ifdef AFS_FREELANCE_CLIENT
1309     if (cm_freelanceEnabled)
1310         cm_InitFreelance();
1311 #endif
1312
1313     /* Initialize the RPC server for session keys */
1314     RpcInit();
1315
1316     afsd_InitServerPreferences();
1317     return 0;
1318 }
1319
1320 int afsd_ShutdownCM(void)
1321 {
1322     cm_ReleaseSCache(cm_data.rootSCachep);
1323
1324     return 0;
1325 }
1326
1327 int afsd_InitDaemons(char **reasonP)
1328 {
1329     long code;
1330     cm_req_t req;
1331
1332     cm_InitReq(&req);
1333
1334     /* this should really be in an init daemon from here on down */
1335
1336     if (!cm_freelanceEnabled) {
1337         int attempts = 10;
1338
1339         osi_Log0(afsd_logp, "Loading Root Volume from cell");
1340         do {
1341             code = cm_GetVolumeByName(cm_data.rootCellp, cm_rootVolumeName, cm_rootUserp,
1342                                        &req, CM_GETVOL_FLAG_CREATE, &cm_data.rootVolumep);
1343             afsi_log("cm_GetVolumeByName code %x root vol %x", code,
1344                       (code ? (cm_volume_t *)-1 : cm_data.rootVolumep));
1345         } while (code && --attempts);
1346         if (code != 0) {
1347             *reasonP = "can't find root volume in root cell";
1348             return -1;
1349         }
1350     }
1351
1352     /* compute the root fid */
1353     if (!cm_freelanceEnabled) {
1354         cm_SetFid(&cm_data.rootFid, cm_data.rootCellp->cellID, cm_GetROVolumeID(cm_data.rootVolumep), 1, 1);
1355     }
1356     else
1357         cm_FakeRootFid(&cm_data.rootFid);
1358         
1359     code = cm_GetSCache(&cm_data.rootFid, &cm_data.rootSCachep, cm_rootUserp, &req);
1360     afsi_log("cm_GetSCache code %x scache %x", code,
1361              (code ? (cm_scache_t *)-1 : cm_data.rootSCachep));
1362     if (code != 0) {
1363         *reasonP = "unknown error";
1364         return -1;
1365     }
1366
1367     cm_InitDaemon(numBkgD);
1368     afsi_log("cm_InitDaemon complete");
1369
1370     return 0;
1371 }
1372
1373 int afsd_InitSMB(char **reasonP, void *aMBfunc)
1374 {
1375     HKEY parmKey;
1376     DWORD dummyLen;
1377     DWORD dwValue;
1378     DWORD code;
1379
1380     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1381                          0, KEY_QUERY_VALUE, &parmKey);
1382     if (code == ERROR_SUCCESS) {
1383         dummyLen = sizeof(DWORD);
1384         code = RegQueryValueEx(parmKey, "StoreAnsiFilenames", NULL, NULL,
1385                                 (BYTE *) &dwValue, &dummyLen);
1386         if (code == ERROR_SUCCESS)
1387             smb_StoreAnsiFilenames = dwValue ? 1 : 0;
1388         afsi_log("StoreAnsiFilenames = %d", smb_StoreAnsiFilenames);
1389
1390         dummyLen = sizeof(DWORD);
1391         code = RegQueryValueEx(parmKey, "EnableSMBAsyncStore", NULL, NULL,
1392                                 (BYTE *) &dwValue, &dummyLen);
1393         if (code == ERROR_SUCCESS)
1394             smb_AsyncStore = dwValue ? 1 : 0;
1395         afsi_log("EnableSMBAsyncStore = %d", smb_AsyncStore);
1396
1397         dummyLen = sizeof(DWORD);
1398         code = RegQueryValueEx(parmKey, "SMBAsyncStoreSize", NULL, NULL,
1399                                 (BYTE *) &dwValue, &dummyLen);
1400         if (code == ERROR_SUCCESS) {
1401             /* Should check for >= blocksize && <= chunksize && round down to multiple of blocksize */
1402             if (dwValue > cm_chunkSize)
1403                 smb_AsyncStoreSize = cm_chunkSize;
1404             else if (dwValue <  cm_data.buf_blockSize)
1405                 smb_AsyncStoreSize = cm_data.buf_blockSize;
1406             else
1407                 smb_AsyncStoreSize = (dwValue & ~(cm_data.buf_blockSize-1));
1408         } else 
1409             smb_AsyncStoreSize = CM_CONFIGDEFAULT_ASYNCSTORESIZE;
1410         afsi_log("SMBAsyncStoreSize = %d", smb_AsyncStoreSize);
1411         
1412         RegCloseKey (parmKey);
1413     }
1414
1415     /* Do this last so that we don't handle requests before init is done.
1416      * Here we initialize the SMB listener.
1417      */
1418     smb_Init(afsd_logp, smb_UseV3, numSvThreads, aMBfunc);
1419     afsi_log("smb_Init complete");
1420
1421     return 0;
1422 }
1423
1424 #ifdef ReadOnly
1425 #undef ReadOnly
1426 #endif
1427
1428 #ifdef File
1429 #undef File
1430 #endif
1431
1432 #pragma pack( push, before_imagehlp, 8 )
1433 #include <imagehlp.h>
1434 #pragma pack( pop, before_imagehlp )
1435
1436 #define MAXNAMELEN 1024
1437
1438 void afsd_printStack(HANDLE hThread, CONTEXT *c)
1439 {
1440     HANDLE hProcess = GetCurrentProcess();
1441     int frameNum;
1442 #if defined(_AMD64_)
1443     DWORD64 offset;
1444 #elif defined(_X86_)
1445     DWORD offset;
1446 #endif
1447     DWORD symOptions;
1448     char functionName[MAXNAMELEN];
1449   
1450     IMAGEHLP_MODULE Module;
1451     IMAGEHLP_LINE Line;
1452   
1453     STACKFRAME s;
1454     IMAGEHLP_SYMBOL *pSym;
1455   
1456     afsi_log_useTimestamp = 0;
1457   
1458     pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
1459   
1460     memset( &s, '\0', sizeof s );
1461     if (!SymInitialize(hProcess, NULL, 1) )
1462     {
1463         afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
1464       
1465         SymCleanup( hProcess );
1466         GlobalFree(pSym);
1467       
1468         return;
1469     }
1470   
1471     symOptions = SymGetOptions();
1472     symOptions |= SYMOPT_LOAD_LINES;
1473     symOptions &= ~SYMOPT_UNDNAME;
1474     SymSetOptions( symOptions );
1475   
1476     /*
1477      * init STACKFRAME for first call
1478      * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
1479      * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
1480      * and good riddance.
1481      */
1482 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
1483 #error The STACKFRAME initialization in afsd_printStack() for this platform
1484 #error must be properly configured
1485 #elif defined(_AMD64_)
1486     s.AddrPC.Offset = c->Rip;
1487     s.AddrPC.Mode = AddrModeFlat;
1488     s.AddrFrame.Offset = c->Rbp;
1489     s.AddrFrame.Mode = AddrModeFlat;
1490 #else
1491     s.AddrPC.Offset = c->Eip;
1492     s.AddrPC.Mode = AddrModeFlat;
1493     s.AddrFrame.Offset = c->Ebp;
1494     s.AddrFrame.Mode = AddrModeFlat;
1495 #endif
1496
1497     memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
1498     pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
1499     pSym->MaxNameLength = MAXNAMELEN;
1500   
1501     memset( &Line, '\0', sizeof Line );
1502     Line.SizeOfStruct = sizeof Line;
1503   
1504     memset( &Module, '\0', sizeof Module );
1505     Module.SizeOfStruct = sizeof Module;
1506   
1507     offset = 0;
1508   
1509     afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
1510   
1511     for ( frameNum = 0; ; ++ frameNum )
1512     {
1513         /*
1514          * get next stack frame (StackWalk(), SymFunctionTableAccess(), 
1515          * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
1516          * ERROR_NOACCESS (998), you can assume that either you are done, or
1517          * that the stack is so hosed that the next deeper frame could not be
1518          * found.
1519          */
1520         if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c, 
1521                           NULL, SymFunctionTableAccess, SymGetModuleBase, 
1522                           NULL ) )
1523             break;
1524       
1525         /* display its contents */
1526         afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
1527                  frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
1528                  s.AddrPC.Offset, s.AddrReturn.Offset,
1529                  s.AddrFrame.Offset, s.AddrStack.Offset );
1530       
1531         if ( s.AddrPC.Offset == 0 )
1532         {
1533             afsi_log("(-nosymbols- PC == 0)" );
1534         }
1535         else
1536         { 
1537             /* show procedure info from a valid PC */
1538             if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
1539             {
1540                 if ( GetLastError() != ERROR_INVALID_ADDRESS )
1541                 {
1542                     afsi_log("SymGetSymFromAddr(): errno = %lu", 
1543                              GetLastError());
1544                 }
1545             }
1546             else
1547             {
1548                 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN, 
1549                                      UNDNAME_NAME_ONLY);
1550                 afsi_log("%s", functionName );
1551
1552                 if ( offset != 0 )
1553                 {
1554                     afsi_log(" %+ld bytes", (long) offset);
1555                 }
1556             }
1557
1558             if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
1559             {
1560                 if (GetLastError() != ERROR_INVALID_ADDRESS)
1561                 {
1562                     afsi_log("Error: SymGetLineFromAddr(): errno = %lu", 
1563                              GetLastError());
1564                 }
1565             }
1566             else
1567             {
1568                 afsi_log("    Line: %s(%lu) %+ld bytes", Line.FileName, 
1569                          Line.LineNumber, offset);
1570             }
1571         }
1572       
1573         /* no return address means no deeper stackframe */
1574         if (s.AddrReturn.Offset == 0)
1575         {
1576             SetLastError(0);
1577             break;
1578         }
1579     }
1580   
1581     if (GetLastError() != 0)
1582     {
1583         afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
1584     }
1585   
1586     SymCleanup(hProcess);
1587     GlobalFree(pSym);
1588 }
1589
1590 #ifdef _DEBUG
1591 static DWORD *afsd_crtDbgBreakCurrent = NULL;
1592 static DWORD afsd_crtDbgBreaks[256];
1593 #endif
1594
1595 static EFaultRepRetVal (WINAPI *pReportFault)(LPEXCEPTION_POINTERS pep, DWORD dwMode) = NULL;
1596 static BOOL (WINAPI *pMiniDumpWriteDump)(HANDLE hProcess,DWORD ProcessId,HANDLE hFile,
1597                                   MINIDUMP_TYPE DumpType,
1598                                   PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
1599                                   PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
1600                                   PMINIDUMP_CALLBACK_INFORMATION CallbackParam) = NULL;
1601
1602
1603 static HANDLE
1604 OpenDumpFile(void)
1605 {
1606     char wd[256];
1607     DWORD code;
1608
1609     code = GetEnvironmentVariable("TEMP", wd, sizeof(wd));
1610     if ( code == 0 || code > sizeof(wd) )
1611     {
1612         if (!GetWindowsDirectory(wd, sizeof(wd)))
1613             return NULL;
1614     }
1615     StringCbCatA(wd, sizeof(wd), "\\afsd.dmp");
1616     return CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1617                             CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
1618 }
1619
1620 void 
1621 GenerateMiniDump(PEXCEPTION_POINTERS ep)
1622 {
1623         if (IsDebuggerPresent())
1624                 return;
1625
1626     if (ep == NULL) 
1627     {
1628         // Generate exception to get proper context in dump
1629         __try 
1630         {
1631             RaiseException(DBG_CONTINUE, 0, 0, NULL);
1632         } 
1633         __except(GenerateMiniDump(GetExceptionInformation()), EXCEPTION_CONTINUE_EXECUTION) 
1634         {
1635         }
1636     } 
1637     else
1638     {
1639         MINIDUMP_EXCEPTION_INFORMATION eInfo;
1640         HANDLE hFile = NULL;
1641         HMODULE hDbgHelp = NULL;
1642
1643         hDbgHelp = LoadLibrary("Dbghelp.dll");
1644         if ( hDbgHelp == NULL )
1645             return;
1646
1647         (FARPROC) pMiniDumpWriteDump = GetProcAddress(hDbgHelp, "MiniDumpWriteDump");
1648         if ( pMiniDumpWriteDump == NULL ) {
1649             FreeLibrary(hDbgHelp);
1650             return;
1651         }
1652
1653         hFile = OpenDumpFile();
1654
1655         if ( hFile ) {
1656             HKEY parmKey;
1657             DWORD dummyLen;
1658             DWORD dwValue;
1659             DWORD code;
1660             DWORD dwMiniDumpType = MiniDumpWithDataSegs;
1661
1662             code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1663                                  0, KEY_QUERY_VALUE, &parmKey);
1664             if (code == ERROR_SUCCESS) {
1665                 dummyLen = sizeof(DWORD);
1666                 code = RegQueryValueEx(parmKey, "MiniDumpType", NULL, NULL,
1667                                         (BYTE *) &dwValue, &dummyLen);
1668                 if (code == ERROR_SUCCESS)
1669                     dwMiniDumpType = dwValue;
1670                 RegCloseKey (parmKey);
1671             }
1672
1673             eInfo.ThreadId = GetCurrentThreadId();
1674             eInfo.ExceptionPointers = ep;
1675             eInfo.ClientPointers = FALSE;
1676
1677             pMiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(),
1678                                 hFile, dwMiniDumpType, ep ? &eInfo : NULL,
1679                                 NULL, NULL);
1680
1681             CloseHandle(hFile);
1682         }
1683         FreeLibrary(hDbgHelp);
1684     }
1685 }
1686
1687 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
1688 {
1689     CONTEXT context;
1690 #ifdef _DEBUG  
1691     BOOL allocRequestBrk = FALSE;
1692 #endif 
1693     HMODULE hLib = NULL;
1694   
1695     afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n", 
1696              ep->ExceptionRecord->ExceptionCode, 
1697              ep->ExceptionRecord->ExceptionAddress);
1698            
1699 #ifdef _DEBUG
1700     if (afsd_crtDbgBreakCurrent && 
1701         *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
1702     { 
1703         allocRequestBrk = TRUE;
1704         afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
1705     }
1706 #endif
1707            
1708     /* save context if we want to print the stack information */
1709     context = *ep->ContextRecord;
1710            
1711     afsd_printStack(GetCurrentThread(), &context);
1712
1713     GenerateMiniDump(ep);
1714
1715     hLib = LoadLibrary("Faultrep.dll");
1716     if ( hLib ) {
1717         (FARPROC) pReportFault = GetProcAddress(hLib, "ReportFault");
1718         if ( pReportFault )
1719             pReportFault(ep, 0);
1720         FreeLibrary(hLib);
1721     }
1722
1723     if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
1724     {
1725         afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
1726     
1727 #ifdef _DEBUG
1728         if (allocRequestBrk)
1729         {
1730             afsd_crtDbgBreakCurrent++;
1731             _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
1732         }
1733 #endif         
1734 #if defined(_X86)    
1735         ep->ContextRecord->Eip++;
1736 #endif
1737 #if defined(_AMD64_)
1738         ep->ContextRecord->Rip++;
1739 #endif
1740         return EXCEPTION_CONTINUE_EXECUTION;
1741     }
1742     else
1743     {
1744         return EXCEPTION_CONTINUE_SEARCH;
1745     }
1746 }
1747   
1748 void afsd_SetUnhandledExceptionFilter()
1749 {
1750     SetUnhandledExceptionFilter(afsd_ExceptionFilter);
1751 }
1752   
1753 #ifdef _DEBUG
1754 void afsd_DbgBreakAllocInit()
1755 {
1756     memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
1757     afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
1758 }
1759   
1760 void afsd_DbgBreakAdd(DWORD requestNumber)
1761 {
1762     int i;
1763     for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
1764         {
1765         if (afsd_crtDbgBreaks[i] == -1)
1766             {
1767             break;
1768             }
1769         }
1770     afsd_crtDbgBreaks[i] = requestNumber;
1771
1772     _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);
1773 }
1774 #endif