viced-deal-gracefully-with-afsconf-failure-20010924
[openafs.git] / src / viced / viced.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 /*  viced.c     - File Server main loop                                  */
11 /*                                                                       */
12 /*  Date: 5/1/85                                                         */
13 /*                                                                       */
14 /*  Function    - This routine has the initialization code for           */
15 /*                FileServer II                                          */
16 /*                                                                       */
17 /* ********************************************************************** */
18
19 #include <afsconfig.h>
20 #include <afs/param.h>
21
22 RCSID("$Header$");
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <sys/types.h>
28 #include <afs/procmgmt.h>  /* signal(), kill(), wait(), etc. */
29 #include <sys/stat.h>
30 #ifdef AFS_NT40_ENV
31 #include <fcntl.h>
32 #include <io.h>
33 #include <windows.h>
34 #include <WINNT/afsevent.h>
35 #else
36 #include <sys/file.h>
37 #include <netinet/in.h>
38 #include <netdb.h>
39 #include <sys/resource.h>
40 #include <unistd.h>     /* sysconf() */
41 #ifndef ITIMER_REAL
42 #include <sys/time.h>
43 #endif /* ITIMER_REAL */
44 #endif /* AFS_NT40_ENV */
45 #include <afs/stds.h>
46 #undef SHARED
47 #include <rx/xdr.h>
48 #include <afs/nfs.h>
49 #ifdef AFS_PTHREAD_ENV
50 #include <assert.h>
51 #else /* AFS_PTHREAD_ENV */
52 #include <afs/assert.h>
53 #endif /* AFS_PTHREAD_ENV */
54 #include <lwp.h>
55 #include <lock.h>
56 #include <afs/ptclient.h>
57 #include <afs/afsint.h>
58 #include <afs/vldbint.h>
59 #include <afs/errors.h>
60 #include <afs/ihandle.h>
61 #include <afs/vnode.h>
62 #include <afs/volume.h>
63 #include <afs/auth.h>
64 #include <afs/cellconfig.h>
65 #include <afs/acl.h>
66 #include <afs/prs_fs.h>
67 #include <rx/rx.h>
68 #include <rx/rxkad.h>
69 #include <afs/keys.h>
70 #include <afs/afs_args.h>
71 #include <afs/vlserver.h>
72 #include <afs/afsutil.h>
73 #include <afs/fileutil.h>
74 #ifndef AFS_NT40_ENV
75 #include <afs/netutils.h>
76 #endif
77 #include "viced.h"
78 #include "host.h"
79 #if defined(AFS_SGI_ENV)
80 #include "sys/schedctl.h"
81 #include "sys/lock.h"
82 #endif
83 #include <rx/rx_globals.h>
84
85
86 extern int      BreakVolumeCallBacks(), InitCallBack();
87 extern  int     LogLevel, etext;
88 extern afs_int32        BlocksSpare, PctSpare;
89
90 void            ShutDown();
91 static void     ClearXStatValues(), NewParms(), PrintCounters();
92 static void     ResetCheckDescriptors(void), ResetCheckSignal(void);
93 static int      CheckSignal();
94 static int      FiveMinuteCheckLWP(), HostCheckLWP();
95 extern  int     GetKeysFromToken();
96 extern struct rx_securityClass *rxnull_NewServerSecurityObject();
97 extern int RXAFS_ExecuteRequest();
98 extern int RXSTATS_ExecuteRequest();
99
100 int eventlog = 0, rxlog = 0;
101 FILE *debugFile;
102 FILE * console = NULL;
103
104 #ifdef AFS_NT40_ENV
105 #define AFS_QUIETFS_ENV 1
106 #define NT_OPEN_MAX    1024 /* This is an arbitrary no. we came up with for 
107                              * now. We hope this will be replaced by a more
108                              * intelligent estimate later. */
109 #endif
110
111 int     SystemId;               /* ViceID of "Administrators"*/
112 int     SystemAnyUser;          /* Viceid of "System:AnyUser" */
113 prlist  SystemAnyUserCPS;       /* CPS for "system:AnyUser */
114 int     AnonymousID = 0;        /* ViceId of "Anonymous"*/
115 prlist  AnonCPS;                /* CPS for "Anonymous"*/
116
117 struct afsconf_dir *confDir;    /* Configuration dir object */
118
119 int     restartMode = RESTART_ORDINARY;
120
121 int Testing = 0; /* for ListViceInodes */
122
123 /*
124  * Home for the performance statistics.
125  */
126 struct afs_PerfStats afs_perfstats;
127
128 extern  int     LogLevel;
129 extern  int     Statistics;
130
131 int     timeout = 30;
132 int     SawSpare;
133 int     SawPctSpare;
134 int     debuglevel = 0;
135 int     printBanner = 0;
136 int     rxJumbograms = 1; /* default is to send and receive jumbograms. */
137 afs_int32       implicitAdminRights = PRSFS_LOOKUP;     /* The ADMINISTER right is 
138                                                    already implied */
139
140 int     stack = 24;
141 int     stackSize = 24000;
142 int     fiveminutes = 300;              /* 5 minutes.  Change this for debugging only */
143 int     CurrentConnections = 0;
144 int     hostaclRefresh = 7200;          /* refresh host clients' acls every 2 hrs */
145 #if defined(AFS_SGI_ENV)
146 int     SawLock;
147 #endif
148 time_t  StartTime;
149
150 int     rxpackets = 150;        /* 100 */
151 int     nSmallVns = 400;        /* 200 */
152 int     large = 400;            /* 200 */
153 int     volcache = 400;         /* 400 */
154 int     numberofcbs = 60000;    /* 60000 */
155 int     lwps = 9;               /* 6 */
156 int     buffs = 90;             /* 70 */
157 int     novbc = 0;              /* Enable Volume Break calls */
158 int     busy_threshold = 600;
159 int     udpBufSize = 0;         /* UDP buffer size for receive*/
160
161 struct timeval  tp;
162
163 /*
164  * FileServer's name and IP address, both network byte order and
165  * host byte order.
166  */
167 #define ADDRSPERSITE 16     /* Same global is in rx/rx_user.c */
168
169 char FS_HostName[128] = "localhost";
170 afs_uint32 FS_HostAddr_NBO;
171 afs_uint32 FS_HostAddr_HBO;
172 afs_uint32 FS_HostAddrs[ADDRSPERSITE], FS_HostAddr_cnt = 0, FS_registered=0;
173 /* All addresses in FS_HostAddrs are in NBO */
174 afsUUID FS_HostUUID;
175
176 static ParseArgs();
177 static FlagMsg();
178
179 /*
180  * Home for the performance statistics.
181  */
182
183 /* DEBUG HACK */
184 static CheckDescriptors()
185 {
186 #ifndef AFS_NT40_ENV
187     struct stat status;
188     register int tsize = getdtablesize();
189     register int i;
190     for (i = 0; i<tsize; i++) {
191         if (fstat(i, &status) != -1) {
192             printf("%d: dev %x, inode %u, length %u, type/mode %x\n",
193                    i, status.st_dev, status.st_ino,
194                    status.st_size, status.st_mode);
195         }
196     }
197     fflush(stdout);
198     ResetCheckDescriptors();
199 #endif
200 } /*CheckDescriptors*/
201
202
203 #ifdef AFS_PTHREAD_ENV
204 void CheckSignal_Signal(x)       {CheckSignal(0);}
205 void ShutDown_Signal(x)          {ShutDown(0);}
206 void CheckDescriptors_Signal(x)  {CheckDescriptors(0);}
207 #else /* AFS_PTHREAD_ENV */
208 void CheckSignal_Signal(x)       {IOMGR_SoftSig(CheckSignal, 0);}
209 void ShutDown_Signal(x)          {IOMGR_SoftSig(ShutDown, 0);}
210 void CheckDescriptors_Signal(x)  {IOMGR_SoftSig(CheckDescriptors, 0);}
211 #endif /* AFS_PTHREAD_ENV */
212
213 /* check whether caller is authorized to manage RX statistics */
214 int fs_rxstat_userok(call)
215     struct rx_call *call;
216 {
217     return afsconf_SuperUser(confDir, call, (char *)0);
218 }
219
220 static void ResetCheckSignal(void)
221 {
222 #ifdef  AFS_HPUX_ENV
223     signal(SIGPOLL, CheckSignal_Signal);
224 #else
225 #ifdef AFS_NT40_ENV
226     signal(SIGUSR2, CheckSignal_Signal);
227 #else
228     signal(SIGXCPU, CheckSignal_Signal);
229 #endif
230 #endif
231 }
232
233 static void ResetCheckDescriptors(void)
234 {
235 #ifndef AFS_NT40_ENV
236     signal(SIGTERM, CheckDescriptors_Signal);
237 #endif
238 }
239
240
241 /* proc called by rxkad module to get a key */
242 static int get_key(arock, akvno, akey)
243     char *akey;
244     char *arock;
245     register afs_int32 akvno;
246
247 {
248     /* find the key */
249     static struct afsconf_key tkey;
250     register afs_int32 code;
251
252     if (!confDir) {
253         ViceLog(0, ("conf dir not open\n"));
254         return 1;
255     }
256     code = afsconf_GetKey(confDir, akvno, tkey.key);
257     if (code)
258         return code;
259     memcpy(akey, tkey.key, sizeof(tkey.key));
260     return 0;
261
262 } /*get_key*/
263
264 #ifndef AFS_NT40_ENV
265 int viced_syscall(a3, a4, a5)
266 afs_uint32 a3, a4;
267 void * a5;
268 {
269   afs_uint32 rcode;
270   void (*old)();
271         
272 #ifndef AFS_LINUX20_ENV
273   old = (void (*)())signal(SIGSYS, SIG_IGN);    
274 #endif
275   rcode = syscall (AFS_SYSCALL, 28 /* AFSCALL_CALL */, a3, a4, a5);
276 #ifndef AFS_LINUX20_ENV
277   signal(SIGSYS, old);  
278 #endif
279
280   return rcode;
281 }
282 #endif
283
284 #if !defined(AFS_NT40_ENV)
285 #include "AFS_component_version_number.c"
286 #endif /* !AFS_NT40_ENV */
287
288 main(argc, argv)
289     int argc;
290     char * argv[];
291
292 {
293     int     i;
294     afs_int32    code;
295     FILE   *file;
296     char tbuffer[32];
297     struct rx_securityClass *sc[4];
298     struct rx_service *tservice;
299 #ifdef AFS_PTHREAD_ENV
300     pthread_t parentPid, serverPid;
301     pthread_attr_t tattr;
302     AFS_SIGSET_DECL;
303 #else /* AFS_PTHREAD_ENV */
304     PROCESS parentPid, serverPid;
305 #endif /* AFS_PTHREAD_ENV */
306     struct hostent *he;
307     int minVnodesRequired;      /* min size of vnode cache */
308 #ifndef AFS_NT40_ENV
309     struct rlimit rlim;         /* max number of open file descriptors */
310 #endif
311     int curLimit;
312
313 #ifdef  AFS_AIX32_ENV
314     struct sigaction nsa;
315     
316     sigemptyset(&nsa.sa_mask);
317     nsa.sa_handler = SIG_DFL;
318     nsa.sa_flags = SA_FULLDUMP;
319     sigaction(SIGABRT, &nsa, NULL);
320     sigaction(SIGSEGV, &nsa, NULL);
321 #endif
322
323     /* Initialize dirpaths */
324     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
325 #ifdef AFS_NT40_ENV
326         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0],0);
327 #endif
328         fprintf(stderr,"%s: Unable to obtain AFS server directory.\n", argv[0]);
329         exit(2);
330     }
331
332 #ifndef AFS_QUIETFS_ENV
333     console = fopen("/dev/console","w");
334 #endif
335
336     if(ParseArgs(argc,argv)) {
337         FlagMsg();
338         exit(-1);
339     }
340
341 #ifdef AFS_PTHREAD_ENV
342     assert(pthread_mutex_init(&fileproc_glock_mutex, NULL) == 0);
343 #endif /* AFS_PTHREAD_ENV */
344
345 #ifdef AFS_SGI_VNODE_GLUE
346     if (afs_init_kernel_config(-1) <0) {
347         printf("Can't determine NUMA configuration, not starting fileserver.\n");
348         exit(1);
349     }
350 #endif
351     confDir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
352     if (!confDir) {
353         fprintf(stderr, "Unable to open config directory %s\n",
354                 AFSDIR_SERVER_ETC_DIRPATH);
355         exit(-1);
356     }
357
358     NewParms(1);
359
360     /* Open FileLog on stdout, stderr, fd 1 and fd2 (for perror), sigh. */
361     OpenLog(AFSDIR_SERVER_FILELOG_FILEPATH);
362     SetupLogSignals(); 
363
364     if (SawSpare && SawPctSpare) {
365         ViceLog(0, ("Both -spare and -pctspare specified, exiting.\n"));
366         exit(-1);
367     }
368
369 #ifdef AFS_SGI_XFS_IOPS_ENV
370     ViceLog(0, ("XFS/EFS File server starting\n"));
371 #else
372     ViceLog(0, ("File server starting\n"));
373 #endif
374
375     /* install signal handlers for controlling the fileserver process */
376     ResetCheckSignal();  /* set CheckSignal_Signal() sig handler */
377     ResetCheckDescriptors();  /* set CheckDescriptors_Signal() sig handler */
378
379 #if defined(AFS_SGI_ENV)
380     /* give this guy a non-degrading priority so help busy servers */
381     schedctl(NDPRI, 0, NDPNORMMAX);
382     if (SawLock)
383         plock(PROCLOCK);
384 #else
385 #ifndef AFS_NT40_ENV
386     nice(-5); /* TODO: */
387 #endif
388 #endif
389     assert(DInit(buffs) == 0);
390  
391 #ifdef AFS_NT40_ENV
392     if (afs_winsockInit()<0) {
393         ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
394         ViceLog(0, ("File server failed to intialize winsock.\n"));
395         exit(1);
396     }
397 #endif
398     CheckAdminName();
399
400     /* if we support more than 16 threads, then we better have the ability 
401     ** to keep open a large number of files simultaneously 
402     */
403 #if     defined(AFS_AIX_ENV) && !defined(AFS_AIX42_ENV)
404     curLimit = OPEN_MAX;        /* for pre AIX 4.2 systems */
405 #elif defined(AFS_NT40_ENV)
406     curLimit = NT_OPEN_MAX;     /* open file descriptor limit on NT */
407 #else
408
409     curLimit = 0;               /* the number of open file descriptors */
410     code     = getrlimit(RLIMIT_NOFILE, &rlim);
411     if (code == 0) {
412         curLimit      = rlim.rlim_cur;
413         rlim.rlim_cur = rlim.rlim_max;
414         code = setrlimit(RLIMIT_NOFILE, &rlim);
415         if ( code == 0 ) 
416             curLimit  = rlim.rlim_max;
417     }
418     if ( code != 0 )
419         ViceLog(0, ("Failed to increase open file limit, using default\n"));
420
421 #endif /* defined(AFS_AIX_ENV) && !defined(AFS_AIX42_ENV) */
422
423     curLimit -= 32;             /* leave a slack of 32 file descriptors */
424     if ( lwps > curLimit ) {
425         if ( curLimit > 0)
426             lwps = curLimit; 
427         else if ( lwps > 16 )
428             lwps = 16;            /* default to a maximum of 16 threads */
429         ViceLog(0, ("The system supports a max of %d open files and we are starting %d threads\n", curLimit, lwps));
430     }
431
432
433 #ifndef AFS_PTHREAD_ENV
434     assert(LWP_InitializeProcessSupport(LWP_MAX_PRIORITY - 2, &parentPid) == LWP_SUCCESS);
435 #endif /* !AFS_PTHREAD_ENV */
436
437     /* Initialize volume support */
438     if (!novbc) {
439         V_BreakVolumeCallbacks = BreakVolumeCallBacks;
440     }
441
442     /* initialize libacl routines */
443     acl_Initialize(ACL_VERSION);
444
445     /* initialize RX support */
446 #ifndef AFS_NT40_ENV
447     rxi_syscallp = viced_syscall;
448 #endif
449     rx_extraPackets = rxpackets;
450     rx_extraQuota = 4;  /* for outgoing prserver calls from R threads */
451     rx_SetBusyThreshold(busy_threshold, VBUSY);
452     rx_SetCallAbortThreshold(10);
453     rx_SetConnAbortThreshold(10);
454     stackSize = lwps * 4000;
455     if (stackSize < 32000)
456         stackSize = 32000;
457     else if (stackSize > 44000)
458         stackSize = 44000;
459 #if    defined(AFS_HPUX_ENV) || defined(AFS_SUN_ENV) || defined(AFS_SGI51_ENV)
460     rx_SetStackSize(1, stackSize);      
461 #endif
462     if ( udpBufSize )
463         rx_SetUdpBufSize(udpBufSize);/* set the UDP buffer size for receive */
464     if (rx_Init((int)htons(7000))<0) {
465         ViceLog(0, ("Cannot initialize RX\n"));
466         exit(1);
467     }
468     if (!rxJumbograms) {
469         /* Don't send and don't allow 3.4 clients to send jumbograms. */
470         rx_SetNoJumbo();
471     }
472     rx_GetIFInfo();
473     rx_SetRxDeadTime(30);
474     sc[0] = rxnull_NewServerSecurityObject();
475     sc[1] = 0; /* rxvab_NewServerSecurityObject(key1, 0) */
476     sc[2] = rxkad_NewServerSecurityObject (rxkad_clear, (char *) 0,
477                                            get_key, (char *) 0);
478     sc[3] = rxkad_NewServerSecurityObject (rxkad_crypt, (char *) 0,
479                                            get_key, (char *) 0);
480     tservice = rx_NewService
481         (/* port */ 0, /* service id */ 1, /*service name */ "AFS",
482          /* security classes */ sc, /* numb sec classes */ 4,
483          RXAFS_ExecuteRequest);
484     if (!tservice) {
485         ViceLog(0, ("Failed to initialize RX, probably two servers running.\n"));
486         exit(-1);
487     }
488     rx_SetDestroyConnProc(tservice, (char (*)()) h_FreeConnection);
489     rx_SetMinProcs(tservice, 3);
490     rx_SetMaxProcs(tservice, lwps);
491
492     tservice = rx_NewService(0,  RX_STATS_SERVICE_ID, "rpcstats", sc, 4, RXSTATS_ExecuteRequest);
493     if (!tservice) {
494         ViceLog(0, ("Failed to initialize rpc stat service.\n"));
495         exit(-1);
496     }
497     rx_SetMinProcs(tservice, 2);
498     rx_SetMaxProcs(tservice, 4);
499
500     /*
501      * Enable RX hot threads, which allows the listener thread to trade
502      * places with an idle thread and moves the context switch from listener
503      * to worker out of the critical path.
504      */
505     rx_EnableHotThread();
506
507     /* Some rx debugging */
508     if (rxlog || eventlog) {
509         debugFile = fopen("rx_dbg", "w");
510         if (rxlog) rx_debugFile = debugFile;
511         if (eventlog) rxevent_debugFile = debugFile;
512     }
513
514     h_InitHostPackage();  /* set up local cellname and realmname */
515     InitCallBack(numberofcbs);
516     ClearXStatValues();
517
518     code = InitVL();
519     if (code) {
520         ViceLog(0,("Fatal error in library initialization, exiting!!\n"));
521         exit(1);
522     }
523
524     code = InitPR();
525     if (code) {
526         ViceLog(0,("Fatal error in protection initialization, exiting!!\n"));
527         exit(1);
528     }
529
530     /* allow super users to manage RX statistics */
531     rx_SetRxStatUserOk(fs_rxstat_userok);
532
533     rx_StartServer(0);  /* now start handling requests */
534
535     /* we ensure that there is enough space in the vnode buffer to satisfy
536     ** requests from all concurrent threads. 
537     ** the maximum number of vnodes used by a single thread at any one time
538     ** is three ( "link" uses three vnodes simultaneously, one vLarge and
539     ** two vSmall for linking files and two vLarge and one vSmall for linking
540     ** files  ) : dhruba 
541     */
542     minVnodesRequired = 2 * lwps + 1;     
543     if ( minVnodesRequired > nSmallVns ) {
544         nSmallVns = minVnodesRequired;
545         ViceLog(0, ("Overriding -s command line parameter with %d\n",
546                     nSmallVns));
547     }
548     if ( minVnodesRequired > large ) {
549         large = minVnodesRequired;
550         ViceLog(0, ("Overriding -l command line parameter with %d\n", large));
551     }
552
553     /* We now do this after getting the listener up and running, so that client
554        connections don't timeout (maybe) if a file server is restarted, since it
555        will be available "real soon now".  Worry about whether we can satisfy the 
556        calls in the volume package itself.
557      */
558     if (VInitVolumePackage(fileServer,large,nSmallVns,0, volcache)) {
559         ViceLog(0, ("Shutting down: errors encountered initializing volume package\n"));
560         VShutdown();
561         exit(1);
562     }
563
564     /*
565      * We are done calling fopen/fdopen. It is safe to use a large
566      * of the file descriptor cache.
567      */
568     ih_UseLargeCache();
569
570 #ifdef AFS_PTHREAD_ENV
571     assert(pthread_attr_init(&tattr) == 0);
572     assert(pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) == 0);
573     /* Block signals in the threads */
574     AFS_SIGSET_CLEAR();
575     assert(pthread_create(&serverPid, &tattr, (void *)FiveMinuteCheckLWP, &fiveminutes) == 0);
576     assert(pthread_create(&serverPid, &tattr, (void *)HostCheckLWP, &fiveminutes) == 0);
577     AFS_SIGSET_RESTORE();
578 #else /* AFS_PTHREAD_ENV */
579     assert(LWP_CreateProcess(FiveMinuteCheckLWP, stack*1024, LWP_MAX_PRIORITY - 2,
580             &fiveminutes, "FiveMinuteChecks", &serverPid) == LWP_SUCCESS);
581             
582     assert(LWP_CreateProcess(HostCheckLWP, stack*1024, LWP_MAX_PRIORITY - 2,
583             &fiveminutes, "HostCheck", &serverPid) == LWP_SUCCESS);
584 #endif /* AFS_PTHREAD_ENV */
585
586     TM_GetTimeOfDay(&tp, 0);
587
588 #ifndef AFS_QUIETFS_ENV
589     if (console != NULL) {
590         fprintf(console, "File server has started at %s\r",
591                 afs_ctime(&tp.tv_sec, tbuffer, sizeof(tbuffer)));
592     }
593 #endif
594
595     /*
596      * Figure out the FileServer's name and primary address.
597      */
598     ViceLog(0, ("Getting FileServer name...\n"));
599     code = gethostname(FS_HostName, 64);
600     if (code) {
601         ViceLog(0, ("gethostname() failed\n"));
602     }
603     ViceLog(0, ("FileServer host name is '%s'\n", FS_HostName));
604
605     ViceLog(0, ("Getting FileServer address...\n"));
606     he = gethostbyname(FS_HostName);
607     if (!he) {
608         ViceLog(0, ("Can't find address for FileServer '%s'\n", FS_HostName));
609     }
610     else {
611         char hoststr[16];
612         memcpy(&FS_HostAddr_NBO, he->h_addr, 4);
613         afs_inet_ntoa_r(FS_HostAddr_NBO, hoststr);
614         FS_HostAddr_HBO = ntohl(FS_HostAddr_NBO);
615         ViceLog(0,("FileServer %s has address %s (0x%x or 0x%x in host byte order)\n",
616                    FS_HostName, hoststr, FS_HostAddr_NBO, FS_HostAddr_HBO));
617     }
618
619     /* Install handler to catch the shutdown signal */
620     signal(SIGQUIT, ShutDown_Signal); /* bosserver assumes SIGQUIT shutdown */
621
622     ViceLog(0,("File Server started %s",
623                afs_ctime(&tp.tv_sec, tbuffer, sizeof(tbuffer))));
624 #if FS_STATS_DETAILED
625     afs_FullPerfStats.det.epoch.tv_sec = StartTime = tp.tv_sec;
626 #endif
627 #ifdef AFS_PTHREAD_ENV
628     while(1) {
629         sleep(1000); /* long time */
630     }
631 #else /* AFS_PTHREAD_ENV */
632     assert(LWP_WaitProcess(&parentPid) == LWP_SUCCESS);
633 #endif /* AFS_PTHREAD_ENV */
634 }
635
636
637 /* This LWP does things roughly every 5 minutes */
638 static FiveMinuteCheckLWP()
639
640 {
641     static int msg  = 0;
642     char tbuffer[32];
643
644     ViceLog(1, ("Starting five minute check process\n"));
645     while (1) {
646 #ifdef AFS_PTHREAD_ENV
647         sleep(fiveminutes);
648 #else /* AFS_PTHREAD_ENV */
649         IOMGR_Sleep(fiveminutes);
650 #endif /* AFS_PTHREAD_ENV */
651
652         /* close the log so it can be removed */
653         ReOpenLog(AFSDIR_SERVER_FILELOG_FILEPATH); /* don't trunc, just append */
654         ViceLog(2, ("Cleaning up timed out callbacks\n"));
655         if(CleanupTimedOutCallBacks())
656             ViceLog(5,("Timed out callbacks deleted\n"));
657         ViceLog(2, ("Set disk usage statistics\n"));
658         VSetDiskUsage();
659         if (FS_registered == 1) Do_VLRegisterRPC();
660         if(printBanner && (++msg&1)) { /* Every 10 minutes */
661             time_t now = FT_ApproxTime();
662             if (console != NULL) {
663 #ifndef AFS_QUIETFS_ENV
664                 fprintf(console,"File server is running at %s\r",
665                         afs_ctime(&now, tbuffer, sizeof(tbuffer)));
666 #endif /* AFS_QUIETFS_ENV */
667                 ViceLog(2, ("File server is running at %s\n",
668                         afs_ctime(&now, tbuffer, sizeof(tbuffer))));
669             }
670         }
671     }
672 } /*FiveMinuteCheckLWP*/
673
674
675 /* This LWP does host checks every 5 minutes:  it should not be used for
676  * other 5 minute activities because it may be delayed by timeouts when
677  * it probes the workstations
678  */
679 static HostCheckLWP()
680
681 {
682     ViceLog(1, ("Starting Host check process\n"));
683     while(1) {
684 #ifdef AFS_PTHREAD_ENV
685         sleep(fiveminutes);
686 #else /* AFS_PTHREAD_ENV */
687         IOMGR_Sleep(fiveminutes);
688 #endif /* AFS_PTHREAD_ENV */
689         ViceLog(2, ("Checking for dead venii & clients\n"));
690         h_CheckHosts();
691     }
692 } /*HostCheckLWP*/
693
694
695 #define MAXADMINNAME 64
696 char adminName[MAXADMINNAME];
697
698 CheckAdminName()
699
700 {
701     int             fd = 0;
702     struct stat     status;
703     
704     if ((stat("/AdminName", &status)) ||        /* if file does not exist */
705         (status.st_size <= 0) ||                /* or it is too short */
706         (status.st_size >= (MAXADMINNAME)) ||   /* or it is too long */
707         !(fd = open("/AdminName", O_RDONLY, 0))) {      /* or the open fails */
708         strcpy(adminName, "System:Administrators");     /* use the default name */
709     }
710     else {
711         read(fd, adminName, status.st_size);    /* use name from the file */
712     }
713     if (fd)
714         close(fd);      /* close fd if it was opened */
715
716 } /*CheckAdminName*/
717
718
719 /*------------------------------------------------------------------------
720  * PRIVATE ClearXStatValues
721  *
722  * Description:
723  *      Initialize all of the values collected via the xstat
724  *      interface.
725  *
726  * Arguments:
727  *      None.
728  *
729  * Returns:
730  *      Nothing.
731  *
732  * Environment:
733  *      Must be called during File Server initialization.
734  *
735  * Side Effects:
736  *      As advertised.
737  *------------------------------------------------------------------------*/
738
739 static void ClearXStatValues()
740
741 { /*ClearXStatValues*/
742
743     struct fs_stats_opTimingData *opTimeP;      /*Ptr to timing struct*/
744     struct fs_stats_xferData *opXferP;          /*Ptr to xfer struct*/
745     int i;                                      /*Loop counter*/
746
747     /*
748      * Zero all xstat-related structures.
749      */
750     memset((char *)(&afs_perfstats), 0, sizeof(struct afs_PerfStats));
751 #if FS_STATS_DETAILED
752     memset((char *)(&afs_FullPerfStats), 0, sizeof(struct fs_stats_FullPerfStats));
753
754     /*
755      * That's not enough.  We have to set reasonable minima for
756      * time and xfer values in the detailed stats.
757      */
758     opTimeP = &(afs_FullPerfStats.det.rpcOpTimes[0]);
759     for (i = 0; i < FS_STATS_NUM_RPC_OPS; i++, opTimeP++)
760         opTimeP->minTime.tv_sec = 999999;
761
762     opXferP = &(afs_FullPerfStats.det.xferOpTimes[0]);
763     for (i = 0; i < FS_STATS_NUM_XFER_OPS; i++, opXferP++) {
764         opXferP->minTime.tv_sec = 999999;
765         opXferP->minBytes = 999999999;
766     }
767
768     /*
769      * There's more.  We have to set our unique system identifier, as
770      * declared in param.h.  If such a thing is not defined, we bitch
771      * and declare ourselves to be an unknown system type.
772      */
773 #ifdef SYS_NAME_ID
774     afs_perfstats.sysname_ID = SYS_NAME_ID;
775 #else
776 #ifndef AFS_NT40_ENV
777     ViceLog(0, ("Sys name ID constant not defined in param.h!!\n"));
778     ViceLog(0, ("[Choosing ``undefined'' sys name ID.\n"));
779 #endif
780     afs_perfstats.sysname_ID = SYS_NAME_ID_UNDEFINED;
781 #endif /* SYS_NAME_ID */
782 #endif
783
784 } /*ClearXStatValues*/
785
786
787 static void PrintCounters()
788
789 {
790     int dirbuff, dircall, dirio;
791     struct timeval  tpl;
792     int workstations, activeworkstations, delworkstations;
793     int processSize = 0;
794     char tbuffer[32];
795
796     TM_GetTimeOfDay(&tpl, 0);
797     Statistics = 1;
798     ViceLog(0, ("Vice was last started at %s\n",
799                 afs_ctime(&StartTime, tbuffer, sizeof(tbuffer))));
800
801     VPrintCacheStats();
802     VPrintDiskStats();
803     DStat(&dirbuff, &dircall, &dirio);
804     ViceLog(0,("With %d directory buffers; %d reads resulted in %d read I/Os\n",
805             dirbuff, dircall, dirio));
806     rx_PrintStats(stderr);
807     h_PrintStats();
808     PrintCallBackStats();
809 #ifdef AFS_NT40_ENV
810     processSize = -1; /* TODO: */
811 #else
812     processSize = (int)((long) sbrk(0) >> 10);
813 #endif
814     ViceLog(0,("There are %d connections, process size %d\n",  CurrentConnections, processSize));
815     h_GetWorkStats(&workstations, &activeworkstations, &delworkstations,
816          tpl.tv_sec-15*60);
817     ViceLog(0,
818             ("There are %d workstations, %d are active (req in < 15 mins), %d marked \"down\"\n",
819             workstations, activeworkstations, delworkstations));
820     Statistics = 0;
821
822 } /*PrintCounters*/
823
824
825
826 static CheckSignal()
827
828 {
829     if (FS_registered > 0)  {
830         /*
831          * We have proper ip addresses; tell the vlserver what we got; the following
832          * routine will do the proper reporting for us
833          */
834         Do_VLRegisterRPC();
835     }
836     h_DumpHosts();
837     h_PrintClients();
838     DumpCallBackState();
839     PrintCounters();
840     ResetCheckSignal();
841
842 } /*CheckSignal*/
843
844 void ShutDownAndCore(dopanic)
845 int dopanic;
846 {
847     time_t now = time(0);
848     char *tstr;
849     char tbuffer[32];
850
851     ViceLog(0, ("Shutting down file server at %s",
852                 afs_ctime(&now, tbuffer, sizeof(tbuffer))));
853     if (dopanic) 
854         ViceLog(0, ("ABNORMAL SHUTDOWN, see core file.\n"));
855 #ifndef AFS_QUIETFS_ENV
856     if (console != NULL) {
857         fprintf(console,"File server restart/shutdown received at %s\r",
858                 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
859     }
860 #endif
861     DFlush();
862     PrintCounters();
863
864     /* do not allows new reqests to be served from now on, all new requests
865        are returned with an error code of RX_RESTARTING ( transient failure ) */
866     rx_SetRxTranquil();                 /* dhruba */
867     VShutdown();
868
869     if (debugFile) {
870         rx_PrintStats(debugFile);
871         fflush(debugFile);
872     }
873     if (console != NULL) {
874         now = time(0);
875         if (dopanic) {
876 #ifndef AFS_QUIETFS_ENV
877             fprintf(console, "File server has terminated abnormally at %s\r",
878                     afs_ctime(&now, tbuffer, sizeof(tbuffer)));
879 #endif
880             ViceLog(0, ("File server has terminated abnormally at %s\n",
881                 afs_ctime(&now, tbuffer, sizeof(tbuffer))));
882         } else {
883 #ifndef AFS_QUIETFS_ENV
884             fprintf(console, "File server has terminated normally at %s\r",
885                     afs_ctime(&now, tbuffer, sizeof(tbuffer)));
886 #endif
887             ViceLog(0, ("File server has terminated normally at %s\n",
888                 afs_ctime(&now, tbuffer, sizeof(tbuffer))));
889         }
890     }
891
892     exit(0);
893
894 } /*ShutDown*/
895
896 void ShutDown() /* backward compatibility */
897 {
898   ShutDownAndCore(DONTPANIC);
899 }
900
901
902 static FlagMsg()
903
904 {
905     char buffer[1024];
906
907         /* default supports help flag */
908
909     strcpy(buffer, "Usage: fileserver ");
910     strcat(buffer, "[-d <debug level>] ");
911     strcat(buffer, "[-p <number of processes>] ");
912     strcat(buffer, "[-spare <number of spare blocks>] ");
913     strcat(buffer, "[-pctspare <percentage spare>] ");
914     strcat(buffer, "[-b <buffers>] ");
915     strcat(buffer, "[-l <large vnodes>] ");
916     strcat(buffer, "[-s <small vnodes>] ");
917     strcat(buffer, "[-vc <volume cachesize>] ");
918     strcat(buffer, "[-w <call back wait interval>] ");
919     strcat(buffer, "[-cb <number of call backs>] ");
920     strcat(buffer, "[-banner (print banner every 10 minutes)] ");
921     strcat(buffer, "[-novbc (whole volume cbs disabled)] ");
922     strcat(buffer, "[-implicit <admin mode bits: rlidwka>] ");
923     strcat(buffer, "[-hr <number of hours between refreshing the host cps>] ");
924     strcat(buffer, "[-busyat <redirect clients when queue > n>] ");
925     strcat(buffer, "[-rxpck <number of rx extra packets>] ");
926     strcat(buffer, "[-rxdbg (enable rx debugging)] ");
927     strcat(buffer, "[-rxdbge (enable rxevent debugging)] ");
928 #ifdef  AFS_AIX32_ENV
929     strcat(buffer, "[-m <min percentage spare in partition>] ");
930 #endif
931 #if defined(AFS_SGI_ENV)
932     strcat(buffer, "[-lock (keep fileserver from swapping)] ");
933 #endif
934     strcat(buffer, "[-L (large server conf)] ");
935     strcat(buffer, "[-S (small server conf)] ");
936     strcat(buffer, "[-k <stack size>] ");
937     strcat(buffer, "[-realm <Kerberos realm name>] ");
938     strcat(buffer, "[-udpsize <size of socket buffer in bytes>] ");
939 /*   strcat(buffer, "[-enable_peer_stats] "); */
940 /*   strcat(buffer, "[-enable_process_stats] "); */
941     strcat(buffer, "[-help]\n");
942 /*
943     ViceLog(0, ("%s", buffer));
944 */
945
946         printf("%s",buffer);
947         fflush(stdout);
948
949 } /*FlagMsg*/
950
951
952 static afs_int32 ParseRights(arights)
953     char *arights;
954 {
955     afs_int32 mode = 0;
956     int i, len;
957     char tc;
958
959     if (!arights || !strcmp(arights, "")) {
960         printf("Missing list of mode bits on -implicit option\n");
961         return -1;
962     }
963     if (!strcmp(arights, "none"))
964       mode = 0;
965     else if (!strcmp(arights, "read")) 
966       mode = PRSFS_READ | PRSFS_LOOKUP;
967     else if (!strcmp(arights, "write"))
968       mode = PRSFS_READ | PRSFS_LOOKUP | PRSFS_INSERT | 
969              PRSFS_DELETE | PRSFS_WRITE | PRSFS_LOCK;
970     else if (!strcmp(arights, "all"))
971       mode = PRSFS_READ | PRSFS_LOOKUP | PRSFS_INSERT | 
972              PRSFS_DELETE | PRSFS_WRITE | PRSFS_LOCK | PRSFS_ADMINISTER;
973     else {
974         len = strlen(arights);
975         for(i=0;i<len;i++) {
976             tc = *arights++;
977             if (tc == 'r') mode |= PRSFS_READ;
978             else if (tc == 'l') mode |= PRSFS_LOOKUP;
979             else if (tc == 'i') mode |= PRSFS_INSERT;
980             else if (tc == 'd') mode |= PRSFS_DELETE;
981             else if (tc == 'w') mode |= PRSFS_WRITE;
982             else if (tc == 'k') mode |= PRSFS_LOCK;
983             else if (tc == 'a') mode |= PRSFS_ADMINISTER;
984             else if (tc == 'A') mode |= PRSFS_USR0;
985             else if (tc == 'B') mode |= PRSFS_USR1;
986             else if (tc == 'C') mode |= PRSFS_USR2;
987             else if (tc == 'D') mode |= PRSFS_USR3;
988             else if (tc == 'E') mode |= PRSFS_USR4;
989             else if (tc == 'F') mode |= PRSFS_USR5;
990             else if (tc == 'G') mode |= PRSFS_USR6;
991             else if (tc == 'H') mode |= PRSFS_USR7;
992             else {
993                 printf("Illegal -implicit rights character '%c'.\n", tc);
994                 return -1;
995             }
996         }
997     }
998     return mode;
999 }
1000
1001 /*
1002  * Limit MAX_FILESERVER_THREAD by the system limit on the number of
1003  * pthreads (sysconf(_SC_THREAD_THREADS_MAX)), if applicable and
1004  * available.
1005  *
1006  * AIX:         sysconf() limit is real
1007  * HP-UX:       sysconf() limit is real
1008  * IRIX:        sysconf() limit is apparently NOT real -- too small
1009  * DUX:         sysconf() limit is apparently NOT real -- too big
1010  * Linux:       sysconf() limit is apparently NOT real -- too big
1011  * Solaris:     no sysconf() limit
1012  */
1013 static int
1014 max_fileserver_thread(void)
1015 {
1016 #if defined(AFS_PTHREAD_ENV)
1017 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV)
1018         long ans;
1019
1020         ans = sysconf(_SC_THREAD_THREADS_MAX);
1021         if (0 < ans && ans < MAX_FILESERVER_THREAD)
1022                 return (int) ans;
1023 #endif
1024 #endif /* defined(AFS_PTHREAD_ENV) */
1025         return MAX_FILESERVER_THREAD;
1026 }
1027
1028 static ParseArgs(argc, argv)
1029     int argc;
1030     char *argv[];
1031
1032 {
1033     int SawL=0, SawS=0, SawVC=0;
1034     int Sawrxpck = 0, Sawsmall=0, Sawlarge=0, Sawcbs=0, Sawlwps=0, Sawbufs=0;
1035     int Sawbusy=0;
1036     int i;
1037     int bufSize = 0;      /* temp variable to read in udp socket buf size*/
1038
1039     for (i = 1; i < argc; i++) {
1040         if (!strcmp(argv[i], "-d")) {
1041             debuglevel = atoi(argv[++i]);
1042             LogLevel = debuglevel;
1043         }
1044         else
1045             if (!strcmp(argv[i], "-banner")) {
1046                 printBanner = 1;
1047         } else
1048             if (!strcmp(argv[i], "-implicit")) {
1049                 implicitAdminRights = ParseRights(argv[++i]);
1050                 if (implicitAdminRights < 0) return implicitAdminRights;
1051         } else
1052             if (!strcmp(argv[i], "-L")) {
1053                 SawL = 1;
1054         } else
1055             if (!strcmp(argv[i], "-S")) {
1056                 SawS = 1;
1057         }
1058         else
1059             if (!strcmp(argv[i], "-p")) {
1060                 int lwps_max = max_fileserver_thread() - FILESERVER_HELPER_THREADS;
1061                 Sawlwps = 1;
1062                 lwps = atoi(argv[++i]);
1063                 if (lwps > lwps_max)
1064                     lwps = lwps_max;
1065                 else if (lwps < 6)
1066                     lwps = 6;
1067             }
1068         else
1069             if (!strcmp(argv[i], "-b")) {
1070                 Sawbufs = 1;
1071                 buffs = atoi(argv[++i]);
1072             }
1073         else
1074             if (!strcmp(argv[i], "-l")) {
1075                 Sawlarge = 1;
1076                 large = atoi(argv[++i]);
1077             }
1078         else
1079             if (!strcmp(argv[i], "-vc")) {
1080                 SawVC = 1;
1081                 volcache = atoi(argv[++i]);
1082             }
1083         else
1084             if (!strcmp(argv[i], "-novbc")) {
1085                 novbc = 1;
1086             }
1087         else
1088             if (!strcmp(argv[i], "-rxpck")) {
1089                 Sawrxpck = 1;
1090                 rxpackets = atoi(argv[++i]);
1091             }
1092         else
1093             if (!strcmp(argv[i], "-s")) {
1094                 Sawsmall = 1;
1095                 nSmallVns = atoi(argv[++i]);
1096             }
1097         else    
1098             if (!strcmp(argv[i], "-k"))
1099                 stack = atoi(argv[++i]);
1100 #if defined(AFS_SGI_ENV)
1101         else
1102             if (!strcmp(argv[i], "-lock")) {
1103                 SawLock = 1;
1104             }
1105 #endif
1106         else
1107             if (!strcmp(argv[i], "-spare")) {
1108                 BlocksSpare = atoi(argv[++i]);
1109                 SawSpare = 1;
1110             }
1111         else
1112             if (!strcmp(argv[i], "-pctspare")) {
1113                 PctSpare = atoi(argv[++i]);
1114                 BlocksSpare = 0;                /* has non-zero default */
1115                 SawPctSpare = 1;
1116             }
1117         else
1118             if (!strcmp(argv[i], "-w"))
1119                 fiveminutes = atoi(argv[++i]);
1120         else
1121             if (!strcmp(argv[i], "-hr")) {
1122                 int hr = atoi(argv[++i]);
1123                 if ((hr < 1) || (hr > 36)) {
1124                     printf("host acl refresh interval of %d hours is invalid; hours must be between 1 and 36\n\n",
1125                            hr);
1126                     return -1;
1127                 }                   
1128                 hostaclRefresh = hr*60*60;
1129         } else
1130             if (!strcmp(argv[i], "-rxdbg"))
1131                 rxlog = 1;
1132         else 
1133             if (!strcmp(argv[i], "-rxdbge"))
1134                 eventlog = 1;
1135         else
1136             if (!strcmp(argv[i], "-cb")) {
1137                 Sawcbs = 1;
1138                 numberofcbs = atoi(argv[++i]);
1139                 if ((numberofcbs < 10000) || (numberofcbs > 65535)) {
1140                     printf("number of cbs %d invalid; must be between 10000 and 65535\n",
1141                            numberofcbs);
1142                     return -1;
1143                 }
1144             }
1145             else
1146               if (!strcmp(argv[i], "-busyat")) {
1147                 Sawbusy = 1;
1148                 busy_threshold = atoi(argv[++i]);
1149                 if (busy_threshold < 10) {
1150                     printf("Busy threshold %d is too low, will compute default.\n",
1151                            busy_threshold);
1152                     Sawbusy = 0;
1153                 }
1154             }
1155 #ifdef  AFS_AIX32_ENV
1156         else
1157             if (!strcmp(argv[i], "-m")) {
1158                 extern int aixlow_water;
1159                  aixlow_water = atoi(argv[++i]);
1160                 if ((aixlow_water < 0) || (aixlow_water > 30)) {
1161                     printf("space reserved %d% invalid; must be between 0-30%\n", aixlow_water);
1162                     return -1;
1163                 }
1164             }
1165 #endif
1166         else
1167             if (!strcmp(argv[i], "-nojumbo")) {
1168                 rxJumbograms = 0;
1169             }
1170         else
1171             if (!strcmp(argv[i], "-realm")) {
1172                 extern char local_realm[AFS_REALM_SZ];
1173                 if (strlen(argv[++i]) >= AFS_REALM_SZ) {
1174                     printf("-realm argument must contain fewer than %d characters.\n",AFS_REALM_SZ);
1175                     return -1;
1176                 }
1177                 strncpy (local_realm, argv[i], AFS_REALM_SZ);
1178             }
1179         else
1180             if ( !strcmp(argv[i], "-udpsize")) {
1181                 if ( (i+1) >= argc ) {
1182                     printf("You have to specify -udpsize <integer value>\n");
1183                     return -1;
1184                 }
1185                 bufSize = atoi(argv[++i]);
1186                 if ( bufSize < rx_GetMinUdpBufSize() )
1187                     printf("Warning:udpsize %d is less than minimum %d; ignoring\n",
1188                                 bufSize, rx_GetMinUdpBufSize() );
1189                 else
1190                     udpBufSize = bufSize;
1191             }
1192         else
1193             if (!strcmp(argv[i], "-enable_peer_stats")) {
1194                 rx_enablePeerRPCStats();
1195             }
1196         else
1197             if (!strcmp(argv[i], "-enable_process_stats")) {
1198                 rx_enableProcessRPCStats();
1199             }
1200 #ifndef AFS_NT40_ENV
1201         else 
1202             if (strcmp(argv[i], "-syslog")==0) {
1203                 /* set syslog logging flag */
1204                 serverLogSyslog = 1;
1205             } 
1206         else 
1207             if (strncmp(argv[i], "-syslog=", 8)==0) {
1208                 serverLogSyslog = 1;
1209                 serverLogSyslogFacility = atoi(argv[i]+8);
1210             }
1211 #endif
1212         else {
1213             return(-1);
1214         }
1215     }
1216     if (SawS && SawL) {
1217         printf("Only one of -L, or -S must be specified\n");
1218         return -1;
1219     }
1220     if (SawS) {
1221         if (!Sawrxpck) rxpackets = 100;
1222         if (!Sawsmall) nSmallVns = 200;
1223         if (!Sawlarge) large = 200;
1224         if (!Sawcbs) numberofcbs = 20000;
1225         if (!Sawlwps) lwps = 6;
1226         if (!Sawbufs) buffs = 70;
1227         if (!SawVC) volcache = 200;
1228     }
1229     if (SawL) {
1230         if (!Sawrxpck) rxpackets = 200;
1231         if (!Sawsmall) nSmallVns = 600;
1232         if (!Sawlarge) large = 600;
1233         if (!Sawcbs) numberofcbs = 64000;
1234         if (!Sawlwps) lwps = 12;
1235         if (!Sawbufs) buffs = 120;
1236         if (!SawVC) volcache = 600;
1237     }
1238     if (!Sawbusy) 
1239         busy_threshold = 3*rxpackets/2;
1240
1241     return(0);
1242
1243 } /*ParseArgs*/
1244
1245
1246 #define MAXPARMS 15
1247
1248 static void NewParms(initializing)
1249     int initializing;
1250
1251 {
1252     static struct stat sbuf;
1253     register int i, fd;
1254     char *parms;
1255     char *argv[MAXPARMS];
1256     register int argc;
1257
1258     if (!(stat("/vice/file/parms",&sbuf))) {
1259         parms = (char *)malloc(sbuf.st_size);
1260         if(parms <= (char *)0) return;
1261         fd = open("parms", O_RDONLY, 0666);
1262         if(fd <= 0) {
1263             ViceLog(0, ("Open for parms failed with errno = %d\n", errno));
1264             return;
1265         }
1266
1267         i = read(fd, parms, sbuf.st_size);
1268         close(fd);
1269         if(i != sbuf.st_size) {
1270             if (i < 0 )
1271                 ViceLog(0, ("Read on parms failed with errno = %d\n", errno));
1272             else
1273                 ViceLog(0,
1274                         ("Read on parms failed; expected %d bytes but read %d\n",
1275                         sbuf.st_size, i));
1276             free(parms);
1277             return;
1278         }
1279
1280         for (i = 0;i < MAXPARMS; argv[i++] = 0 );
1281         
1282         for (argc = i = 0; i < sbuf.st_size; i++) {
1283             if ((*(parms + i) != ' ') && (*(parms + i) != '\n')){
1284                 if(argv[argc] == 0) argv[argc] = (parms+i);
1285             }
1286             else {
1287                 *(parms + i) = '\0';
1288                 if(argv[argc] != 0) {
1289                     if(++argc == MAXPARMS) break;
1290                 }
1291                 while ((*(parms + i + 1) == ' ') || (*(parms + i + 1) == '\n'))
1292                     i++;
1293             }
1294         }
1295         if(ParseArgs(argc, argv) == 0)
1296             ViceLog(0, ("Change parameters to:"));
1297         else
1298             ViceLog(0, ("Invalid parameter in:"));
1299         for(i = 0; i < argc; i++) {
1300             ViceLog(0, (" %s", argv[i]));
1301         }
1302         ViceLog(0,("\n"));
1303         free(parms);
1304     }
1305     else
1306         if(!initializing)
1307             ViceLog(0, ("Received request to change parms but no parms file exists\n"));
1308
1309 } /*NewParms*/
1310
1311
1312 /* Miscellaneous routines */
1313 Die (msg)
1314     char *msg;
1315
1316 {
1317     ViceLog (0,("%s\n", msg));
1318     assert(0);
1319
1320 } /*Die*/
1321
1322
1323 InitPR()
1324
1325 {
1326     register code;
1327
1328     /*
1329      * If this fails, it's because something major is wrong, and is not
1330      * likely to be time dependent.
1331      */
1332     code = pr_Initialize(2, AFSDIR_SERVER_ETC_DIRPATH, 0);
1333     if (code != 0) {
1334         ViceLog(0, ("Couldn't initialize protection library; code=%d.\n", code));
1335         return code; 
1336     }
1337     SystemId = SYSADMINID;
1338     SystemAnyUser = ANYUSERID;
1339     SystemAnyUserCPS.prlist_len = 0;
1340     SystemAnyUserCPS.prlist_val = (afs_int32 *)0;
1341     AnonCPS.prlist_len = 0;
1342     AnonCPS.prlist_val = (afs_int32 *)0;
1343     while (1) {
1344         code = pr_GetCPS(SystemAnyUser, &SystemAnyUserCPS);
1345         if (code != 0) {
1346             ViceLog(0,
1347                     ("Couldn't get CPS for AnyUser, will try again in 30 seconds; code=%d.\n",
1348                     code));
1349             goto sleep;
1350         }
1351         code = pr_GetCPS(ANONYMOUSID,&AnonCPS);
1352         if (code != 0) {
1353             ViceLog(0,("Couldn't get Anonymous CPS, exiting; code=%d.\n", code));
1354             return -1;
1355         }
1356         AnonymousID = ANONYMOUSID;
1357         return 0;
1358 sleep:
1359 #ifdef AFS_PTHREAD_ENV
1360         sleep(30);
1361 #else /* AFS_PTHREAD_ENV */
1362         IOMGR_Sleep(30);
1363 #endif /* AFS_PTHREAD_ENV */
1364     }
1365 } /*InitPR*/
1366
1367 struct rx_connection *serverconns[MAXSERVERS];
1368 struct ubik_client *cstruct;
1369 afs_int32 vl_Initialize(confDir)
1370 char *confDir;
1371 {   afs_int32 code, scIndex = 0, i;
1372     struct afsconf_dir *tdir;
1373     struct rx_securityClass *sc;
1374     struct afsconf_cell info;
1375
1376     tdir = afsconf_Open(confDir);
1377     if (!tdir) {
1378         ViceLog(0, ("Could not open configuration directory (%s).\n", confDir));
1379         exit(1);
1380     }
1381     code = afsconf_ClientAuth(tdir, &sc, &scIndex);
1382     if (code) {
1383         ViceLog(0, ("Could not get security object for localAuth\n"));
1384         exit(1);
1385     }
1386     code = afsconf_GetCellInfo(tdir,(char *)0, AFSCONF_VLDBSERVICE, &info);
1387     if (info.numServers > MAXSERVERS) {
1388         ViceLog(0, ("vl_Initialize: info.numServers=%d (> MAXSERVERS=%d)\n",info.numServers, MAXSERVERS));
1389         exit(1);
1390     }
1391     for (i = 0;i<info.numServers;i++) 
1392         serverconns[i] = rx_NewConnection(info.hostAddr[i].sin_addr.s_addr, info.hostAddr[i].sin_port,
1393                                           USER_SERVICE_ID, sc, scIndex);
1394     code = ubik_ClientInit(serverconns, &cstruct);
1395     if (code) {
1396         ViceLog(0, ("vl_Initialize: ubik client init failed.\n"));
1397         return code;
1398     }
1399     return 0;
1400 }
1401
1402 #define SYSIDMAGIC      0x88aabbcc
1403 #define SYSIDVERSION    1
1404
1405 ReadSysIdFile() {
1406     afs_int32 fd, nentries, i;
1407     struct versionStamp vsn;
1408     struct stat     status;
1409     afsUUID uuid;
1410
1411     if ((stat(AFSDIR_SERVER_SYSID_FILEPATH, &status)) || (status.st_size <= 0)) {
1412         ViceLog(0, ("%s: doesn't exist\n", AFSDIR_SERVER_SYSID_FILEPATH));
1413         return ENOENT;
1414     }
1415     if (!(fd = open(AFSDIR_SERVER_SYSID_FILEPATH, O_RDONLY, 0))) {
1416         ViceLog(0, ("%s: can't open (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1417         return EIO;
1418     }
1419     if ((i = read(fd, (char *)&vsn, sizeof(vsn))) != sizeof(vsn)) {
1420         ViceLog(0, ("%s: Read failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1421         return EIO;
1422     }
1423     if (vsn.magic != SYSIDMAGIC) {
1424         ViceLog(0, ("%s: wrong magic %x (we support %x)\n", AFSDIR_SERVER_SYSID_FILEPATH, vsn.magic, SYSIDMAGIC));
1425         return EIO;
1426     }
1427     if (vsn.version != SYSIDVERSION) {
1428         ViceLog(0, ("%s: wrong version %d (we support %d)\n", AFSDIR_SERVER_SYSID_FILEPATH, vsn.version, SYSIDVERSION));
1429         return EIO;
1430     }
1431     if ((i = read(fd, (char *)&uuid, sizeof(struct afsUUID))) != sizeof(struct afsUUID)) {
1432         ViceLog(0, ("%s: read of uuid failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1433         return EIO;
1434     }
1435     afs_ntohuuid(&uuid);
1436     FS_HostUUID = uuid;
1437     if ((i = read(fd, (char *)&nentries, sizeof(afs_int32))) != sizeof(afs_int32)) {
1438         ViceLog(0, ("%s: Read of entries failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1439         return EIO;
1440     }
1441     if (nentries <= 0 || nentries > ADDRSPERSITE) {
1442         ViceLog(0, ("%s: invalid num of interfaces: %d\n", AFSDIR_SERVER_SYSID_FILEPATH, nentries));
1443         return EIO;
1444     }
1445     FS_HostAddr_cnt = nentries;
1446     for (i = 0; i < nentries; i++) {
1447         if (read(fd, (char *)&FS_HostAddrs[i], sizeof(afs_int32)) != sizeof(afs_int32)) {       
1448             ViceLog(0, ("%s: Read of addresses failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1449             FS_HostAddr_cnt = 0;        /* reset it */
1450             return EIO;
1451         }
1452     }
1453     close(fd);
1454     return 0;
1455 }
1456
1457 WriteSysIdFile() {
1458     afs_int32 fd, nentries, i;
1459     struct versionStamp vsn;
1460     struct stat     status;
1461     afsUUID uuid;
1462     
1463     if (!stat(AFSDIR_SERVER_SYSID_FILEPATH, &status)) {
1464         /*
1465          * File exists; keep the old one around
1466          */
1467         renamefile(AFSDIR_SERVER_SYSID_FILEPATH, AFSDIR_SERVER_OLDSYSID_FILEPATH);      
1468     }
1469     fd = open(AFSDIR_SERVER_SYSID_FILEPATH, O_WRONLY|O_TRUNC|O_CREAT, 0666);
1470     if (fd < 1) {
1471         ViceLog(0, ("%s: can't create (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1472         return EIO;
1473     }
1474     vsn.magic = SYSIDMAGIC;
1475     vsn.version = 1;
1476     if ((i = write(fd, (char *)&vsn, sizeof(vsn))) != sizeof(vsn)) {
1477         ViceLog(0, ("%s: write failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1478         return EIO;
1479     }
1480     uuid = FS_HostUUID;
1481     afs_htonuuid(&uuid);
1482     if ((i = write(fd, (char *)&uuid, sizeof(struct afsUUID))) != sizeof(struct afsUUID)) {
1483         ViceLog(0, ("%s: write of uuid failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1484         return EIO;
1485     }
1486     if ((i = write(fd, (char *)&FS_HostAddr_cnt, sizeof(afs_int32))) != sizeof(afs_int32)) {
1487         ViceLog(0, ("%s: write of # of entries failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1488         return EIO;
1489     }
1490     for (i = 0; i < FS_HostAddr_cnt; i++) {
1491         if (write(fd, (char *)&FS_HostAddrs[i], sizeof(afs_int32)) != sizeof(afs_int32)) {      
1492             ViceLog(0, ("%s: write of addresses failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1493             return EIO;
1494         }
1495     }
1496     close(fd);
1497     return 0;
1498 }
1499
1500 /*
1501  * defect 10966 
1502  * This routine sets up the buffers for the VL_RegisterAddrs RPC. All addresses
1503  * in FS_HostAddrs[] are in NBO, while the RPC treats them as a "blob" of data
1504  * and so we need to convert each of them into HBO which is what the extra 
1505  * array called FS_HostAddrs_HBO is used here.
1506  */ 
1507 Do_VLRegisterRPC() {
1508     register int code;
1509     bulkaddrs addrs;
1510     extern int VL_RegisterAddrs();
1511     afs_uint32 FS_HostAddrs_HBO[ADDRSPERSITE];
1512     int i=0;
1513  
1514     for (i=0; i < FS_HostAddr_cnt ; i++) 
1515      FS_HostAddrs_HBO[i]=ntohl(FS_HostAddrs[i]);
1516     addrs.bulkaddrs_len = FS_HostAddr_cnt;
1517     addrs.bulkaddrs_val = (afs_uint32 *)FS_HostAddrs_HBO;
1518     code = ubik_Call(VL_RegisterAddrs, cstruct, 0, &FS_HostUUID, 0, &addrs);
1519     if (code) {
1520        if (code == VL_MULTIPADDR) {
1521           ViceLog(0, ("VL_RegisterAddrs rpc failed; The ethernet address exist on a different server; repair it\n"));
1522           ViceLog(0, ("VL_RegisterAddrs rpc failed; See VLLog for details\n"));
1523           return code;
1524        } else if (code == RXGEN_OPCODE) {
1525           ViceLog(0, ("vlserver doesn't support VL_RegisterAddrs rpc; ignored\n"));
1526           FS_registered = 2;    /* So we don't have to retry in the gc daemon */
1527        } else {
1528           ViceLog(0, ("VL_RegisterAddrs rpc failed; will retry periodically (code=%d, err=%d)\n",
1529                       code, errno));
1530        }
1531     } else {
1532        FS_registered = 2;       /* So we don't have to retry in the gc daemon */
1533        WriteSysIdFile();
1534     }
1535
1536     return 0;
1537 }
1538
1539 AddrsEqual(cnt, addr1, addr2) 
1540     int cnt;
1541     afs_int32 *addr1, *addr2; 
1542 {
1543     register int i, j;
1544
1545     for (i = 0; i < cnt; i++) {
1546         for (j = 0; j < cnt; j++) {
1547             if (addr1[i] == addr2[j]) break;
1548         }
1549         if (j == cnt) return 0;
1550     }
1551     return 1;
1552 }
1553
1554 InitVL() {
1555     int (*old)();
1556     afs_int32 code;
1557     afs_int32 cnt, i;
1558     extern int rxi_numNetAddrs;
1559     extern afs_uint32 rxi_NetAddrs[];
1560
1561     /*
1562      * If this fails, it's because something major is wrong, and is not
1563      * likely to be time dependent.
1564      */
1565     code = vl_Initialize(AFSDIR_SERVER_ETC_DIRPATH);
1566     if (code != 0) {
1567         ViceLog(0, ("Couldn't initialize protection library; code=%d.\n", code));
1568         return code;
1569     }
1570
1571     /* Read or create the sysid file and register the fileserver's
1572      * IP addresses with the vlserver.
1573      */
1574     code = ReadSysIdFile();
1575     if (code) {
1576        /* Need to create the file */
1577        ViceLog(0, ("Creating new SysID file\n")); 
1578        if (code = afs_uuid_create(&FS_HostUUID)) {
1579           ViceLog(0, ("Failed to create new uuid: %d\n", code)); 
1580           exit(1);
1581        }
1582     }
1583     /* A good sysid file exists; inform the vlserver. If any conflicts,
1584      * we always use the latest interface available as the real truth.
1585      */
1586 #ifndef AFS_NT40_ENV
1587     if(AFSDIR_SERVER_NETRESTRICT_FILEPATH || AFSDIR_SERVER_NETINFO_FILEPATH) {
1588       /*
1589        * Find addresses we are supposed to register as per the netrestrict 
1590        * and netinfo files (/usr/afs/local/NetInfo and 
1591        * /usr/afs/local/NetRestict)
1592        */
1593       char reason[1024];
1594       afs_int32 code = parseNetFiles(FS_HostAddrs,NULL, NULL,
1595                                  ADDRSPERSITE, reason,
1596                                  AFSDIR_SERVER_NETINFO_FILEPATH,
1597                                  AFSDIR_SERVER_NETRESTRICT_FILEPATH);
1598       if (code < 0) {
1599         ViceLog(0,("Can' register any valid addresses:%s\n",reason));
1600         exit(1);
1601       }
1602       FS_HostAddr_cnt = (afs_uint32) code;
1603     }
1604     else 
1605 #endif
1606     {
1607       FS_HostAddr_cnt = rx_getAllAddr(FS_HostAddrs, ADDRSPERSITE);
1608     }
1609
1610     FS_registered = 1;
1611     code = Do_VLRegisterRPC();
1612     return code;
1613