ubik-serverinit-clones-correction-20081222
[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 RCSID
14     ("$Header$");
15
16 #include <fcntl.h>
17 #include <sys/stat.h>
18 #ifdef AFS_NT40_ENV
19 #include <winsock2.h>
20 #include <WINNT/afsevent.h>
21 #else
22 #include <netinet/in.h>
23 #include <sys/file.h>
24 #include <sys/time.h>
25 #include <netdb.h>
26 #endif
27 #include <string.h>
28 #include <afs/stds.h>
29 #include <sys/types.h>
30 #include <time.h>
31 #include <stdio.h>
32 #include <afs/cmd.h>
33 #include <lwp.h>
34 #include <ubik.h>
35 #include <rx/xdr.h>
36 #include <rx/rx.h>
37 #include <rx/rxkad.h>
38 #include <rx/rx_globals.h>
39 #include <afs/cellconfig.h>
40 #include <afs/bubasics.h>
41 #include <afs/afsutil.h>
42 #include <afs/com_err.h>
43 #include <errno.h>
44 #ifdef  AFS_AIX32_ENV
45 #include <signal.h>
46 #endif
47 #include "budb_errs.h"
48 #include "database.h"
49 #include "error_macros.h"
50 #include "globals.h"
51 #include "afs/audit.h"
52
53 struct ubik_dbase *BU_dbase;
54 struct afsconf_dir *BU_conf;    /* for getting cell info */
55
56 int argHandler(struct cmd_syndesc *, void *);
57
58 char lcell[MAXKTCREALMLEN];
59 afs_int32 myHost = 0;
60 int helpOption;
61
62 /* server's global configuration information. This is exported to other
63  * files/routines
64  */
65
66 buServerConfT globalConf;
67 buServerConfP globalConfPtr = &globalConf;
68 char dbDir[AFSDIR_PATH_MAX], cellConfDir[AFSDIR_PATH_MAX];
69 /* debugging control */
70 int debugging = 0;
71
72 int rxBind = 0;
73 int lwps   = 3;
74
75 #define MINLWP  3
76 #define MAXLWP 16
77
78 #define ADDRSPERSITE 16         /* Same global is in rx/rx_user.c */
79 afs_uint32 SHostAddrs[ADDRSPERSITE];
80
81 #if defined(AFS_PTHREAD_ENV)
82 char *
83 threadNum(void)
84 {
85     return pthread_getspecific(rx_thread_id_key);
86 }
87 #endif
88
89 /* check whether caller is authorized to manage RX statistics */
90 int
91 BU_rxstat_userok(call)
92      struct rx_call *call;
93 {
94     return afsconf_SuperUser(BU_conf, call, NULL);
95 }
96
97 int
98 convert_cell_to_ubik(cellinfo, myHost, serverList)
99      struct afsconf_cell *cellinfo;
100      afs_int32 *myHost;
101      afs_int32 *serverList;
102 {
103     int i;
104     char hostname[64];
105     struct hostent *th;
106
107     /* get this host */
108     gethostname(hostname, sizeof(hostname));
109     th = gethostbyname(hostname);
110     if (!th) {
111         printf("prserver: couldn't get address of this host.\n");
112         BUDB_EXIT(1);
113     }
114     memcpy(myHost, th->h_addr, sizeof(afs_int32));
115
116     for (i = 0; i < cellinfo->numServers; i++)
117         /* omit my host from serverList */
118         if (cellinfo->hostAddr[i].sin_addr.s_addr != *myHost)
119             *serverList++ = cellinfo->hostAddr[i].sin_addr.s_addr;
120
121     *serverList = 0;            /* terminate list */
122     return 0;
123 }
124
125 /* MyBeforeProc
126  *      The whole purpose of MyBeforeProc is to detect
127  *      if the -help option was not within the command line.
128  *      If it were, this routine would never have been called.
129  */
130 static int
131 MyBeforeProc(register struct cmd_syndesc *as, void *arock)
132 {
133     helpOption = 0;
134     return 0;
135 }
136
137 /* initializeCommands
138  *      initialize all the supported commands and their arguments
139  */
140
141 void
142 initializeArgHandler()
143 {
144     struct cmd_syndesc *cptr;
145
146     cmd_SetBeforeProc(MyBeforeProc, NULL);
147
148     cptr = cmd_CreateSyntax(NULL, argHandler, NULL, "Backup database server");
149
150     cmd_AddParm(cptr, "-database", CMD_SINGLE, CMD_OPTIONAL,
151                 "database directory");
152
153     cmd_AddParm(cptr, "-cellservdb", CMD_SINGLE, CMD_OPTIONAL,
154                 "cell configuration directory");
155
156     cmd_AddParm(cptr, "-resetdb", CMD_FLAG, CMD_OPTIONAL,
157                 "truncate the database");
158
159     cmd_AddParm(cptr, "-noauth", CMD_FLAG, CMD_OPTIONAL,
160                 "run without authentication");
161
162     cmd_AddParm(cptr, "-smallht", CMD_FLAG, CMD_OPTIONAL,
163                 "use small hash tables");
164
165     cmd_AddParm(cptr, "-servers", CMD_LIST, CMD_OPTIONAL,
166                 "list of ubik database servers");
167
168     cmd_AddParm(cptr, "-ubikbuffers", CMD_SINGLE, CMD_OPTIONAL,
169                 "the number of ubik buffers");
170
171     cmd_AddParm(cptr, "-auditlog", CMD_SINGLE, CMD_OPTIONAL,
172                 "audit log path");
173
174     cmd_AddParm(cptr, "-p", CMD_SINGLE, CMD_OPTIONAL,
175                 "number of processes");
176
177     cmd_AddParm(cptr, "-rxbind", CMD_FLAG, CMD_OPTIONAL,
178                 "bind the Rx socket (primary interface only)");
179
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     if (as->parms[7].items != 0) {
232         char *fileName = as->parms[7].items->data;
233
234         osi_audit_file(fileName);
235     }
236
237     /* user provided the number of threads    */
238     if (as->parms[8].items != 0) {
239         lwps = atoi(as->parms[8].items->data);
240         if (lwps > MAXLWP) {
241             printf ("Warning: '-p %d' is too big; using %d instead\n",
242                 lwps, MAXLWP);
243             lwps = MAXLWP;
244         }
245         if (lwps < MINLWP) {
246             printf ("Warning: '-p %d' is too small; using %d instead\n",
247                 lwps, MINLWP);
248             lwps = MINLWP;
249         }
250     }
251
252     /* user provided rxbind option    */
253     if (as->parms[9].items != 0) {
254         rxBind = 1;
255     }
256
257     return 0;
258 }
259
260 /* --- */
261
262 parseServerList(itemPtr)
263      struct cmd_item *itemPtr;
264 {
265     struct cmd_item *save;
266     char **serverArgs;
267     char **ptr;
268     afs_int32 nservers = 0;
269     afs_int32 code = 0;
270
271     save = itemPtr;
272
273     /* compute number of servers in the list */
274     while (itemPtr) {
275         nservers++;
276         itemPtr = itemPtr->next;
277     }
278
279     LogDebug(3, "%d servers\n", nservers);
280
281     /* now can allocate the space for the server arguments */
282     serverArgs = (char **)malloc((nservers + 2) * sizeof(char *));
283     if (serverArgs == 0)
284         ERROR(-1);
285
286     ptr = serverArgs;
287     *ptr++ = "";
288     *ptr++ = "-servers";
289
290     /* now go through and construct the list of servers */
291     itemPtr = save;
292     while (itemPtr) {
293         *ptr++ = itemPtr->data;
294         itemPtr = itemPtr->next;
295     }
296
297     code =
298         ubik_ParseServerList(nservers + 2, serverArgs, &globalConfPtr->myHost,
299                              globalConfPtr->serverList);
300     if (code)
301         ERROR(code);
302
303     /* free space for the server args */
304     free((char *)serverArgs);
305
306   error_exit:
307     return (code);
308 }
309
310 /* truncateDatabase
311  *      truncates just the database file.
312  */
313
314 truncateDatabase()
315 {
316     char *path;
317     afs_int32 code = 0;
318     int fd;
319
320     path =
321         (char *)malloc(strlen(globalConfPtr->databaseDirectory) +
322                        strlen(globalConfPtr->databaseName) +
323                        strlen(globalConfPtr->databaseExtension) + 1);
324     if (path == 0)
325         ERROR(-1);
326
327     /* construct the database name */
328     strcpy(path, globalConfPtr->databaseDirectory);
329     strcat(path, globalConfPtr->databaseName);
330     strcat(path, globalConfPtr->databaseExtension);
331
332     fd = open(path, O_RDWR, 0755);
333     if (!fd) {
334         code = errno;
335     } else {
336         if (ftruncate(fd, 0) != 0) {
337             code = errno;
338         } else
339             close(fd);
340     }
341
342   error_exit:
343     return (code);
344 }
345
346
347 /* --- */
348
349 #include "AFS_component_version_number.c"
350
351 main(argc, argv)
352      int argc;
353      char *argv[];
354 {
355     char *whoami = argv[0];
356     char *dbNamePtr = 0;
357     struct afsconf_cell cellinfo;
358     time_t currentTime;
359     afs_int32 code = 0;
360     afs_uint32 host = ntohl(INADDR_ANY);
361
362     char  clones[MAXHOSTSPERCELL];
363
364     struct rx_service *tservice;
365     struct rx_securityClass *sca[3];
366
367     extern int afsconf_ServerAuth();
368     extern int afsconf_CheckAuth();
369
370     extern int rx_stackSize;
371     extern int BUDB_ExecuteRequest();
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( threadNum );
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         code =
486             convert_cell_to_ubik(&cellinfo, &globalConfPtr->myHost,
487                                  globalConfPtr->serverList);
488         if (code)
489             ERROR(code);
490     }
491
492     /* initialize ubik */
493     ubik_CRXSecurityProc = afsconf_ClientAuth;
494     ubik_CRXSecurityRock = (char *)BU_conf;
495
496     ubik_SRXSecurityProc = afsconf_ServerAuth;
497     ubik_SRXSecurityRock = (char *)BU_conf;
498
499     ubik_CheckRXSecurityProc = afsconf_CheckAuth;
500     ubik_CheckRXSecurityRock = (char *)BU_conf;
501
502     if (ubik_nBuffers == 0)
503         ubik_nBuffers = 400;
504
505     LogError(0, "Will allocate %d ubik buffers\n", ubik_nBuffers);
506
507     dbNamePtr =
508         (char *)malloc(strlen(globalConfPtr->databaseDirectory) +
509                        strlen(globalConfPtr->databaseName) + 1);
510     if (dbNamePtr == 0)
511         ERROR(-1);
512
513     /* construct the database name */
514     strcpy(dbNamePtr, globalConfPtr->databaseDirectory);
515     strcat(dbNamePtr, globalConfPtr->databaseName);     /* name prefix */
516
517     rx_SetRxDeadTime(60);       /* 60 seconds inactive before timeout */
518
519     if (rxBind) {
520         afs_int32 ccode;
521         if (AFSDIR_SERVER_NETRESTRICT_FILEPATH || 
522             AFSDIR_SERVER_NETINFO_FILEPATH) {
523             char reason[1024];
524             ccode = parseNetFiles(SHostAddrs, NULL, NULL,
525                                            ADDRSPERSITE, reason,
526                                            AFSDIR_SERVER_NETINFO_FILEPATH,
527                                            AFSDIR_SERVER_NETRESTRICT_FILEPATH);
528         } else 
529         {
530             ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
531         }
532         if (ccode == 1) {
533             host = SHostAddrs[0];
534             rx_InitHost(host, htons(AFSCONF_BUDBPORT));
535         }
536     }
537
538     code = ubik_ServerInitByInfo (globalConfPtr->myHost,
539                                   htons(AFSCONF_BUDBPORT), 
540                                   &cellinfo,
541                                   clones,              
542                                   dbNamePtr,           /* name prefix */
543                                   &BU_dbase);
544
545     if (code) {
546         LogError(code, "Ubik init failed\n");
547         afs_com_err(whoami, code, "Ubik init failed");
548         ERROR(code);
549     }
550
551     sca[RX_SCINDEX_NULL] = rxnull_NewServerSecurityObject();
552     sca[RX_SCINDEX_VAB] = 0;
553     sca[RX_SCINDEX_KAD] =
554         rxkad_NewServerSecurityObject(rxkad_clear, BU_conf, afsconf_GetKey,
555                                       NULL);
556
557     /* Disable jumbograms */
558     rx_SetNoJumbo();
559
560     tservice =
561         rx_NewServiceHost(host, 0, BUDB_SERVICE, "BackupDatabase", sca, 3,
562                       BUDB_ExecuteRequest);
563     if (tservice == (struct rx_service *)0) {
564         LogError(0, "Could not create backup database rx service\n");
565         printf("Could not create backup database rx service\n");
566         BUDB_EXIT(3);
567     }
568     rx_SetMinProcs(tservice, 1);
569     rx_SetMaxProcs(tservice, lwps);
570     rx_SetStackSize(tservice, 10000);
571
572     /* allow super users to manage RX statistics */
573     rx_SetRxStatUserOk(BU_rxstat_userok);
574
575     /* misc. initialization */
576
577     /* database dump synchronization */
578     memset(dumpSyncPtr, 0, sizeof(*dumpSyncPtr));
579     Lock_Init(&dumpSyncPtr->ds_lock);
580
581     rx_StartServer(0);          /* start handling requests */
582
583     code = InitProcs();
584     if (code)
585         ERROR(code);
586
587
588     currentTime = time(0);
589     LogError(0, "Ready to process requests at %s\n", ctime(&currentTime));
590
591     rx_ServerProc(NULL);                /* donate this LWP */
592
593   error_exit:
594     osi_audit(BUDB_FinishEvent, code, AUD_END);
595     return (code);
596 }
597
598 void
599 consistencyCheckDb()
600 {
601     /* do consistency checks on structure sizes */
602     if ((sizeof(struct htBlock) > BLOCKSIZE)
603         || (sizeof(struct vfBlock) > BLOCKSIZE)
604         || (sizeof(struct viBlock) > BLOCKSIZE)
605         || (sizeof(struct dBlock) > BLOCKSIZE)
606         || (sizeof(struct tBlock) > BLOCKSIZE)
607         ) {
608         fprintf(stderr, "Block layout error!\n");
609         BUDB_EXIT(99);
610     }
611 }
612
613  /*VARARGS*/
614 LogDebug(level, a, b, c, d, e, f, g, h, i)
615      int level;
616      char *a, *b, *c, *d, *e, *f, *g, *h, *i;
617 {
618
619     if (debugging >= level) {
620         /* log normally closed so can remove it */
621         globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
622         if (globalConfPtr->log != NULL) {
623             fprintf(globalConfPtr->log, a, b, c, d, e, f, g, h, i);
624             fflush(globalConfPtr->log);
625             fclose(globalConfPtr->log);
626         }
627     }
628     return 0;
629 }
630
631 static char *
632 TimeStamp(time_t t)
633 {
634     struct tm *lt;
635     static char timestamp[20];
636
637     lt = localtime(&t);
638     strftime(timestamp, 20, "%m/%d/%Y %H:%M:%S", lt);
639     return timestamp;
640 }
641
642  /*VARARGS*/
643 Log(a, b, c, d, e, f, g, h, i)
644      char *a, *b, *c, *d, *e, *f, *g, *h, *i;
645 {
646     time_t now;
647
648     globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
649     if (globalConfPtr->log != NULL) {
650         now = time(0);
651         fprintf(globalConfPtr->log, "%s ", TimeStamp(now));
652
653         fprintf(globalConfPtr->log, a, b, c, d, e, f, g, h, i);
654         fflush(globalConfPtr->log);
655         fclose(globalConfPtr->log);
656     }
657     return 0;
658 }
659
660  /*VARARGS*/
661 LogError(code, a, b, c, d, e, f, g, h, i)
662      long code;
663      char *a, *b, *c, *d, *e, *f, *g, *h, *i;
664 {
665     time_t now;
666
667     globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
668
669     if (globalConfPtr->log != NULL) {
670         now = time(0);
671         fprintf(globalConfPtr->log, "%s ", TimeStamp(now));
672
673         if (code)
674             fprintf(globalConfPtr->log, "%s: %s\n", afs_error_table_name(code),
675                     afs_error_message(code));
676         fprintf(globalConfPtr->log, a, b, c, d, e, f, g, h, i);
677         fflush(globalConfPtr->log);
678         fclose(globalConfPtr->log);
679     }
680     return 0;
681 }
682
683
684 /*  ----------------
685  * debug
686  * ----------------
687  */
688
689
690 LogNetDump(dumpPtr)
691      struct dump *dumpPtr;
692 {
693     struct dump hostDump;
694     extern buServerConfP globalConfPtr;
695
696     dump_ntoh(dumpPtr, &hostDump);
697
698     globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
699     if (globalConfPtr->log != NULL) {
700         printDump(globalConfPtr->log, &hostDump);
701         fclose(globalConfPtr->log);
702     }
703     return 0;
704 }