1 // Copyright (c) 2009 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // The following is duplicated from base/linux_utils.cc.
6 // We shouldn't link against C++ code in a setuid binary.
8 #define _GNU_SOURCE // For O_DIRECTORY
9 #include "linux_util.h"
19 #include <sys/types.h>
22 // expected prefix of the target of the /proc/self/fd/%d link for a socket
23 static const char kSocketLinkPrefix[] = "socket:[";
25 // Parse a symlink in /proc/pid/fd/$x and return the inode number of the
27 // inode_out: (output) set to the inode number on success
28 // path: e.g. /proc/1234/fd/5 (must be a UNIX domain socket descriptor)
29 static bool ProcPathGetInodeAt(ino_t* inode_out, int base_dir_fd,
31 // We also check that the path is relative.
32 if (!inode_out || !path || *path == '/')
35 const ssize_t n = readlinkat(base_dir_fd, path, buf, sizeof(buf) - 1);
40 if (memcmp(kSocketLinkPrefix, buf, sizeof(kSocketLinkPrefix) - 1))
45 const unsigned long long int inode_ull =
46 strtoull(buf + sizeof(kSocketLinkPrefix) - 1, &endptr, 10);
47 if (inode_ull == ULLONG_MAX || !endptr || *endptr != ']' || errno != 0)
50 *inode_out = inode_ull;
54 static DIR* opendirat(int base_dir_fd, const char* name) {
55 // Also check that |name| is relative.
56 if (base_dir_fd < 0 || !name || *name == '/')
58 int new_dir_fd = openat(base_dir_fd, name, O_RDONLY | O_DIRECTORY);
62 return fdopendir(new_dir_fd);
65 bool FindProcessHoldingSocket(pid_t* pid_out, ino_t socket_inode) {
66 bool already_found = false;
68 DIR* proc = opendir("/proc");
72 const uid_t uid = getuid();
74 while ((dent = readdir(proc))) {
77 const unsigned long int pid_ul = strtoul(dent->d_name, &endptr, 10);
78 if (pid_ul == ULONG_MAX || !endptr || *endptr || errno != 0)
81 // We have this setuid code here because the zygote and its children have
82 // /proc/$pid/fd owned by root. While scanning through /proc, we add this
83 // extra check so users cannot accidentally gain information about other
84 // users' processes. To determine process ownership, we use the property
85 // that if user foo owns process N, then /proc/N is owned by foo.
90 snprintf(buf, sizeof(buf), "/proc/%lu", pid_ul);
91 proc_pid_fd = open(buf, O_RDONLY | O_DIRECTORY);
94 if (fstat(proc_pid_fd, &statbuf) < 0 || uid != statbuf.st_uid) {
100 DIR* fd = opendirat(proc_pid_fd, "fd");
106 while ((dent = readdir(fd))) {
108 int printed = snprintf(buf, sizeof(buf), "fd/%s", dent->d_name);
109 if (printed < 0 || printed >= (int)(sizeof(buf) - 1)) {
114 if (ProcPathGetInodeAt(&fd_inode, proc_pid_fd, buf)) {
115 if (fd_inode == socket_inode) {
123 already_found = true;
134 return already_found;