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