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