]> git.sven.stormbind.net Git - sven/jattach.git/blob - src/posix/psutil.c
New upstream version 2.0
[sven/jattach.git] / src / posix / psutil.c
1 /*
2  * Copyright 2021 Andrei Pangin
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <sys/stat.h>
21 #include <sys/syscall.h>
22 #include <dirent.h>
23 #include <fcntl.h>
24 #include <unistd.h>
25 #include "psutil.h"
26
27
28 // Less than MAX_PATH to leave some space for appending
29 char tmp_path[MAX_PATH - 100];
30
31 // Called just once to fill in tmp_path buffer
32 void get_tmp_path(int pid) {
33     // Try user-provided alternative path first
34     const char* jattach_path = getenv("JATTACH_PATH");
35     if (jattach_path != NULL && strlen(jattach_path) < sizeof(tmp_path)) {
36         strcpy(tmp_path, jattach_path);
37         return;
38     }
39
40     if (get_tmp_path_r(pid, tmp_path, sizeof(tmp_path)) != 0) {
41         strcpy(tmp_path, "/tmp");
42     }
43 }
44
45
46 #ifdef __linux__
47
48 // The first line of /proc/pid/sched looks like
49 // java (1234, #threads: 12)
50 // where 1234 is the host PID (before Linux 4.1)
51 static int sched_get_host_pid(const char* path) {
52     static char* line = NULL;
53     size_t size;
54     int result = -1;
55
56     FILE* sched_file = fopen(path, "r");
57     if (sched_file != NULL) {
58         if (getline(&line, &size, sched_file) != -1) {
59             char* c = strrchr(line, '(');
60             if (c != NULL) {
61                 result = atoi(c + 1);
62             }
63         }
64         fclose(sched_file);
65     }
66
67     return result;
68 }
69
70 // Linux kernels < 4.1 do not export NStgid field in /proc/pid/status.
71 // Fortunately, /proc/pid/sched in a container exposes a host PID,
72 // so the idea is to scan all container PIDs to find which one matches the host PID.
73 static int alt_lookup_nspid(int pid) {
74     char path[300];
75     snprintf(path, sizeof(path), "/proc/%d/ns/pid", pid);
76
77     // Don't bother looking for container PID if we are already in the same PID namespace
78     struct stat oldns_stat, newns_stat;
79     if (stat("/proc/self/ns/pid", &oldns_stat) == 0 && stat(path, &newns_stat) == 0) {
80         if (oldns_stat.st_ino == newns_stat.st_ino) {
81             return pid;
82         }
83     }
84
85     // Otherwise browse all PIDs in the namespace of the target process
86     // trying to find which one corresponds to the host PID
87     snprintf(path, sizeof(path), "/proc/%d/root/proc", pid);
88     DIR* dir = opendir(path);
89     if (dir != NULL) {
90         struct dirent* entry;
91         while ((entry = readdir(dir)) != NULL) {
92             if (entry->d_name[0] >= '1' && entry->d_name[0] <= '9') {
93                 // Check if /proc/<container-pid>/sched points back to <host-pid>
94                 snprintf(path, sizeof(path), "/proc/%d/root/proc/%s/sched", pid, entry->d_name);
95                 if (sched_get_host_pid(path) == pid) {
96                     closedir(dir);
97                     return atoi(entry->d_name);
98                 }
99             }
100         }
101         closedir(dir);
102     }
103
104     // Could not find container pid; return host pid as the last resort
105     return pid;
106 }
107
108 int get_tmp_path_r(int pid, char* buf, size_t bufsize) {
109     if (snprintf(buf, bufsize, "/proc/%d/root/tmp", pid) >= bufsize) {
110         return -1;
111     }
112
113     // Check if the remote /tmp can be accessed via /proc/[pid]/root
114     struct stat stats;
115     return stat(buf, &stats);
116 }
117
118 int get_process_info(int pid, uid_t* uid, gid_t* gid, int* nspid) {
119     // Parse /proc/pid/status to find process credentials
120     char path[64];
121     snprintf(path, sizeof(path), "/proc/%d/status", pid);
122     FILE* status_file = fopen(path, "r");
123     if (status_file == NULL) {
124         return -1;
125     }
126
127     char* line = NULL;
128     size_t size;
129     int nspid_found = 0;
130
131     while (getline(&line, &size, status_file) != -1) {
132         if (strncmp(line, "Uid:", 4) == 0) {
133             // Get the effective UID, which is the second value in the line
134             *uid = (uid_t)atoi(strchr(line + 5, '\t'));
135         } else if (strncmp(line, "Gid:", 4) == 0) {
136             // Get the effective GID, which is the second value in the line
137             *gid = (gid_t)atoi(strchr(line + 5, '\t'));
138         } else if (strncmp(line, "NStgid:", 7) == 0) {
139             // PID namespaces can be nested; the last one is the innermost one
140             *nspid = atoi(strrchr(line, '\t'));
141             nspid_found = 1;
142         }
143     }
144
145     free(line);
146     fclose(status_file);
147
148     if (!nspid_found) {
149         *nspid = alt_lookup_nspid(pid);
150     }
151
152     return 0;
153 }
154
155 int enter_ns(int pid, const char* type) {
156 #ifdef __NR_setns
157     char path[64], selfpath[64];
158     snprintf(path, sizeof(path), "/proc/%d/ns/%s", pid, type);
159     snprintf(selfpath, sizeof(selfpath), "/proc/self/ns/%s", type);
160
161     struct stat oldns_stat, newns_stat;
162     if (stat(selfpath, &oldns_stat) == 0 && stat(path, &newns_stat) == 0) {
163         // Don't try to call setns() if we're in the same namespace already
164         if (oldns_stat.st_ino != newns_stat.st_ino) {
165             int newns = open(path, O_RDONLY);
166             if (newns < 0) {
167                 return -1;
168             }
169
170             // Some ancient Linux distributions do not have setns() function
171             int result = syscall(__NR_setns, newns, 0);
172             close(newns);
173             return result < 0 ? -1 : 1;
174         }
175     }
176 #endif // __NR_setns
177
178     return 0;
179 }
180
181 #elif defined(__APPLE__)
182
183 #include <sys/sysctl.h>
184
185 // macOS has a secure per-user temporary directory
186 int get_tmp_path_r(int pid, char* buf, size_t bufsize) {
187     size_t path_size = confstr(_CS_DARWIN_USER_TEMP_DIR, buf, bufsize);
188     return path_size > 0 && path_size <= sizeof(tmp_path) ? 0 : -1;
189 }
190
191 int get_process_info(int pid, uid_t* uid, gid_t* gid, int* nspid) {
192     int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
193     struct kinfo_proc info;
194     size_t len = sizeof(info);
195
196     if (sysctl(mib, 4, &info, &len, NULL, 0) < 0 || len <= 0) {
197         return -1;
198     }
199
200     *uid = info.kp_eproc.e_ucred.cr_uid;
201     *gid = info.kp_eproc.e_ucred.cr_gid;
202     *nspid = pid;
203     return 0;
204 }
205
206 // This is a Linux-specific API; nothing to do on macOS and FreeBSD
207 int enter_ns(int pid, const char* type) {
208     return 0;
209 }
210
211 #else // __FreeBSD__
212
213 #include <sys/sysctl.h>
214 #include <sys/user.h>
215
216 // Use default /tmp path on FreeBSD
217 int get_tmp_path_r(int pid, char* buf, size_t bufsize) {
218     return -1;
219 }
220
221 int get_process_info(int pid, uid_t* uid, gid_t* gid, int* nspid) {
222     int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
223     struct kinfo_proc info;
224     size_t len = sizeof(info);
225
226     if (sysctl(mib, 4, &info, &len, NULL, 0) < 0 || len <= 0) {
227         return -1;
228     }
229
230     *uid = info.ki_uid;
231     *gid = info.ki_groups[0];
232     *nspid = pid;
233     return 0;
234 }
235
236 // This is a Linux-specific API; nothing to do on macOS and FreeBSD
237 int enter_ns(int pid, const char* type) {
238     return 0;
239 }
240
241 #endif