2 * Copyright (c) 2012-2013 Todd C. Miller <Todd.Miller@courtesan.com>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 /* Large files not supported by procfs.h */
20 #if defined(HAVE_PROCFS_H) || defined(HAVE_SYS_PROCFS_H)
21 # undef _FILE_OFFSET_BITS
25 #include <sys/types.h>
26 #include <sys/param.h>
28 #if defined(MAJOR_IN_MKDEV)
29 # include <sys/mkdev.h>
30 #elif defined(MAJOR_IN_SYSMACROS)
31 # include <sys/sysmacros.h>
41 #endif /* STDC_HEADERS */
43 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
47 #endif /* HAVE_STRING_H */
50 #endif /* HAVE_STRINGS_H */
53 #endif /* HAVE_UNISTD_H */
59 # define NAMLEN(dirent) strlen((dirent)->d_name)
61 # define dirent direct
62 # define NAMLEN(dirent) (dirent)->d_namlen
63 # ifdef HAVE_SYS_NDIR_H
64 # include <sys/ndir.h>
66 # ifdef HAVE_SYS_DIR_H
73 #if defined(HAVE_STRUCT_KINFO_PROC_P_TDEV) || defined (HAVE_STRUCT_KINFO_PROC_KP_EPROC_E_TDEV) || defined(HAVE_STRUCT_KINFO_PROC2_P_TDEV)
74 # include <sys/sysctl.h>
75 #elif defined(HAVE_STRUCT_KINFO_PROC_KI_TDEV)
76 # include <sys/sysctl.h>
77 # include <sys/user.h>
79 #if defined(HAVE_PROCFS_H)
81 #elif defined(HAVE_SYS_PROCFS_H)
82 # include <sys/procfs.h>
88 * How to access the tty device number in struct kinfo_proc.
90 #if defined(HAVE_STRUCT_KINFO_PROC2_P_TDEV)
91 # define SUDO_KERN_PROC KERN_PROC2
92 # define sudo_kinfo_proc kinfo_proc2
93 # define sudo_kp_tdev p_tdev
94 # define sudo_kp_namelen 6
95 #elif defined(HAVE_STRUCT_KINFO_PROC_P_TDEV)
96 # define SUDO_KERN_PROC KERN_PROC
97 # define sudo_kinfo_proc kinfo_proc
98 # define sudo_kp_tdev p_tdev
99 # define sudo_kp_namelen 6
100 #elif defined(HAVE_STRUCT_KINFO_PROC_KI_TDEV)
101 # define SUDO_KERN_PROC KERN_PROC
102 # define sudo_kinfo_proc kinfo_proc
103 # define sudo_kp_tdev ki_tdev
104 # define sudo_kp_namelen 4
105 #elif defined(HAVE_STRUCT_KINFO_PROC_KP_EPROC_E_TDEV)
106 # define SUDO_KERN_PROC KERN_PROC
107 # define sudo_kinfo_proc kinfo_proc
108 # define sudo_kp_tdev kp_eproc.e_tdev
109 # define sudo_kp_namelen 4
112 #if defined(sudo_kp_tdev)
114 * Like ttyname() but uses a dev_t instead of an open fd.
115 * Caller is responsible for freeing the returned string.
116 * The BSD version uses devname()
119 sudo_ttyname_dev(dev_t tdev)
121 char *dev, *tty = NULL;
122 debug_decl(sudo_ttyname_dev, SUDO_DEBUG_UTIL)
124 /* Some versions of devname() return NULL on failure, others do not. */
125 dev = devname(tdev, S_IFCHR);
126 if (dev != NULL && *dev != '?' && *dev != '#') {
128 /* devname() doesn't use the /dev/ prefix, add one... */
129 size_t len = sizeof(_PATH_DEV) + strlen(dev);
131 strlcpy(tty, _PATH_DEV, len);
132 strlcat(tty, dev, len);
134 /* Should not happen but just in case... */
138 debug_return_str(tty);
140 #elif defined(HAVE__TTYNAME_DEV)
141 extern char *_ttyname_dev(dev_t rdev, char *buffer, size_t buflen);
144 * Like ttyname() but uses a dev_t instead of an open fd.
145 * Caller is responsible for freeing the returned string.
146 * This version is just a wrapper around _ttyname_dev().
149 sudo_ttyname_dev(dev_t tdev)
151 char buf[TTYNAME_MAX], *tty;
152 debug_decl(sudo_ttyname_dev, SUDO_DEBUG_UTIL)
154 tty = _ttyname_dev(tdev, buf, sizeof(buf));
156 debug_return_str(estrdup(tty));
160 * Devices to search before doing a breadth-first scan.
162 static char *search_devs[] = {
172 static char *ignore_devs[] = {
181 * Do a breadth-first scan of dir looking for the specified device.
184 sudo_ttyname_scan(const char *dir, dev_t rdev, bool builtin)
187 char pathbuf[PATH_MAX], **subdirs = NULL, *devname = NULL;
188 size_t sdlen, d_len, len, num_subdirs = 0, max_subdirs = 0;
192 debug_decl(sudo_ttyname_scan, SUDO_DEBUG_UTIL)
194 if (dir[0] == '\0' || (d = opendir(dir)) == NULL)
198 if (dir[sdlen - 1] == '/')
200 if (sdlen + 1 >= sizeof(pathbuf)) {
201 errno = ENAMETOOLONG;
202 warning("%.*s/", (int)sdlen, dir);
205 memcpy(pathbuf, dir, sdlen);
206 pathbuf[sdlen++] = '/';
207 pathbuf[sdlen] = '\0';
209 while ((dp = readdir(d)) != NULL) {
210 /* Skip anything starting with "." */
211 if (dp->d_name[0] == '.')
215 if (sdlen + d_len >= sizeof(pathbuf))
217 memcpy(&pathbuf[sdlen], dp->d_name, d_len + 1); /* copy NUL too */
220 for (i = 0; ignore_devs[i] != NULL; i++) {
221 len = strlen(ignore_devs[i]);
222 if (ignore_devs[i][len - 1] == '/')
224 if (d_len == len && strncmp(pathbuf, ignore_devs[i], len) == 0)
227 if (ignore_devs[i] != NULL)
230 /* Skip entries in search_devs; we already checked them. */
231 for (i = 0; search_devs[i] != NULL; i++) {
232 len = strlen(search_devs[i]);
233 if (search_devs[i][len - 1] == '/')
235 if (d_len == len && strncmp(pathbuf, search_devs[i], len) == 0)
238 if (search_devs[i] != NULL)
241 # if defined(HAVE_STRUCT_DIRENT_D_TYPE) && defined(DTTOIF)
242 /* Use d_type to avoid a stat() if possible. */
243 /* Convert d_type to stat-style type bits but follow links. */
244 if (dp->d_type != DT_LNK && dp->d_type != DT_CHR)
245 sb.st_mode = DTTOIF(dp->d_type);
248 if (stat(pathbuf, &sb) == -1)
250 if (S_ISDIR(sb.st_mode)) {
252 /* Add to list of subdirs to search. */
253 if (num_subdirs + 1 > max_subdirs) {
255 subdirs = erealloc3(subdirs, max_subdirs, sizeof(char *));
257 subdirs[num_subdirs++] = estrdup(pathbuf);
261 if (S_ISCHR(sb.st_mode) && sb.st_rdev == rdev) {
262 devname = estrdup(pathbuf);
267 /* Search subdirs if we didn't find it in the root level. */
268 for (i = 0; devname == NULL && i < num_subdirs; i++)
269 devname = sudo_ttyname_scan(subdirs[i], rdev, false);
274 for (i = 0; i < num_subdirs; i++)
277 debug_return_str(devname);
281 * Like ttyname() but uses a dev_t instead of an open fd.
282 * Caller is responsible for freeing the returned string.
286 sudo_ttyname_dev(dev_t rdev)
290 char buf[PATH_MAX], **sd, *devname, *tty = NULL;
291 debug_decl(sudo_ttyname_dev, SUDO_DEBUG_UTIL)
294 * First check search_devs for common tty devices.
296 for (sd = search_devs; tty == NULL && (devname = *sd) != NULL; sd++) {
297 len = strlen(devname);
298 if (devname[len - 1] == '/') {
299 if (strcmp(devname, "/dev/pts/") == 0) {
300 /* Special case /dev/pts */
301 (void)snprintf(buf, sizeof(buf), "%spts/%u", _PATH_DEV,
302 (unsigned int)minor(rdev));
303 if (stat(buf, &sb) == 0) {
304 if (S_ISCHR(sb.st_mode) && sb.st_rdev == rdev)
308 /* Traverse directory */
309 tty = sudo_ttyname_scan(devname, rdev, true);
312 if (stat(devname, &sb) == 0) {
313 if (S_ISCHR(sb.st_mode) && sb.st_rdev == rdev)
314 tty = estrdup(devname);
320 * Not found? Do a breadth-first traversal of /dev/.
323 tty = sudo_ttyname_scan(_PATH_DEV, rdev, false);
325 debug_return_str(tty);
329 #if defined(sudo_kp_tdev)
331 * Return a string from ttyname() containing the tty to which the process is
332 * attached or NULL if there is no tty associated with the process (or its
333 * parent). First tries sysctl using the current pid, then the parent's pid.
334 * Falls back on ttyname of std{in,out,err} if that fails.
337 get_process_ttyname(void)
340 struct sudo_kinfo_proc *ki_proc = NULL;
341 size_t size = sizeof(*ki_proc);
343 debug_decl(get_process_ttyname, SUDO_DEBUG_UTIL)
346 * Lookup tty for this process and, failing that, our parent.
347 * Even if we redirect std{in,out,err} the kernel should still know.
349 for (i = 0; tty == NULL && i < 2; i++) {
351 mib[1] = SUDO_KERN_PROC;
352 mib[2] = KERN_PROC_PID;
353 mib[3] = i ? (int)getppid() : (int)getpid();
354 mib[4] = sizeof(*ki_proc);
358 ki_proc = erealloc(ki_proc, size);
359 rc = sysctl(mib, sudo_kp_namelen, ki_proc, &size, NULL, 0);
360 } while (rc == -1 && errno == ENOMEM);
362 if (ki_proc->sudo_kp_tdev != (dev_t)-1) {
363 tty = sudo_ttyname_dev(ki_proc->sudo_kp_tdev);
365 sudo_debug_printf(SUDO_DEBUG_WARN,
366 "unable to map device number %u to name",
367 ki_proc->sudo_kp_tdev);
371 sudo_debug_printf(SUDO_DEBUG_WARN,
372 "unable to resolve tty via KERN_PROC: %s", strerror(errno));
377 debug_return_str(tty);
379 #elif defined(HAVE_STRUCT_PSINFO_PR_TTYDEV)
381 * Return a string from ttyname() containing the tty to which the process is
382 * attached or NULL if there is no tty associated with the process (or its
383 * parent). First tries /proc/pid/psinfo, then /proc/ppid/psinfo.
384 * Falls back on ttyname of std{in,out,err} if that fails.
387 get_process_ttyname(void)
389 char path[PATH_MAX], *tty = NULL;
390 struct psinfo psinfo;
393 debug_decl(get_process_ttyname, SUDO_DEBUG_UTIL)
395 /* Try to determine the tty from pr_ttydev in /proc/pid/psinfo. */
396 for (i = 0; tty == NULL && i < 2; i++) {
397 (void)snprintf(path, sizeof(path), "/proc/%u/psinfo",
398 i ? (unsigned int)getppid() : (unsigned int)getpid());
399 if ((fd = open(path, O_RDONLY, 0)) == -1)
401 nread = read(fd, &psinfo, sizeof(psinfo));
403 if (nread == (ssize_t)sizeof(psinfo)) {
404 dev_t rdev = (dev_t)psinfo.pr_ttydev;
406 if (psinfo.pr_ttydev & DEVNO64)
407 rdev = makedev(major64(psinfo.pr_ttydev), minor64(psinfo.pr_ttydev));
409 if (rdev != (dev_t)-1)
410 tty = sudo_ttyname_dev(rdev);
414 debug_return_str(tty);
416 #elif defined(__linux__)
418 * Return a string from ttyname() containing the tty to which the process is
419 * attached or NULL if there is no tty associated with the process (or its
420 * parent). First tries field 7 in /proc/pid/stat, then /proc/ppid/stat.
421 * Falls back on ttyname of std{in,out,err} if that fails.
424 get_process_ttyname(void)
426 char *line = NULL, *tty = NULL;
430 debug_decl(get_process_ttyname, SUDO_DEBUG_UTIL)
432 /* Try to determine the tty from tty_nr in /proc/pid/stat. */
433 for (i = 0; tty == NULL && i < 2; i++) {
436 (void)snprintf(path, sizeof(path), "/proc/%u/stat",
437 i ? (unsigned int)getppid() : (unsigned int)getpid());
438 if ((fp = fopen(path, "r")) == NULL)
440 len = getline(&line, &linesize, fp);
443 /* Field 7 is the tty dev (0 if no tty) */
446 while (*cp != '\0') {
449 dev_t tdev = (dev_t)atoi(cp);
451 tty = sudo_ttyname_dev(tdev);
460 debug_return_str(tty);
464 * Return a string from ttyname() containing the tty to which the process is
465 * attached or NULL if there is no tty associated with the process.
469 get_process_ttyname(void)
472 debug_decl(get_process_ttyname, SUDO_DEBUG_UTIL)
474 if ((tty = ttyname(STDIN_FILENO)) == NULL) {
475 if ((tty = ttyname(STDOUT_FILENO)) == NULL)
476 tty = ttyname(STDERR_FILENO);
479 debug_return_str(estrdup(tty));