budb: Fail if afsconf_GetExtendedCellInfo does
[openafs.git] / src / budb / server.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 <afsconfig.h>
11 #include <afs/param.h>
12 #include <afs/stds.h>
13
14 #include <roken.h>
15
16 #ifdef AFS_NT40_ENV
17 #include <WINNT/afsevent.h>
18 #endif
19 #include <afs/cmd.h>
20 #include <lwp.h>
21 #include <ubik.h>
22 #include <rx/xdr.h>
23 #include <rx/rx.h>
24 #include <rx/rxkad.h>
25 #include <rx/rx_globals.h>
26 #include <afs/cellconfig.h>
27 #include <afs/bubasics.h>
28 #include <afs/afsutil.h>
29 #include <afs/com_err.h>
30 #include <afs/audit.h>
31
32 #include "budb_errs.h"
33 #include "database.h"
34 #include "error_macros.h"
35 #include "budb_internal.h"
36 #include "globals.h"
37
38 struct ubik_dbase *BU_dbase;
39 struct afsconf_dir *BU_conf;    /* for getting cell info */
40
41 int argHandler(struct cmd_syndesc *, void *);
42 int truncateDatabase(void);
43 int parseServerList(struct cmd_item *);
44
45 char lcell[MAXKTCREALMLEN];
46 afs_uint32 myHost = 0;
47 int helpOption;
48
49 /* server's global configuration information. This is exported to other
50  * files/routines
51  */
52
53 buServerConfT globalConf;
54 buServerConfP globalConfPtr = &globalConf;
55 char dbDir[AFSDIR_PATH_MAX], cellConfDir[AFSDIR_PATH_MAX];
56 /* debugging control */
57 int debugging = 0;
58
59 int rxBind = 0;
60 int lwps   = 3;
61
62 #define MINLWP  3
63 #define MAXLWP 16
64
65 #define ADDRSPERSITE 16         /* Same global is in rx/rx_user.c */
66 afs_uint32 SHostAddrs[ADDRSPERSITE];
67
68 /* check whether caller is authorized to manage RX statistics */
69 int
70 BU_rxstat_userok(struct rx_call *call)
71 {
72     return afsconf_SuperUser(BU_conf, call, NULL);
73 }
74
75 /**
76  * Return true if this name is a member of the local realm.
77  */
78 int
79 BU_IsLocalRealmMatch(void *rock, char *name, char *inst, char *cell)
80 {
81     struct afsconf_dir *dir = (struct afsconf_dir *)rock;
82     afs_int32 islocal = 0;      /* default to no */
83     int code;
84
85     code = afsconf_IsLocalRealmMatch(dir, &islocal, name, inst, cell);
86     if (code) {
87         LogError(code, "Failed local realm check; name=%s, inst=%s, cell=%s\n",
88                  name, inst, cell);
89     }
90     return islocal;
91 }
92
93 int
94 convert_cell_to_ubik(struct afsconf_cell *cellinfo, afs_uint32 *myHost,
95                      afs_uint32 *serverList)
96 {
97     int i;
98     char hostname[64];
99     struct hostent *th;
100
101     /* get this host */
102     gethostname(hostname, sizeof(hostname));
103     th = gethostbyname(hostname);
104     if (!th) {
105         printf("prserver: couldn't get address of this host.\n");
106         BUDB_EXIT(1);
107     }
108     memcpy(myHost, th->h_addr, sizeof(afs_uint32));
109
110     for (i = 0; i < cellinfo->numServers; i++)
111         /* omit my host from serverList */
112         if (cellinfo->hostAddr[i].sin_addr.s_addr != *myHost)
113             *serverList++ = cellinfo->hostAddr[i].sin_addr.s_addr;
114
115     *serverList = 0;            /* terminate list */
116     return 0;
117 }
118
119 /* MyBeforeProc
120  *      The whole purpose of MyBeforeProc is to detect
121  *      if the -help option was not within the command line.
122  *      If it were, this routine would never have been called.
123  */
124 static int
125 MyBeforeProc(struct cmd_syndesc *as, void *arock)
126 {
127     helpOption = 0;
128     return 0;
129 }
130
131 /* initializeCommands
132  *      initialize all the supported commands and their arguments
133  */
134
135 void
136 initializeArgHandler(void)
137 {
138     struct cmd_syndesc *cptr;
139
140     cmd_SetBeforeProc(MyBeforeProc, NULL);
141
142     cptr = cmd_CreateSyntax(NULL, argHandler, NULL, "Backup database server");
143
144     cmd_AddParm(cptr, "-database", CMD_SINGLE, CMD_OPTIONAL,
145                 "database directory");
146
147     cmd_AddParm(cptr, "-cellservdb", CMD_SINGLE, CMD_OPTIONAL,
148                 "cell configuration directory");
149
150     cmd_AddParm(cptr, "-resetdb", CMD_FLAG, CMD_OPTIONAL,
151                 "truncate the database");
152
153     cmd_AddParm(cptr, "-noauth", CMD_FLAG, CMD_OPTIONAL,
154                 "run without authentication");
155
156     cmd_AddParm(cptr, "-smallht", CMD_FLAG, CMD_OPTIONAL,
157                 "use small hash tables");
158
159     cmd_AddParm(cptr, "-servers", CMD_LIST, CMD_OPTIONAL,
160                 "list of ubik database servers");
161
162     cmd_AddParm(cptr, "-ubikbuffers", CMD_SINGLE, CMD_OPTIONAL,
163                 "the number of ubik buffers");
164
165     cmd_AddParm(cptr, "-auditlog", CMD_SINGLE, CMD_OPTIONAL,
166                 "audit log path");
167
168     cmd_AddParm(cptr, "-p", CMD_SINGLE, CMD_OPTIONAL,
169                 "number of processes");
170
171     cmd_AddParm(cptr, "-rxbind", CMD_FLAG, CMD_OPTIONAL,
172                 "bind the Rx socket (primary interface only)");
173
174     cmd_AddParm(cptr, "-audit-interface", CMD_SINGLE, CMD_OPTIONAL,
175                 "audit interface (file or sysvmq)");
176 }
177
178 int
179 argHandler(struct cmd_syndesc *as, void *arock)
180 {
181
182     /* globalConfPtr provides the handle for the configuration information */
183
184     /* database directory */
185     if (as->parms[0].items != 0) {
186         globalConfPtr->databaseDirectory = strdup(as->parms[0].items->data);
187         if (globalConfPtr->databaseDirectory == 0)
188             BUDB_EXIT(-1);
189     }
190
191     /* -cellservdb, cell configuration directory */
192     if (as->parms[1].items != 0) {
193         globalConfPtr->cellConfigdir = strdup(as->parms[1].items->data);
194         if (globalConfPtr->cellConfigdir == 0)
195             BUDB_EXIT(-1);
196
197         globalConfPtr->debugFlags |= DF_RECHECKNOAUTH;
198     }
199
200     /* truncate the database */
201     if (as->parms[2].items != 0)
202         truncateDatabase();
203
204     /* run without authentication */
205     if (as->parms[3].items != 0)
206         globalConfPtr->debugFlags |= DF_NOAUTH;
207
208     /* use small hash tables */
209     if (as->parms[4].items != 0)
210         globalConfPtr->debugFlags |= DF_SMALLHT;
211
212     /* user provided list of ubik database servers */
213     if (as->parms[5].items != 0)
214         parseServerList(as->parms[5].items);
215
216     /* user provided the number of ubik buffers    */
217     if (as->parms[6].items != 0)
218         ubik_nBuffers = atoi(as->parms[6].items->data);
219     else
220         ubik_nBuffers = 0;
221
222     /* param 7 (-auditlog) handled below */
223
224     /* user provided the number of threads    */
225     if (as->parms[8].items != 0) {
226         lwps = atoi(as->parms[8].items->data);
227         if (lwps > MAXLWP) {
228             printf ("Warning: '-p %d' is too big; using %d instead\n",
229                 lwps, MAXLWP);
230             lwps = MAXLWP;
231         }
232         if (lwps < MINLWP) {
233             printf ("Warning: '-p %d' is too small; using %d instead\n",
234                 lwps, MINLWP);
235             lwps = MINLWP;
236         }
237     }
238
239     /* user provided rxbind option    */
240     if (as->parms[9].items != 0) {
241         rxBind = 1;
242     }
243
244     /* -audit-interface */
245     if (as->parms[10].items != 0) {
246         char *interface = as->parms[10].items->data;
247
248         if (osi_audit_interface(interface)) {
249             printf("Invalid audit interface '%s'\n", interface);
250             BUDB_EXIT(-1);
251         }
252     }
253
254     /* -auditlog */
255     /* needs to be after -audit-interface, so we osi_audit_interface
256      * before we osi_audit_file */
257     if (as->parms[7].items != 0) {
258         char *fileName = as->parms[7].items->data;
259
260         osi_audit_file(fileName);
261     }
262
263     return 0;
264 }
265
266 /* --- */
267
268 int
269 parseServerList(struct cmd_item *itemPtr)
270 {
271     struct cmd_item *save;
272     char **serverArgs;
273     char **ptr;
274     afs_int32 nservers = 0;
275     afs_int32 code = 0;
276
277     save = itemPtr;
278
279     /* compute number of servers in the list */
280     while (itemPtr) {
281         nservers++;
282         itemPtr = itemPtr->next;
283     }
284
285     LogDebug(3, "%d servers\n", nservers);
286
287     /* now can allocate the space for the server arguments */
288     serverArgs = malloc((nservers + 2) * sizeof(char *));
289     if (serverArgs == 0)
290         ERROR(-1);
291
292     ptr = serverArgs;
293     *ptr++ = "";
294     *ptr++ = "-servers";
295
296     /* now go through and construct the list of servers */
297     itemPtr = save;
298     while (itemPtr) {
299         *ptr++ = itemPtr->data;
300         itemPtr = itemPtr->next;
301     }
302
303     code =
304         ubik_ParseServerList(nservers + 2, serverArgs, &globalConfPtr->myHost,
305                              globalConfPtr->serverList);
306     if (code)
307         ERROR(code);
308
309     /* free space for the server args */
310     free(serverArgs);
311
312   error_exit:
313     return (code);
314 }
315
316 /* truncateDatabase
317  *      truncates just the database file.
318  */
319
320 int
321 truncateDatabase(void)
322 {
323     char *path;
324     afs_int32 code = 0;
325     int fd;
326
327     asprintf(&path, "%s%s%s",
328              globalConfPtr->databaseDirectory,
329              globalConfPtr->databaseName,
330              globalConfPtr->databaseExtension);
331     if (path == NULL)
332         ERROR(-1);
333
334     fd = open(path, O_RDWR, 0755);
335     if (!fd) {
336         code = errno;
337     } else {
338         if (ftruncate(fd, 0) != 0) {
339             code = errno;
340         } else
341             close(fd);
342     }
343
344     free(path);
345
346   error_exit:
347     return (code);
348 }
349
350
351 /* --- */
352
353 #include "AFS_component_version_number.c"
354
355 int
356 main(int argc, char **argv)
357 {
358     char *whoami = argv[0];
359     char *dbNamePtr = 0;
360     struct afsconf_cell cellinfo;
361     time_t currentTime;
362     afs_int32 code = 0;
363     afs_uint32 host = ntohl(INADDR_ANY);
364
365     char  clones[MAXHOSTSPERCELL];
366
367     struct rx_service *tservice;
368     struct rx_securityClass **securityClasses;
369     afs_int32 numClasses;
370
371     extern int rx_stackSize;
372
373 #ifdef AFS_NT40_ENV
374     /* initialize winsock */
375     if (afs_winsockInit() < 0) {
376         ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
377         fprintf(stderr, "%s: Couldn't initialize winsock.\n", whoami);
378         exit(1);
379     }
380 #endif
381
382 #ifdef  AFS_AIX32_ENV
383     /*
384      * The following signal action for AIX is necessary so that in case of a
385      * crash (i.e. core is generated) we can include the user's data section
386      * in the core dump. Unfortunately, by default, only a partial core is
387      * generated which, in many cases, isn't too useful.
388      */
389     struct sigaction nsa;
390
391     sigemptyset(&nsa.sa_mask);
392     nsa.sa_handler = SIG_DFL;
393     nsa.sa_flags = SA_FULLDUMP;
394     sigaction(SIGSEGV, &nsa, NULL);
395     sigaction(SIGABRT, &nsa, NULL);
396 #endif
397     osi_audit_init();
398     osi_audit(BUDB_StartEvent, 0, AUD_END);
399
400     initialize_BUDB_error_table();
401     initializeArgHandler();
402
403     /* Initialize dirpaths */
404     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
405 #ifdef AFS_NT40_ENV
406         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
407 #endif
408         afs_com_err(whoami, errno, "; Unable to obtain AFS server directory.");
409         exit(2);
410     }
411
412     memset(globalConfPtr, 0, sizeof(*globalConfPtr));
413
414     /* set default configuration values */
415     strcpy(dbDir, AFSDIR_SERVER_DB_DIRPATH);
416     strcat(dbDir, "/");
417     globalConfPtr->databaseDirectory = dbDir;
418     globalConfPtr->databaseName = DEFAULT_DBPREFIX;
419     strcpy(cellConfDir, AFSDIR_SERVER_ETC_DIRPATH);
420     globalConfPtr->cellConfigdir = cellConfDir;
421
422     /* open the log file */
423 /*
424     globalConfPtr->log = fopen(DEFAULT_LOGNAME,"a");
425     if ( globalConfPtr->log == NULL )
426     {
427         printf("Can't open log file %s - aborting\n", DEFAULT_LOGNAME);
428         BUDB_EXIT(-1);
429     }
430 */
431
432     srandom(1);
433
434 #ifdef AFS_PTHREAD_ENV
435     SetLogThreadNumProgram( rx_GetThreadNum );
436 #endif
437
438     /* process the user supplied args */
439     helpOption = 1;
440     code = cmd_Dispatch(argc, argv);
441     if (code)
442         ERROR(code);
443
444     /* exit if there was a help option */
445     if (helpOption)
446         BUDB_EXIT(0);
447
448     /* open the log file */
449     globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
450     if (globalConfPtr->log == NULL) {
451         printf("Can't open log file %s - aborting\n",
452                AFSDIR_SERVER_BUDBLOG_FILEPATH);
453         BUDB_EXIT(-1);
454     }
455
456     /* keep log closed so can remove it */
457
458     fclose(globalConfPtr->log);
459
460     /* open the cell's configuration directory */
461     LogDebug(4, "opening %s\n", globalConfPtr->cellConfigdir);
462
463     BU_conf = afsconf_Open(globalConfPtr->cellConfigdir);
464     if (BU_conf == 0) {
465         LogError(code, "Failed getting cell info\n");
466         afs_com_err(whoami, code, "Failed getting cell info");
467         ERROR(BUDB_NOCELLS);
468     }
469
470     code = afsconf_GetLocalCell(BU_conf, lcell, sizeof(lcell));
471     if (code) {
472         LogError(0, "** Can't determine local cell name!\n");
473         ERROR(code);
474     }
475
476     if (globalConfPtr->myHost == 0) {
477         /* if user hasn't supplied a list of servers, extract server
478          * list from the cell's database
479          */
480
481         LogDebug(1, "Using server list from %s cell database.\n", lcell);
482
483         code = afsconf_GetExtendedCellInfo (BU_conf, lcell, 0, &cellinfo,
484                                             clones);
485         if (code) {
486             LogError(0, "Can't read cell information\n");
487             ERROR(code);
488         }
489
490         code =
491             convert_cell_to_ubik(&cellinfo, &globalConfPtr->myHost,
492                                  globalConfPtr->serverList);
493         if (code)
494             ERROR(code);
495     }
496
497     /* initialize audit user check */
498     osi_audit_set_user_check(BU_conf, BU_IsLocalRealmMatch);
499
500     /* initialize ubik */
501     ubik_SetClientSecurityProcs(afsconf_ClientAuth, afsconf_UpToDate, BU_conf);
502     ubik_SetServerSecurityProcs(afsconf_BuildServerSecurityObjects,
503                                 afsconf_CheckAuth, BU_conf);
504
505     if (ubik_nBuffers == 0)
506         ubik_nBuffers = 400;
507
508     LogError(0, "Will allocate %d ubik buffers\n", ubik_nBuffers);
509
510     asprintf(&dbNamePtr, "%s%s", globalConfPtr->databaseDirectory,
511              globalConfPtr->databaseName);
512     if (dbNamePtr == 0)
513         ERROR(-1);
514
515     rx_SetRxDeadTime(60);       /* 60 seconds inactive before timeout */
516
517     if (rxBind) {
518         afs_int32 ccode;
519         if (AFSDIR_SERVER_NETRESTRICT_FILEPATH ||
520             AFSDIR_SERVER_NETINFO_FILEPATH) {
521             char reason[1024];
522             ccode = afsconf_ParseNetFiles(SHostAddrs, NULL, NULL,
523                                           ADDRSPERSITE, reason,
524                                           AFSDIR_SERVER_NETINFO_FILEPATH,
525                                           AFSDIR_SERVER_NETRESTRICT_FILEPATH);
526         } else
527         {
528             ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
529         }
530         if (ccode == 1) {
531             host = SHostAddrs[0];
532             rx_InitHost(host, htons(AFSCONF_BUDBPORT));
533         }
534     }
535
536     /* Disable jumbograms */
537     rx_SetNoJumbo();
538
539     code = ubik_ServerInitByInfo (globalConfPtr->myHost,
540                                   htons(AFSCONF_BUDBPORT),
541                                   &cellinfo,
542                                   clones,
543                                   dbNamePtr,           /* name prefix */
544                                   &BU_dbase);
545
546     if (code) {
547         LogError(code, "Ubik init failed\n");
548         afs_com_err(whoami, code, "Ubik init failed");
549         ERROR(code);
550     }
551
552     afsconf_BuildServerSecurityObjects(BU_conf, &securityClasses, &numClasses);
553
554     tservice =
555         rx_NewServiceHost(host, 0, BUDB_SERVICE, "BackupDatabase",
556                           securityClasses, numClasses, BUDB_ExecuteRequest);
557
558     if (tservice == (struct rx_service *)0) {
559         LogError(0, "Could not create backup database rx service\n");
560         printf("Could not create backup database rx service\n");
561         BUDB_EXIT(3);
562     }
563     rx_SetMinProcs(tservice, 1);
564     rx_SetMaxProcs(tservice, lwps);
565     rx_SetStackSize(tservice, 10000);
566
567     /* allow super users to manage RX statistics */
568     rx_SetRxStatUserOk(BU_rxstat_userok);
569
570     /* misc. initialization */
571
572     /* database dump synchronization */
573     memset(dumpSyncPtr, 0, sizeof(*dumpSyncPtr));
574     Lock_Init(&dumpSyncPtr->ds_lock);
575
576     rx_StartServer(0);          /* start handling requests */
577
578     code = InitProcs();
579     if (code)
580         ERROR(code);
581
582
583     currentTime = time(0);
584     LogError(0, "Ready to process requests at %s\n", ctime(&currentTime));
585
586     rx_ServerProc(NULL);                /* donate this LWP */
587
588   error_exit:
589     osi_audit(BUDB_FinishEvent, code, AUD_END);
590     return (code);
591 }
592
593 void
594 consistencyCheckDb(void)
595 {
596     /* do consistency checks on structure sizes */
597     if ((sizeof(struct htBlock) > BLOCKSIZE)
598         || (sizeof(struct vfBlock) > BLOCKSIZE)
599         || (sizeof(struct viBlock) > BLOCKSIZE)
600         || (sizeof(struct dBlock) > BLOCKSIZE)
601         || (sizeof(struct tBlock) > BLOCKSIZE)
602         ) {
603         fprintf(stderr, "Block layout error!\n");
604         BUDB_EXIT(99);
605     }
606 }
607
608 void
609 LogDebug(int level, char *fmt, ... )
610 {
611     va_list ap;
612
613     va_start(ap, fmt);
614
615     if (debugging >= level) {
616         /* log normally closed so can remove it */
617         globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
618         if (globalConfPtr->log != NULL) {
619             vfprintf(globalConfPtr->log, fmt, ap);
620             fflush(globalConfPtr->log);
621             fclose(globalConfPtr->log);
622         }
623     }
624     va_end(ap);
625 }
626
627 static char *
628 TimeStamp(time_t t)
629 {
630     struct tm *lt;
631     static char timestamp[20];
632
633     lt = localtime(&t);
634     strftime(timestamp, 20, "%m/%d/%Y %H:%M:%S", lt);
635     return timestamp;
636 }
637
638 void
639 Log(char *fmt, ...)
640 {
641     va_list ap;
642     time_t now;
643
644     va_start(ap, fmt);
645     globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
646     if (globalConfPtr->log != NULL) {
647         now = time(0);
648         fprintf(globalConfPtr->log, "%s ", TimeStamp(now));
649
650         vfprintf(globalConfPtr->log, fmt, ap);
651         fflush(globalConfPtr->log);
652         fclose(globalConfPtr->log);
653     }
654     va_end(ap);
655 }
656
657 void
658 LogError(long code, char *fmt, ... )
659 {
660     va_list ap;
661     time_t now;
662
663     va_start(ap, fmt);
664     globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
665
666     if (globalConfPtr->log != NULL) {
667         now = time(0);
668         fprintf(globalConfPtr->log, "%s ", TimeStamp(now));
669
670         if (code)
671             fprintf(globalConfPtr->log, "%s: %s\n", afs_error_table_name(code),
672                     afs_error_message(code));
673         vfprintf(globalConfPtr->log, fmt, ap );
674         fflush(globalConfPtr->log);
675         fclose(globalConfPtr->log);
676     }
677 }
678
679
680 /*  ----------------
681  * debug
682  * ----------------
683  */
684
685 void
686 LogNetDump(struct dump *dumpPtr)
687 {
688     struct dump hostDump;
689     extern buServerConfP globalConfPtr;
690
691     dump_ntoh(dumpPtr, &hostDump);
692
693     globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
694     if (globalConfPtr->log != NULL) {
695         printDump(globalConfPtr->log, &hostDump);
696         fclose(globalConfPtr->log);
697     }
698 }
699