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