xref: /original-bsd/usr.sbin/kvm_mkdb/kvm_mkdb.c (revision 5133e8a4)
1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 char copyright[] =
10 "@(#) Copyright (c) 1990 The Regents of the University of California.\n\
11  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)kvm_mkdb.c	5.16 (Berkeley) 06/02/92";
16 #endif /* not lint */
17 
18 #include <sys/param.h>
19 #include <sys/stat.h>
20 #include <fcntl.h>
21 #include <db.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <paths.h>
27 
28 #include "extern.h"
29 
30 static void usage __P(());
31 
32 int
33 main(argc, argv)
34 	int argc;
35 	char **argv;
36 {
37 	DB *db;
38 	int ch;
39 	char *p, *nlistpath, *nlistname, dbtemp[MAXPATHLEN], dbname[MAXPATHLEN];
40 
41 	while ((ch = getopt(argc, argv, "")) != EOF)
42 		switch((char)ch) {
43 		case '?':
44 		default:
45 			usage();
46 		}
47 	argc -= optind;
48 	argv += optind;
49 
50 	if (argc > 1)
51 		usage();
52 
53 	/* If the existing db file matches the currently running kernel, exit */
54 	if (testdb())
55 		exit(0);
56 
57 #define	basename(cp)	((p = rindex((cp), '/')) != NULL ? p + 1 : (cp))
58 	nlistpath = argc > 0 ? argv[0] : _PATH_UNIX;
59 	nlistname = basename(nlistpath);
60 
61 	(void)snprintf(dbtemp, sizeof(dbtemp), "%skvm_%s.tmp",
62 	    _PATH_VARDB, nlistname);
63 	(void)snprintf(dbname, sizeof(dbname), "%skvm_%s.db",
64 	    _PATH_VARDB, nlistname);
65 	(void)umask(0);
66 	db = dbopen(dbtemp, O_CREAT|O_EXLOCK|O_TRUNC|O_WRONLY,
67 	    S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH, DB_HASH, NULL);
68 	if (!db) {
69 		(void)fprintf(stderr,
70 		    "kvm_mkdb: %s: %s\n", dbtemp, strerror(errno));
71 		exit(1);
72 	}
73 	create_knlist(nlistpath, db);
74 	(void)(db->close)(db);
75 	if (rename(dbtemp, dbname)) {
76 		(void)fprintf(stderr, "kvm_mkdb: %s to %s: %s.\n",
77 		    dbtemp, dbname, strerror(errno));
78 		exit(1);
79 	}
80 	exit(0);
81 }
82 
83 void
84 error(n)
85 	char *n;
86 {
87 	int sverr;
88 
89 	sverr = errno;
90 	(void)fprintf(stderr, "kvm_mkdb: ");
91 	if (n)
92 		(void)fprintf(stderr, "%s: ", n);
93 	(void)fprintf(stderr, "%s\n", strerror(sverr));
94 	exit(1);
95 }
96 
97 void
98 usage()
99 {
100 	(void)fprintf(stderr, "usage: kvm_mkdb [file]\n");
101 	exit(1);
102 }
103