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