a165403033599986dbf28251d53b7d907014d7fc
[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 static int
84 threadNum(void)
85 {
86     return (intptr_t)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 **securityClasses;
381     afs_int32 numClasses;
382
383     extern int rx_stackSize;
384
385 #ifdef AFS_NT40_ENV
386     /* initialize winsock */
387     if (afs_winsockInit() < 0) {
388         ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
389         fprintf(stderr, "%s: Couldn't initialize winsock.\n", whoami);
390         exit(1);
391     }
392 #endif
393
394 #ifdef  AFS_AIX32_ENV
395     /*
396      * The following signal action for AIX is necessary so that in case of a 
397      * crash (i.e. core is generated) we can include the user's data section 
398      * in the core dump. Unfortunately, by default, only a partial core is
399      * generated which, in many cases, isn't too useful.
400      */
401     struct sigaction nsa;
402
403     sigemptyset(&nsa.sa_mask);
404     nsa.sa_handler = SIG_DFL;
405     nsa.sa_flags = SA_FULLDUMP;
406     sigaction(SIGSEGV, &nsa, NULL);
407     sigaction(SIGABRT, &nsa, NULL);
408 #endif
409     osi_audit_init();
410     osi_audit(BUDB_StartEvent, 0, AUD_END);
411
412     initialize_BUDB_error_table();
413     initializeArgHandler();
414
415     /* Initialize dirpaths */
416     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
417 #ifdef AFS_NT40_ENV
418         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
419 #endif
420         afs_com_err(whoami, errno, "; Unable to obtain AFS server directory.");
421         exit(2);
422     }
423
424     memset(globalConfPtr, 0, sizeof(*globalConfPtr));
425
426     /* set default configuration values */
427     strcpy(dbDir, AFSDIR_SERVER_DB_DIRPATH);
428     strcat(dbDir, "/");
429     globalConfPtr->databaseDirectory = dbDir;
430     globalConfPtr->databaseName = DEFAULT_DBPREFIX;
431     strcpy(cellConfDir, AFSDIR_SERVER_ETC_DIRPATH);
432     globalConfPtr->cellConfigdir = cellConfDir;
433
434     /* open the log file */
435 /*
436     globalConfPtr->log = fopen(DEFAULT_LOGNAME,"a");
437     if ( globalConfPtr->log == NULL )
438     {   
439         printf("Can't open log file %s - aborting\n", DEFAULT_LOGNAME);
440         BUDB_EXIT(-1);
441     }
442 */
443
444     srandom(1);
445
446 #ifdef AFS_PTHREAD_ENV
447     SetLogThreadNumProgram( threadNum );
448 #endif
449
450     /* process the user supplied args */
451     helpOption = 1;
452     code = cmd_Dispatch(argc, argv);
453     if (code)
454         ERROR(code);
455
456     /* exit if there was a help option */
457     if (helpOption)
458         BUDB_EXIT(0);
459
460     /* open the log file */
461     globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
462     if (globalConfPtr->log == NULL) {
463         printf("Can't open log file %s - aborting\n",
464                AFSDIR_SERVER_BUDBLOG_FILEPATH);
465         BUDB_EXIT(-1);
466     }
467
468     /* keep log closed so can remove it */
469
470     fclose(globalConfPtr->log);
471
472     /* open the cell's configuration directory */
473     LogDebug(4, "opening %s\n", globalConfPtr->cellConfigdir);
474
475     BU_conf = afsconf_Open(globalConfPtr->cellConfigdir);
476     if (BU_conf == 0) {
477         LogError(code, "Failed getting cell info\n");
478         afs_com_err(whoami, code, "Failed getting cell info");
479         ERROR(BUDB_NOCELLS);
480     }
481
482     code = afsconf_GetLocalCell(BU_conf, lcell, sizeof(lcell));
483     if (code) {
484         LogError(0, "** Can't determine local cell name!\n");
485         ERROR(code);
486     }
487
488     if (globalConfPtr->myHost == 0) {
489         /* if user hasn't supplied a list of servers, extract server
490          * list from the cell's database
491          */
492
493         LogDebug(1, "Using server list from %s cell database.\n", lcell);
494
495         code = afsconf_GetExtendedCellInfo (BU_conf, lcell, 0, &cellinfo,
496                                             clones);
497         code =
498             convert_cell_to_ubik(&cellinfo, &globalConfPtr->myHost,
499                                  globalConfPtr->serverList);
500         if (code)
501             ERROR(code);
502     }
503
504     /* initialize ubik */
505     ubik_CRXSecurityProc = afsconf_ClientAuth;
506     ubik_CRXSecurityRock = BU_conf;
507
508     ubik_SRXSecurityProc = afsconf_ServerAuth;
509     ubik_SRXSecurityRock = BU_conf;
510
511     ubik_CheckRXSecurityProc = afsconf_CheckAuth;
512     ubik_CheckRXSecurityRock = BU_conf;
513
514     if (ubik_nBuffers == 0)
515         ubik_nBuffers = 400;
516
517     LogError(0, "Will allocate %d ubik buffers\n", ubik_nBuffers);
518
519     dbNamePtr =
520         (char *)malloc(strlen(globalConfPtr->databaseDirectory) +
521                        strlen(globalConfPtr->databaseName) + 1);
522     if (dbNamePtr == 0)
523         ERROR(-1);
524
525     /* construct the database name */
526     strcpy(dbNamePtr, globalConfPtr->databaseDirectory);
527     strcat(dbNamePtr, globalConfPtr->databaseName);     /* name prefix */
528
529     rx_SetRxDeadTime(60);       /* 60 seconds inactive before timeout */
530
531     if (rxBind) {
532         afs_int32 ccode;
533         if (AFSDIR_SERVER_NETRESTRICT_FILEPATH || 
534             AFSDIR_SERVER_NETINFO_FILEPATH) {
535             char reason[1024];
536             ccode = parseNetFiles(SHostAddrs, NULL, NULL,
537                                            ADDRSPERSITE, reason,
538                                            AFSDIR_SERVER_NETINFO_FILEPATH,
539                                            AFSDIR_SERVER_NETRESTRICT_FILEPATH);
540         } else 
541         {
542             ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
543         }
544         if (ccode == 1) {
545             host = SHostAddrs[0];
546             rx_InitHost(host, htons(AFSCONF_BUDBPORT));
547         }
548     }
549
550     code = ubik_ServerInitByInfo (globalConfPtr->myHost,
551                                   htons(AFSCONF_BUDBPORT), 
552                                   &cellinfo,
553                                   clones,              
554                                   dbNamePtr,           /* name prefix */
555                                   &BU_dbase);
556
557     if (code) {
558         LogError(code, "Ubik init failed\n");
559         afs_com_err(whoami, code, "Ubik init failed");
560         ERROR(code);
561     }
562
563     afsconf_BuildServerSecurityObjects(BU_conf, 0,
564                                        &securityClasses, &numClasses);
565
566     /* Disable jumbograms */
567     rx_SetNoJumbo();
568
569     tservice =
570         rx_NewServiceHost(host, 0, BUDB_SERVICE, "BackupDatabase",
571                           securityClasses, numClasses, BUDB_ExecuteRequest);
572
573     if (tservice == (struct rx_service *)0) {
574         LogError(0, "Could not create backup database rx service\n");
575         printf("Could not create backup database rx service\n");
576         BUDB_EXIT(3);
577     }
578     rx_SetMinProcs(tservice, 1);
579     rx_SetMaxProcs(tservice, lwps);
580     rx_SetStackSize(tservice, 10000);
581
582     /* allow super users to manage RX statistics */
583     rx_SetRxStatUserOk(BU_rxstat_userok);
584
585     /* misc. initialization */
586
587     /* database dump synchronization */
588     memset(dumpSyncPtr, 0, sizeof(*dumpSyncPtr));
589     Lock_Init(&dumpSyncPtr->ds_lock);
590
591     rx_StartServer(0);          /* start handling requests */
592
593     code = InitProcs();
594     if (code)
595         ERROR(code);
596
597
598     currentTime = time(0);
599     LogError(0, "Ready to process requests at %s\n", ctime(&currentTime));
600
601     rx_ServerProc(NULL);                /* donate this LWP */
602
603   error_exit:
604     osi_audit(BUDB_FinishEvent, code, AUD_END);
605     return (code);
606 }
607
608 void
609 consistencyCheckDb(void)
610 {
611     /* do consistency checks on structure sizes */
612     if ((sizeof(struct htBlock) > BLOCKSIZE)
613         || (sizeof(struct vfBlock) > BLOCKSIZE)
614         || (sizeof(struct viBlock) > BLOCKSIZE)
615         || (sizeof(struct dBlock) > BLOCKSIZE)
616         || (sizeof(struct tBlock) > BLOCKSIZE)
617         ) {
618         fprintf(stderr, "Block layout error!\n");
619         BUDB_EXIT(99);
620     }
621 }
622
623 void
624 LogDebug(int level, char *fmt, ... )
625 {
626     va_list ap;
627
628     va_start(ap, fmt);
629         
630     if (debugging >= level) {
631         /* log normally closed so can remove it */
632         globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
633         if (globalConfPtr->log != NULL) {
634             vfprintf(globalConfPtr->log, fmt, ap);
635             fflush(globalConfPtr->log);
636             fclose(globalConfPtr->log);
637         }
638     }
639     va_end(ap);
640 }
641
642 static char *
643 TimeStamp(time_t t)
644 {
645     struct tm *lt;
646     static char timestamp[20];
647
648     lt = localtime(&t);
649     strftime(timestamp, 20, "%m/%d/%Y %H:%M:%S", lt);
650     return timestamp;
651 }
652
653 void
654 Log(char *fmt, ...)
655 {
656     va_list ap;
657     time_t now;
658
659     va_start(ap, fmt);
660     globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
661     if (globalConfPtr->log != NULL) {
662         now = time(0);
663         fprintf(globalConfPtr->log, "%s ", TimeStamp(now));
664
665         vfprintf(globalConfPtr->log, fmt, ap);
666         fflush(globalConfPtr->log);
667         fclose(globalConfPtr->log);
668     }
669     va_end(ap);
670 }
671
672 void
673 LogError(long code, char *fmt, ... )
674 {
675     va_list ap;
676     time_t now;
677
678     va_start(ap, fmt);
679     globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
680
681     if (globalConfPtr->log != NULL) {
682         now = time(0);
683         fprintf(globalConfPtr->log, "%s ", TimeStamp(now));
684
685         if (code)
686             fprintf(globalConfPtr->log, "%s: %s\n", afs_error_table_name(code),
687                     afs_error_message(code));
688         vfprintf(globalConfPtr->log, fmt, ap );
689         fflush(globalConfPtr->log);
690         fclose(globalConfPtr->log);
691     }
692 }
693
694
695 /*  ----------------
696  * debug
697  * ----------------
698  */
699
700 void
701 LogNetDump(struct dump *dumpPtr)
702 {
703     struct dump hostDump;
704     extern buServerConfP globalConfPtr;
705
706     dump_ntoh(dumpPtr, &hostDump);
707
708     globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
709     if (globalConfPtr->log != NULL) {
710         printDump(globalConfPtr->log, &hostDump);
711         fclose(globalConfPtr->log);
712     }
713 }
714