tty_linux.c (2447B)
1 /* see LICENSE file for copyright and license details */ 2 #ifndef _DEFAULT_SOURCE 3 #define _DEFAULT_SOURCE /* vhangup */ 4 #endif 5 #include "../util.h" 6 7 /* the numbers are the ones linux gives ttys, and the dev the encoding 8 * of tty_nr in /proc/<pid>/stat */ 9 #if defined(__linux__) && !defined(ARUU_FORCE_POSIX) 10 #include <sys/stat.h> 11 #include <sys/sysmacros.h> 12 #include <sys/types.h> 13 14 #include <dirent.h> 15 #include <fcntl.h> 16 #include <limits.h> 17 #include <stdio.h> 18 #include <stdlib.h> 19 #include <string.h> 20 #include <unistd.h> 21 22 #include "../paths.h" 23 24 void 25 devtotty(int dev, int *tty_maj, int *tty_min) 26 { 27 *tty_maj = (dev >> 8) & 0xfff; 28 *tty_min = (dev & 0xff) | ((dev >> 12) & 0xfff00); 29 } 30 31 int 32 ttytostr(int tty_maj, int tty_min, char *str, size_t n) 33 { 34 struct stat sb; 35 struct dirent *dp; 36 DIR *dirp; 37 char path[PATH_MAX]; 38 int fd; 39 int r = 0; 40 41 switch (tty_maj) { 42 case 136: 43 snprintf(str, n, "pts/%d", tty_min); 44 return 0; 45 case 4: 46 snprintf(str, n, "tty%d", tty_min); 47 return 0; 48 default: 49 str[0] = '?'; 50 str[1] = '\0'; 51 break; 52 } 53 54 dirp = opendir("/dev"); 55 if (!dirp) { 56 weprintf("opendir /dev:"); 57 return -1; 58 } 59 60 while ((dp = readdir(dirp))) { 61 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) 62 continue; 63 64 if (strlcpy(path, ARUU_PATH_DEV "/", sizeof(path)) >= sizeof(path)) { 65 weprintf("path too long\n"); 66 r = -1; 67 goto err0; 68 } 69 if (strlcat(path, dp->d_name, sizeof(path)) >= sizeof(path)) { 70 weprintf("path too long\n"); 71 r = -1; 72 goto err0; 73 } 74 75 if (stat(path, &sb) < 0) { 76 weprintf("stat %s:", path); 77 r = -1; 78 goto err0; 79 } 80 81 if ((int)major(sb.st_rdev) == tty_maj && (int)minor(sb.st_rdev) == tty_min) { 82 fd = open(path, O_RDONLY | O_NONBLOCK); 83 if (fd < 0) 84 continue; 85 if (isatty(fd)) { 86 strlcpy(str, dp->d_name, n); 87 close(fd); 88 break; 89 } else { 90 close(fd); 91 r = -1; 92 goto err0; 93 } 94 } 95 } 96 97 err0: 98 if (closedir(dirp) < 0) { 99 weprintf("closedir /dev:"); 100 r = -1; 101 } 102 103 return r; 104 } 105 106 /* the first virtual console, and the TERM it speaks */ 107 const char * 108 ttyconsole(void) 109 { 110 return ARUU_PATH_DEV "/tty1"; 111 } 112 113 const char * 114 ttyconsterm(void) 115 { 116 return "linux"; 117 } 118 119 /* every process with the controlling tty open loses it */ 120 void 121 ttyhangup(void) 122 { 123 vhangup(); 124 } 125 #endif