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