xref: /original-bsd/lib/libc/gen/ttyname.c (revision 56c13d2e)
1 /*
2  * Copyright (c) 1988 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #if defined(LIBC_SCCS) && !defined(lint)
9 static char sccsid[] = "@(#)ttyname.c	5.9 (Berkeley) 03/06/91";
10 #endif /* LIBC_SCCS and not lint */
11 
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <fcntl.h>
15 #include <dirent.h>
16 #include <sgtty.h>
17 #include <db.h>
18 #include <unistd.h>
19 #include <paths.h>
20 
21 static char buf[sizeof(_PATH_DEV) + MAXNAMLEN] = _PATH_DEV;
22 
23 char *
24 ttyname(fd)
25 	int fd;
26 {
27 	struct stat sb;
28 	struct sgttyb ttyb;
29 	DB *db;
30 	DBT data, key;
31 	static char *__oldttyname();
32 
33 	/* Must be a terminal. */
34 	if (ioctl(fd, TIOCGETP, &ttyb) < 0)
35 		return(NULL);
36 	/* Must be a character device. */
37 	if (fstat(fd, &sb) || !S_ISCHR(sb.st_mode))
38 		return(NULL);
39 
40 	if (db = hash_open(_PATH_DEVDB, O_RDONLY, 0, NULL)) {
41 		key.data = (u_char *)&sb.st_rdev;
42 		key.size = sizeof(sb.st_rdev);
43 		if (!(db->get)(db, &key, &data, 0)) {
44 			bcopy(data.data,
45 			    buf + sizeof(_PATH_DEV) - 1, data.size);
46 			return(buf);
47 		}
48 	}
49 	return(__oldttyname(fd, &sb));
50 }
51 
52 static char *
53 __oldttyname(fd, sb)
54 	int fd;
55 	struct stat *sb;
56 {
57 	register struct dirent *dirp;
58 	register DIR *dp;
59 	struct stat dsb;
60 	char *rval, *strcpy();
61 
62 	if ((dp = opendir(_PATH_DEV)) == NULL)
63 		return(NULL);
64 
65 	for (rval = NULL; dirp = readdir(dp);) {
66 		if (dirp->d_fileno != sb->st_ino)
67 			continue;
68 		bcopy(dirp->d_name, buf + sizeof(_PATH_DEV) - 1,
69 		    dirp->d_namlen + 1);
70 		if (stat(buf, &dsb) || sb->st_dev != dsb.st_dev ||
71 		    sb->st_ino != dsb.st_ino)
72 			continue;
73 		(void)closedir(dp);
74 		rval = buf;
75 		break;
76 	}
77 	(void)closedir(dp);
78 	return(rval);
79 }
80