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