hyperthreading-bad-20040625
[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(rx_nojumbo);
554     code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
555                            (BYTE *) &rx_nojumbo, &dummyLen);
556     if (code != ERROR_SUCCESS) {
557         rx_nojumbo = 0;
558     }
559     if(rx_nojumbo)
560         afsi_log("RX Jumbograms are disabled");
561
562     dummyLen = sizeof(rx_mtu);
563     code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
564                            (BYTE *) &rx_mtu, &dummyLen);
565     if (code != ERROR_SUCCESS || !rx_mtu) {
566         rx_mtu = -1;
567     }
568     if(rx_mtu != -1)
569         afsi_log("RX maximum MTU is %d", rx_mtu);
570
571     dummyLen = sizeof(ConnDeadtimeout);
572     code = RegQueryValueEx(parmKey, "ConnDeadTimeout", NULL, NULL,
573                            (BYTE *) &ConnDeadtimeout, &dummyLen);
574     afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
575
576     dummyLen = sizeof(HardDeadtimeout);
577     code = RegQueryValueEx(parmKey, "HardDeadTimeout", NULL, NULL,
578                            (BYTE *) &HardDeadtimeout, &dummyLen);
579     afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
580
581         RegCloseKey (parmKey);
582
583     /* Call lanahelper to get Netbios name, lan adapter number and gateway flag */
584     if(SUCCEEDED(code = lana_GetUncServerNameEx(cm_NetbiosName, &lanaNum, &isGateway, LANA_NETBIOS_NAME_FULL))) {
585         LANadapter = (lanaNum == LANA_INVALID)? -1: lanaNum;
586
587         if(LANadapter != -1)
588             afsi_log("LAN adapter number %d", LANadapter);
589         else
590             afsi_log("LAN adapter number not determined");
591
592         if(isGateway)
593             afsi_log("Set for gateway service");
594
595         afsi_log("Using >%s< as SMB server name", cm_NetbiosName);
596     } else {
597         /* something went horribly wrong.  We can't proceed without a netbios name */
598         StringCbPrintfA(buf,sizeof(buf),"Netbios name could not be determined: %li", code);
599         osi_panic(buf, __FILE__, __LINE__);
600     }
601
602         /* setup early variables */
603         /* These both used to be configurable. */
604         smb_UseV3 = 1;
605     buf_bufferSize = CM_CONFIGDEFAULT_BLOCKSIZE;
606
607         /* turn from 1024 byte units into memory blocks */
608     cacheBlocks = (cacheSize * 1024) / buf_bufferSize;
609         
610         /* get network related info */
611         cm_noIPAddr = CM_MAXINTERFACE_ADDR;
612         code = syscfg_GetIFInfo(&cm_noIPAddr,
613                             cm_IPAddr, cm_SubnetMask,
614                             cm_NetMtu, cm_NetFlags);
615
616         if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
617             afsi_log("syscfg_GetIFInfo error code %d", code);
618         else
619             afsi_log("First Network address %x SubnetMask %x",
620                  cm_IPAddr[0], cm_SubnetMask[0]);
621
622         /*
623          * Save client configuration for GetCacheConfig requests
624          */
625         cm_initParams.nChunkFiles = 0;
626         cm_initParams.nStatCaches = stats;
627         cm_initParams.nDataCaches = 0;
628         cm_initParams.nVolumeCaches = 0;
629         cm_initParams.firstChunkSize = cm_chunkSize;
630         cm_initParams.otherChunkSize = cm_chunkSize;
631         cm_initParams.cacheSize = cacheSize;
632         cm_initParams.setTime = 0;
633         cm_initParams.memCache = 0;
634
635     /* Set RX parameters before initializing RX */
636     if ( rx_nojumbo ) {
637         rx_SetNoJumbo();
638         afsi_log("rx_SetNoJumbo successful");
639     }
640
641     if ( rx_mtu != -1 ) {
642         rx_SetMaxMTU(rx_mtu);
643         afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
644     }
645
646     /* Open Microsoft Firewall to allow in port 7001 */
647     {
648         HKEY hk;
649         DWORD dwDisp;
650         TCHAR* value = TEXT("7001:UDP:*:Enabled:AFS Cache Manager Callback");
651         if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, 
652                             "SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\DomainProfile\\GloballyOpenP", 
653                             0, TEXT("container"), 0, KEY_SET_VALUE, NULL, &hk, &dwDisp) == ERROR_SUCCESS)
654         {
655             RegSetValueEx (hk, TEXT("7001:UDP"), 0, REG_SZ, (PBYTE)value, sizeof(TCHAR) * (1+lstrlen(value)));
656             RegCloseKey (hk);
657         }
658         if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, 
659                             "SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\StandardProfile\\GloballyOpenP", 
660                             0, TEXT("container"), 0, KEY_SET_VALUE, NULL, &hk, &dwDisp) == ERROR_SUCCESS)
661         {
662             RegSetValueEx (hk, TEXT("7001:UDP"), 0, REG_SZ, (PBYTE)value, sizeof(TCHAR) * (1+lstrlen(value)));
663             RegCloseKey (hk);
664         }
665     }
666
667         /* initialize RX, and tell it to listen to port 7001, which is used for
668      * callback RPC messages.
669      */
670         code = rx_Init(htons(7001));
671         afsi_log("rx_Init code %x", code);
672         if (code != 0) {
673                 *reasonP = "afsd: failed to init rx client on port 7001";
674                 return -1;
675         }
676
677         /* Initialize the RPC server for session keys */
678         RpcInit();
679
680         /* create an unauthenticated service #1 for callbacks */
681         nullServerSecurityClassp = rxnull_NewServerSecurityObject();
682     serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
683                             RXAFSCB_ExecuteRequest);
684         afsi_log("rx_NewService addr %x", (int)serverp);
685         if (serverp == NULL) {
686                 *reasonP = "unknown error";
687                 return -1;
688         }
689
690         nullServerSecurityClassp = rxnull_NewServerSecurityObject();
691     serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
692                             &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
693         afsi_log("rx_NewService addr %x", (int)serverp);
694         if (serverp == NULL) {
695                 *reasonP = "unknown error";
696                 return -1;
697         }
698         
699     /* start server threads, *not* donating this one to the pool */
700     rx_StartServer(0);
701         afsi_log("rx_StartServer");
702
703         /* init user daemon, and other packages */
704         cm_InitUser();
705
706         cm_InitACLCache(2*stats);
707
708         cm_InitConn();
709
710     cm_InitCell();
711         
712     cm_InitServer();
713         
714     cm_InitVolume();
715
716     cm_InitIoctl();
717         
718     smb_InitIoctl();
719         
720     cm_InitCallback();
721         
722     cm_InitSCache(stats);
723         
724     code = cm_InitDCache(0, cacheBlocks);
725         afsi_log("cm_InitDCache code %x", code);
726         if (code != 0) {
727                 *reasonP = "error initializing cache";
728                 return -1;
729         }
730
731 #ifdef AFS_AFSDB_ENV
732 #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
733         if (cm_InitDNS(cm_dnsEnabled) == -1)
734           cm_dnsEnabled = 0;  /* init failed, so deactivate */
735         afsi_log("cm_InitDNS %d", cm_dnsEnabled);
736 #endif
737 #endif
738
739         code = cm_GetRootCellName(rootCellName);
740         afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s", 
741              code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
742         if (code != 0 && !cm_freelanceEnabled) 
743     {
744             *reasonP = "can't find root cell name in afsd.ini";
745             return -1;
746     }
747     else if (cm_freelanceEnabled)
748         cm_rootCellp = NULL;
749
750     if (code == 0 && !cm_freelanceEnabled) 
751     {
752         cm_rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
753         afsi_log("cm_GetCell addr %x", (int)cm_rootCellp);
754         if (cm_rootCellp == NULL) 
755         {
756             *reasonP = "can't find root cell in afsdcell.ini";
757             return -1;
758         }
759         }
760
761 #ifdef AFS_FREELANCE_CLIENT
762         if (cm_freelanceEnabled)
763           cm_InitFreelance();
764 #endif
765
766         return 0;
767 }
768
769 int afsd_InitDaemons(char **reasonP)
770 {
771         long code;
772         cm_req_t req;
773
774         cm_InitReq(&req);
775
776         /* this should really be in an init daemon from here on down */
777
778     if (!cm_freelanceEnabled) {
779                 osi_Log0(afsd_logp, "Loading Root Volume from cell");
780         code = cm_GetVolumeByName(cm_rootCellp, cm_rootVolumeName, cm_rootUserp,
781                                   &req, CM_FLAG_CREATE, &cm_rootVolumep);
782         afsi_log("cm_GetVolumeByName code %x root vol %x", code,
783                  (code ? (cm_volume_t *)-1 : cm_rootVolumep));
784         if (code != 0) {
785             *reasonP = "can't find root volume in root cell";
786             return -1;
787         }
788     }
789
790         /* compute the root fid */
791         if (!cm_freelanceEnabled) {
792         cm_rootFid.cell = cm_rootCellp->cellID;
793         cm_rootFid.volume = cm_GetROVolumeID(cm_rootVolumep);
794         cm_rootFid.vnode = 1;
795         cm_rootFid.unique = 1;
796         }
797         else
798         cm_FakeRootFid(&cm_rootFid);
799         
800     code = cm_GetSCache(&cm_rootFid, &cm_rootSCachep, cm_rootUserp, &req);
801         afsi_log("cm_GetSCache code %x scache %x", code,
802              (code ? (cm_scache_t *)-1 : cm_rootSCachep));
803         if (code != 0) {
804                 *reasonP = "unknown error";
805                 return -1;
806         }
807
808         cm_InitDaemon(numBkgD);
809         afsi_log("cm_InitDaemon");
810
811         return 0;
812 }
813
814 int afsd_InitSMB(char **reasonP, void *aMBfunc)
815 {
816         /* Do this last so that we don't handle requests before init is done.
817      * Here we initialize the SMB listener.
818      */
819     smb_Init(afsd_logp, cm_NetbiosName, smb_UseV3, LANadapter, numSvThreads, aMBfunc);
820     afsi_log("smb_Init");
821
822         return 0;
823 }
824
825 #ifdef ReadOnly
826 #undef ReadOnly
827 #endif
828
829 #ifdef File
830 #undef File
831 #endif
832
833 #pragma pack( push, before_imagehlp, 8 )
834 #include <imagehlp.h>
835 #pragma pack( pop, before_imagehlp )
836
837 #define MAXNAMELEN 1024
838
839 void afsd_printStack(HANDLE hThread, CONTEXT *c)
840 {
841     HANDLE hProcess = GetCurrentProcess();
842     int frameNum;
843     DWORD offset;
844     DWORD symOptions;
845     char functionName[MAXNAMELEN];
846   
847     IMAGEHLP_MODULE Module;
848     IMAGEHLP_LINE Line;
849   
850     STACKFRAME s;
851     IMAGEHLP_SYMBOL *pSym;
852   
853     afsi_log_useTimestamp = 0;
854   
855     pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
856   
857     memset( &s, '\0', sizeof s );
858     if (!SymInitialize(hProcess, NULL, 1) )
859     {
860         afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
861       
862         SymCleanup( hProcess );
863         GlobalFree(pSym);
864       
865         return;
866     }
867   
868     symOptions = SymGetOptions();
869     symOptions |= SYMOPT_LOAD_LINES;
870     symOptions &= ~SYMOPT_UNDNAME;
871     SymSetOptions( symOptions );
872   
873     /*
874      * init STACKFRAME for first call
875      * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
876      * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
877      * and good riddance.
878      */
879 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
880 #error The STACKFRAME initialization in afsd_printStack() for this platform
881 #error must be properly configured
882 #else
883     s.AddrPC.Offset = c->Eip;
884     s.AddrPC.Mode = AddrModeFlat;
885     s.AddrFrame.Offset = c->Ebp;
886     s.AddrFrame.Mode = AddrModeFlat;
887 #endif
888
889     memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
890     pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
891     pSym->MaxNameLength = MAXNAMELEN;
892   
893     memset( &Line, '\0', sizeof Line );
894     Line.SizeOfStruct = sizeof Line;
895   
896     memset( &Module, '\0', sizeof Module );
897     Module.SizeOfStruct = sizeof Module;
898   
899     offset = 0;
900   
901     afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
902   
903     for ( frameNum = 0; ; ++ frameNum )
904     {
905         /*
906          * get next stack frame (StackWalk(), SymFunctionTableAccess(), 
907          * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
908          * ERROR_NOACCESS (998), you can assume that either you are done, or
909          * that the stack is so hosed that the next deeper frame could not be
910          * found.
911          */
912         if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c, 
913                           NULL, SymFunctionTableAccess, SymGetModuleBase, 
914                           NULL ) )
915             break;
916       
917         /* display its contents */
918         afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
919                  frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
920                  s.AddrPC.Offset, s.AddrReturn.Offset,
921                  s.AddrFrame.Offset, s.AddrStack.Offset );
922       
923         if ( s.AddrPC.Offset == 0 )
924         {
925             afsi_log("(-nosymbols- PC == 0)" );
926         }
927         else
928         { 
929             /* show procedure info from a valid PC */
930             if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
931             {
932                 if ( GetLastError() != ERROR_INVALID_ADDRESS )
933                 {
934                     afsi_log("SymGetSymFromAddr(): errno = %lu", 
935                              GetLastError());
936                 }
937             }
938             else
939             {
940                 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN, 
941                                      UNDNAME_NAME_ONLY);
942                 afsi_log("%s", functionName );
943
944                 if ( offset != 0 )
945                 {
946                     afsi_log(" %+ld bytes", (long) offset);
947                 }
948             }
949
950             if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
951             {
952                 if (GetLastError() != ERROR_INVALID_ADDRESS)
953                 {
954                     afsi_log("Error: SymGetLineFromAddr(): errno = %lu", 
955                              GetLastError());
956                 }
957             }
958             else
959             {
960                 afsi_log("    Line: %s(%lu) %+ld bytes", Line.FileName, 
961                          Line.LineNumber, offset);
962             }
963         }
964       
965         /* no return address means no deeper stackframe */
966         if (s.AddrReturn.Offset == 0)
967         {
968             SetLastError(0);
969             break;
970         }
971     }
972   
973     if (GetLastError() != 0)
974     {
975         afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
976     }
977   
978     SymCleanup(hProcess);
979     GlobalFree(pSym);
980 }
981
982 #ifdef _DEBUG
983 static DWORD *afsd_crtDbgBreakCurrent = NULL;
984 static DWORD afsd_crtDbgBreaks[256];
985 #endif
986
987 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
988 {
989     CONTEXT context;
990 #ifdef _DEBUG  
991     BOOL allocRequestBrk = FALSE;
992 #endif 
993   
994     afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n", 
995              ep->ExceptionRecord->ExceptionCode, 
996              ep->ExceptionRecord->ExceptionAddress);
997            
998 #ifdef _DEBUG
999     if (afsd_crtDbgBreakCurrent && 
1000         *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
1001     { 
1002         allocRequestBrk = TRUE;
1003         afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
1004     }
1005 #endif
1006            
1007     /* save context if we want to print the stack information */
1008     context = *ep->ContextRecord;
1009            
1010     afsd_printStack(GetCurrentThread(), &context);
1011            
1012     if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
1013     {
1014         afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
1015     
1016 #ifdef _DEBUG
1017         if (allocRequestBrk)
1018         {
1019             afsd_crtDbgBreakCurrent++;
1020             _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
1021         }
1022 #endif         
1023     
1024         ep->ContextRecord->Eip++;
1025         return EXCEPTION_CONTINUE_EXECUTION;
1026     }
1027     else
1028     {
1029         return EXCEPTION_CONTINUE_SEARCH;
1030     }
1031 }
1032   
1033 void afsd_SetUnhandledExceptionFilter()
1034 {
1035     SetUnhandledExceptionFilter(afsd_ExceptionFilter);
1036 }
1037   
1038 #ifdef _DEBUG
1039 void afsd_DbgBreakAllocInit()
1040 {
1041     memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
1042     afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
1043 }
1044   
1045 void afsd_DbgBreakAdd(DWORD requestNumber)
1046 {
1047     int i;
1048     for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
1049         {
1050         if (afsd_crtDbgBreaks[i] == -1)
1051             {
1052             break;
1053             }
1054         }
1055     afsd_crtDbgBreaks[i] = requestNumber;
1056
1057     _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);
1058 }
1059 #endif