xref: /original-bsd/usr.sbin/dev_mkdb/dev_mkdb.c (revision 1ff91bf0)
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[] = "@(#)dev_mkdb.c	5.5 (Berkeley) 04/27/91";
16 #endif /* not lint */
17 
18 #include <sys/param.h>
19 #include <sys/stat.h>
20 #include <fcntl.h>
21 #undef DIRBLKSIZ
22 #include <dirent.h>
23 #include <kvm.h>
24 #include <db.h>
25 #include <errno.h>
26 #include <stdio.h>
27 #include <paths.h>
28 #include <string.h>
29 
30 main(argc, argv)
31 	int argc;
32 	char **argv;
33 {
34 	extern int optind;
35 	register DIR *dirp;
36 	register struct dirent *dp;
37 	struct stat sb;
38 	DB *db;
39 	DBT data, key;
40 	int ch;
41 	u_char buf[MAXNAMLEN + 1];
42 	char dbtmp[MAXPATHLEN + 1], dbname[MAXPATHLEN + 1];
43 
44 	while ((ch = getopt(argc, argv, "")) != EOF)
45 		switch((char)ch) {
46 		case '?':
47 		default:
48 			usage();
49 		}
50 	argc -= optind;
51 	argv += optind;
52 
53 	if (chdir(_PATH_DEV))
54 		error(_PATH_DEV);
55 
56 	dirp = opendir(".");
57 
58 	(void)snprintf(dbtmp, sizeof(dbtmp), "%s/dev.tmp", _PATH_VARRUN);
59 	(void)snprintf(dbname, sizeof(dbtmp), "%s/dev.db", _PATH_VARRUN);
60 	db = hash_open(dbtmp, O_CREAT|O_WRONLY|O_EXCL, DEFFILEMODE,
61 	    (HASHINFO *)NULL);
62 	if (!db)
63 		error(dbtmp);
64 
65 	key.data = (u_char *)&sb.st_rdev;
66 	key.size = sizeof(sb.st_rdev);
67 	data.data = buf;
68 	while (dp = readdir(dirp)) {
69 		if (stat(dp->d_name, &sb))
70 			error(dp->d_name);
71 		if (!S_ISCHR(sb.st_mode))
72 			continue;
73 
74 		/* Nul terminate the name so ps doesn't have to. */
75 		bcopy(dp->d_name, buf, dp->d_namlen);
76 		buf[dp->d_namlen] = '\0';
77 		data.size = dp->d_namlen + 1;
78 		if ((db->put)(db, &key, &data, 0))
79 			error(dbtmp);
80 	}
81 	(void)(db->close)(db);
82 	if (rename(dbtmp, dbname)) {
83 		(void)fprintf(stderr, "dev_mkdb: %s to %s: %s.\n",
84 		    dbtmp, dbname, strerror(errno));
85 		exit(1);
86 	}
87 	exit(0);
88 }
89 
90 error(n)
91 	char *n;
92 {
93 	(void)fprintf(stderr, "dev_mkdb: %s: %s\n", n, strerror(errno));
94 	exit(1);
95 }
96 
97 usage()
98 {
99 	(void)fprintf(stderr, "usage: dev_mkdb\n");
100 	exit(1);
101 }
102