strftime-portability-20080528
[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         int tempfd, flags;
233         FILE *auditout;
234         char oldName[MAXPATHLEN];
235         char *fileName = as->parms[7].items->data;
236 #ifndef AFS_NT40_ENV
237         struct stat statbuf;
238
239         if ((lstat(fileName, &statbuf) == 0) 
240             && (S_ISFIFO(statbuf.st_mode))) {
241             flags = O_WRONLY | O_NONBLOCK;
242         } else 
243 #endif
244         {
245             strcpy(oldName, fileName);
246             strcat(oldName, ".old");
247             renamefile(fileName, oldName);
248             flags = O_WRONLY | O_TRUNC | O_CREAT;
249         }
250         tempfd = open(fileName, flags, 0666);
251         if (tempfd > -1) {
252             auditout = fdopen(tempfd, "a");
253             if (auditout) {
254                 osi_audit_file(auditout);
255             } else
256                 printf("Warning: auditlog %s not writable, ignored.\n", fileName);
257         } else
258             printf("Warning: auditlog %s not writable, ignored.\n", fileName);
259     }
260
261     /* user provided the number of threads    */
262     if (as->parms[8].items != 0) {
263         lwps = atoi(as->parms[8].items->data);
264         if (lwps > MAXLWP) {
265             printf ("Warning: '-p %d' is too big; using %d instead\n",
266                 lwps, MAXLWP);
267             lwps = MAXLWP;
268         }
269         if (lwps < MINLWP) {
270             printf ("Warning: '-p %d' is too small; using %d instead\n",
271                 lwps, MINLWP);
272             lwps = MINLWP;
273         }
274     }
275
276     /* user provided rxbind option    */
277     if (as->parms[9].items != 0) {
278         rxBind = 1;
279     }
280
281     return 0;
282 }
283
284 /* --- */
285
286 parseServerList(itemPtr)
287      struct cmd_item *itemPtr;
288 {
289     struct cmd_item *save;
290     char **serverArgs;
291     char **ptr;
292     afs_int32 nservers = 0;
293     afs_int32 code = 0;
294
295     save = itemPtr;
296
297     /* compute number of servers in the list */
298     while (itemPtr) {
299         nservers++;
300         itemPtr = itemPtr->next;
301     }
302
303     LogDebug(3, "%d servers\n", nservers);
304
305     /* now can allocate the space for the server arguments */
306     serverArgs = (char **)malloc((nservers + 2) * sizeof(char *));
307     if (serverArgs == 0)
308         ERROR(-1);
309
310     ptr = serverArgs;
311     *ptr++ = "";
312     *ptr++ = "-servers";
313
314     /* now go through and construct the list of servers */
315     itemPtr = save;
316     while (itemPtr) {
317         *ptr++ = itemPtr->data;
318         itemPtr = itemPtr->next;
319     }
320
321     code =
322         ubik_ParseServerList(nservers + 2, serverArgs, &globalConfPtr->myHost,
323                              globalConfPtr->serverList);
324     if (code)
325         ERROR(code);
326
327     /* free space for the server args */
328     free((char *)serverArgs);
329
330   error_exit:
331     return (code);
332 }
333
334 /* truncateDatabase
335  *      truncates just the database file.
336  */
337
338 truncateDatabase()
339 {
340     char *path;
341     afs_int32 code = 0;
342     int fd;
343
344     path =
345         (char *)malloc(strlen(globalConfPtr->databaseDirectory) +
346                        strlen(globalConfPtr->databaseName) +
347                        strlen(globalConfPtr->databaseExtension) + 1);
348     if (path == 0)
349         ERROR(-1);
350
351     /* construct the database name */
352     strcpy(path, globalConfPtr->databaseDirectory);
353     strcat(path, globalConfPtr->databaseName);
354     strcat(path, globalConfPtr->databaseExtension);
355
356     fd = open(path, O_RDWR, 0755);
357     if (!fd) {
358         code = errno;
359     } else {
360         if (ftruncate(fd, 0) != 0) {
361             code = errno;
362         } else
363             close(fd);
364     }
365
366   error_exit:
367     return (code);
368 }
369
370
371 /* --- */
372
373 #include "AFS_component_version_number.c"
374
375 main(argc, argv)
376      int argc;
377      char *argv[];
378 {
379     char *whoami = argv[0];
380     char *dbNamePtr = 0;
381     struct afsconf_cell cellinfo;
382     time_t currentTime;
383     afs_int32 code = 0;
384     afs_uint32 host = ntohl(INADDR_ANY);
385
386     char  clones[MAXHOSTSPERCELL];
387
388     struct rx_service *tservice;
389     struct rx_securityClass *sca[3];
390
391     extern int afsconf_ServerAuth();
392     extern int afsconf_CheckAuth();
393
394     extern int rx_stackSize;
395     extern int BUDB_ExecuteRequest();
396
397 #ifdef AFS_NT40_ENV
398     /* initialize winsock */
399     if (afs_winsockInit() < 0) {
400         ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
401         fprintf(stderr, "%s: Couldn't initialize winsock.\n", whoami);
402         exit(1);
403     }
404 #endif
405
406 #ifdef  AFS_AIX32_ENV
407     /*
408      * The following signal action for AIX is necessary so that in case of a 
409      * crash (i.e. core is generated) we can include the user's data section 
410      * in the core dump. Unfortunately, by default, only a partial core is
411      * generated which, in many cases, isn't too useful.
412      */
413     struct sigaction nsa;
414
415     sigemptyset(&nsa.sa_mask);
416     nsa.sa_handler = SIG_DFL;
417     nsa.sa_flags = SA_FULLDUMP;
418     sigaction(SIGSEGV, &nsa, NULL);
419     sigaction(SIGABRT, &nsa, NULL);
420 #endif
421     osi_audit_init();
422     osi_audit(BUDB_StartEvent, 0, AUD_END);
423
424     initialize_BUDB_error_table();
425     initializeArgHandler();
426
427     /* Initialize dirpaths */
428     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
429 #ifdef AFS_NT40_ENV
430         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
431 #endif
432         afs_com_err(whoami, errno, "; Unable to obtain AFS server directory.");
433         exit(2);
434     }
435
436     memset(globalConfPtr, 0, sizeof(*globalConfPtr));
437
438     /* set default configuration values */
439     strcpy(dbDir, AFSDIR_SERVER_DB_DIRPATH);
440     strcat(dbDir, "/");
441     globalConfPtr->databaseDirectory = dbDir;
442     globalConfPtr->databaseName = DEFAULT_DBPREFIX;
443     strcpy(cellConfDir, AFSDIR_SERVER_ETC_DIRPATH);
444     globalConfPtr->cellConfigdir = cellConfDir;
445
446     /* open the log file */
447 /*
448     globalConfPtr->log = fopen(DEFAULT_LOGNAME,"a");
449     if ( globalConfPtr->log == NULL )
450     {   
451         printf("Can't open log file %s - aborting\n", DEFAULT_LOGNAME);
452         BUDB_EXIT(-1);
453     }
454 */
455
456     srandom(1);
457
458 #ifdef AFS_PTHREAD_ENV
459     SetLogThreadNumProgram( threadNum );
460 #endif
461
462     /* process the user supplied args */
463     helpOption = 1;
464     code = cmd_Dispatch(argc, argv);
465     if (code)
466         ERROR(code);
467
468     /* exit if there was a help option */
469     if (helpOption)
470         BUDB_EXIT(0);
471
472     /* open the log file */
473     globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
474     if (globalConfPtr->log == NULL) {
475         printf("Can't open log file %s - aborting\n",
476                AFSDIR_SERVER_BUDBLOG_FILEPATH);
477         BUDB_EXIT(-1);
478     }
479
480     /* keep log closed so can remove it */
481
482     fclose(globalConfPtr->log);
483
484     /* open the cell's configuration directory */
485     LogDebug(4, "opening %s\n", globalConfPtr->cellConfigdir);
486
487     BU_conf = afsconf_Open(globalConfPtr->cellConfigdir);
488     if (BU_conf == 0) {
489         LogError(code, "Failed getting cell info\n");
490         afs_com_err(whoami, code, "Failed getting cell info");
491         ERROR(BUDB_NOCELLS);
492     }
493
494     code = afsconf_GetLocalCell(BU_conf, lcell, sizeof(lcell));
495     if (code) {
496         LogError(0, "** Can't determine local cell name!\n");
497         ERROR(code);
498     }
499
500     if (globalConfPtr->myHost == 0) {
501         /* if user hasn't supplied a list of servers, extract server
502          * list from the cell's database
503          */
504
505         LogDebug(1, "Using server list from %s cell database.\n", lcell);
506
507         code = afsconf_GetExtendedCellInfo (BU_conf, lcell, 0, &cellinfo, 
508                                             &clones); 
509         code =
510             convert_cell_to_ubik(&cellinfo, &globalConfPtr->myHost,
511                                  globalConfPtr->serverList);
512         if (code)
513             ERROR(code);
514     }
515
516     /* initialize ubik */
517     ubik_CRXSecurityProc = afsconf_ClientAuth;
518     ubik_CRXSecurityRock = (char *)BU_conf;
519
520     ubik_SRXSecurityProc = afsconf_ServerAuth;
521     ubik_SRXSecurityRock = (char *)BU_conf;
522
523     ubik_CheckRXSecurityProc = afsconf_CheckAuth;
524     ubik_CheckRXSecurityRock = (char *)BU_conf;
525
526     if (ubik_nBuffers == 0)
527         ubik_nBuffers = 400;
528
529     LogError(0, "Will allocate %d ubik buffers\n", ubik_nBuffers);
530
531     dbNamePtr =
532         (char *)malloc(strlen(globalConfPtr->databaseDirectory) +
533                        strlen(globalConfPtr->databaseName) + 1);
534     if (dbNamePtr == 0)
535         ERROR(-1);
536
537     /* construct the database name */
538     strcpy(dbNamePtr, globalConfPtr->databaseDirectory);
539     strcat(dbNamePtr, globalConfPtr->databaseName);     /* name prefix */
540
541     rx_SetRxDeadTime(60);       /* 60 seconds inactive before timeout */
542
543     if (rxBind) {
544         afs_int32 ccode;
545 #ifndef AFS_NT40_ENV
546         if (AFSDIR_SERVER_NETRESTRICT_FILEPATH || 
547             AFSDIR_SERVER_NETINFO_FILEPATH) {
548             char reason[1024];
549             ccode = parseNetFiles(SHostAddrs, NULL, NULL,
550                                            ADDRSPERSITE, reason,
551                                            AFSDIR_SERVER_NETINFO_FILEPATH,
552                                            AFSDIR_SERVER_NETRESTRICT_FILEPATH);
553         } else 
554 #endif  
555         {
556             ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
557         }
558         if (ccode == 1) {
559             host = SHostAddrs[0];
560             rx_InitHost(host, htons(AFSCONF_BUDBPORT));
561         }
562     }
563
564     code = ubik_ServerInitByInfo (globalConfPtr->myHost,
565                                   htons(AFSCONF_BUDBPORT), 
566                                   &cellinfo,
567                                   &clones,              
568                                   dbNamePtr,           /* name prefix */
569                                   &BU_dbase);
570
571     if (code) {
572         LogError(code, "Ubik init failed\n");
573         afs_com_err(whoami, code, "Ubik init failed");
574         ERROR(code);
575     }
576
577     sca[RX_SCINDEX_NULL] = rxnull_NewServerSecurityObject();
578     sca[RX_SCINDEX_VAB] = 0;
579     sca[RX_SCINDEX_KAD] =
580         rxkad_NewServerSecurityObject(rxkad_clear, BU_conf, afsconf_GetKey,
581                                       NULL);
582
583     /* Disable jumbograms */
584     rx_SetNoJumbo();
585
586     tservice =
587         rx_NewServiceHost(host, 0, BUDB_SERVICE, "BackupDatabase", sca, 3,
588                       BUDB_ExecuteRequest);
589     if (tservice == (struct rx_service *)0) {
590         LogError(0, "Could not create backup database rx service\n");
591         printf("Could not create backup database rx service\n");
592         BUDB_EXIT(3);
593     }
594     rx_SetMinProcs(tservice, 1);
595     rx_SetMaxProcs(tservice, lwps);
596     rx_SetStackSize(tservice, 10000);
597
598     /* allow super users to manage RX statistics */
599     rx_SetRxStatUserOk(BU_rxstat_userok);
600
601     /* misc. initialization */
602
603     /* database dump synchronization */
604     memset(dumpSyncPtr, 0, sizeof(*dumpSyncPtr));
605     Lock_Init(&dumpSyncPtr->ds_lock);
606
607     rx_StartServer(0);          /* start handling requests */
608
609     code = InitProcs();
610     if (code)
611         ERROR(code);
612
613
614     currentTime = time(0);
615     LogError(0, "Ready to process requests at %s\n", ctime(&currentTime));
616
617     rx_ServerProc(NULL);                /* donate this LWP */
618
619   error_exit:
620     osi_audit(BUDB_FinishEvent, code, AUD_END);
621     return (code);
622 }
623
624 void
625 consistencyCheckDb()
626 {
627     /* do consistency checks on structure sizes */
628     if ((sizeof(struct htBlock) > BLOCKSIZE)
629         || (sizeof(struct vfBlock) > BLOCKSIZE)
630         || (sizeof(struct viBlock) > BLOCKSIZE)
631         || (sizeof(struct dBlock) > BLOCKSIZE)
632         || (sizeof(struct tBlock) > BLOCKSIZE)
633         ) {
634         fprintf(stderr, "Block layout error!\n");
635         BUDB_EXIT(99);
636     }
637 }
638
639  /*VARARGS*/
640 LogDebug(level, a, b, c, d, e, f, g, h, i)
641      int level;
642      char *a, *b, *c, *d, *e, *f, *g, *h, *i;
643 {
644
645     if (debugging >= level) {
646         /* log normally closed so can remove it */
647         globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
648         if (globalConfPtr->log != NULL) {
649             fprintf(globalConfPtr->log, a, b, c, d, e, f, g, h, i);
650             fflush(globalConfPtr->log);
651             fclose(globalConfPtr->log);
652         }
653     }
654     return 0;
655 }
656
657 static char *
658 TimeStamp(time_t t)
659 {
660     struct tm *lt;
661     static char timestamp[20];
662
663     lt = localtime(&t);
664     strftime(timestamp, 20, "%m/%d/%Y %H:%M:%S", lt);
665     return timestamp;
666 }
667
668  /*VARARGS*/
669 Log(a, b, c, d, e, f, g, h, i)
670      char *a, *b, *c, *d, *e, *f, *g, *h, *i;
671 {
672     time_t now;
673
674     globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
675     if (globalConfPtr->log != NULL) {
676         now = time(0);
677         fprintf(globalConfPtr->log, "%s ", TimeStamp(now));
678
679         fprintf(globalConfPtr->log, a, b, c, d, e, f, g, h, i);
680         fflush(globalConfPtr->log);
681         fclose(globalConfPtr->log);
682     }
683     return 0;
684 }
685
686  /*VARARGS*/
687 LogError(code, a, b, c, d, e, f, g, h, i)
688      long code;
689      char *a, *b, *c, *d, *e, *f, *g, *h, *i;
690 {
691     time_t now;
692
693     globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
694
695     if (globalConfPtr->log != NULL) {
696         now = time(0);
697         fprintf(globalConfPtr->log, "%s ", TimeStamp(now));
698
699         if (code)
700             fprintf(globalConfPtr->log, "%s: %s\n", afs_error_table_name(code),
701                     afs_error_message(code));
702         fprintf(globalConfPtr->log, a, b, c, d, e, f, g, h, i);
703         fflush(globalConfPtr->log);
704         fclose(globalConfPtr->log);
705     }
706     return 0;
707 }
708
709
710 /*  ----------------
711  * debug
712  * ----------------
713  */
714
715
716 LogNetDump(dumpPtr)
717      struct dump *dumpPtr;
718 {
719     struct dump hostDump;
720     extern buServerConfP globalConfPtr;
721
722     dump_ntoh(dumpPtr, &hostDump);
723
724     globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");
725     if (globalConfPtr->log != NULL) {
726         printDump(globalConfPtr->log, &hostDump);
727         fclose(globalConfPtr->log);
728     }
729     return 0;
730 }