]> git.sven.stormbind.net Git - sven/jattach.git/blob - src/posix/psutil.c
releasing package jattach version 2.2-1
[sven/jattach.git] / src / posix / psutil.c
1 /*
2  * Copyright jattach authors
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                     pid = atoi(entry->d_name);
97                     break;
98                 }
99             }
100         }
101         closedir(dir);
102     }
103
104     return pid;
105 }
106
107 int get_tmp_path_r(int pid, char* buf, size_t bufsize) {
108     if (snprintf(buf, bufsize, "/proc/%d/root/tmp", pid) >= bufsize) {
109         return -1;
110     }
111
112     // Check if the remote /tmp can be accessed via /proc/[pid]/root
113     struct stat stats;
114     return stat(buf, &stats);
115 }
116
117 int get_process_info(int pid, uid_t* uid, gid_t* gid, int* nspid) {
118     // Parse /proc/pid/status to find process credentials
119     char path[64];
120     snprintf(path, sizeof(path), "/proc/%d/status", pid);
121     FILE* status_file = fopen(path, "r");
122     if (status_file == NULL) {
123         return -1;
124     }
125
126     char* line = NULL;
127     size_t size;
128     int nspid_found = 0;
129
130     while (getline(&line, &size, status_file) != -1) {
131         if (strncmp(line, "Uid:", 4) == 0 && strtok(line + 4, "\t ") != NULL) {
132             // Get the effective UID, which is the second value in the line
133             *uid = (uid_t)atoi(strtok(NULL, "\t "));
134         } else if (strncmp(line, "Gid:", 4) == 0 && strtok(line + 4, "\t ") != NULL) {
135             // Get the effective GID, which is the second value in the line
136             *gid = (gid_t)atoi(strtok(NULL, "\t "));
137         } else if (strncmp(line, "NStgid:", 7) == 0) {
138             // PID namespaces can be nested; the last one is the innermost one
139             char* s;
140             for (s = strtok(line + 7, "\t "); s != NULL; s = strtok(NULL, "\t ")) {
141                 *nspid = atoi(s);
142             }
143             nspid_found = 1;
144         }
145     }
146
147     free(line);
148     fclose(status_file);
149
150     if (!nspid_found) {
151         *nspid = alt_lookup_nspid(pid);
152     }
153
154     return 0;
155 }
156
157 int enter_ns(int pid, const char* type) {
158 #ifdef __NR_setns
159     char path[64], selfpath[64];
160     snprintf(path, sizeof(path), "/proc/%d/ns/%s", pid, type);
161     snprintf(selfpath, sizeof(selfpath), "/proc/self/ns/%s", type);
162
163     struct stat oldns_stat, newns_stat;
164     if (stat(selfpath, &oldns_stat) == 0 && stat(path, &newns_stat) == 0) {
165         // Don't try to call setns() if we're in the same namespace already
166         if (oldns_stat.st_ino != newns_stat.st_ino) {
167             int newns = open(path, O_RDONLY);
168             if (newns < 0) {
169                 return -1;
170             }
171
172             // Some ancient Linux distributions do not have setns() function
173             int result = syscall(__NR_setns, newns, 0);
174             close(newns);
175             return result < 0 ? -1 : 1;
176         }
177     }
178 #endif // __NR_setns
179
180     return 0;
181 }
182
183 #elif defined(__APPLE__)
184
185 #include <sys/sysctl.h>
186
187 // macOS has a secure per-user temporary directory
188 int get_tmp_path_r(int pid, char* buf, size_t bufsize) {
189     size_t path_size = confstr(_CS_DARWIN_USER_TEMP_DIR, buf, bufsize);
190     return path_size > 0 && path_size <= sizeof(tmp_path) ? 0 : -1;
191 }
192
193 int get_process_info(int pid, uid_t* uid, gid_t* gid, int* nspid) {
194     int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
195     struct kinfo_proc info;
196     size_t len = sizeof(info);
197
198     if (sysctl(mib, 4, &info, &len, NULL, 0) < 0 || len <= 0) {
199         return -1;
200     }
201
202     *uid = info.kp_eproc.e_ucred.cr_uid;
203     *gid = info.kp_eproc.e_ucred.cr_gid;
204     *nspid = pid;
205     return 0;
206 }
207
208 // This is a Linux-specific API; nothing to do on macOS and FreeBSD
209 int enter_ns(int pid, const char* type) {
210     return 0;
211 }
212
213 #else // __FreeBSD__
214
215 #include <sys/sysctl.h>
216 #include <sys/user.h>
217
218 // Use default /tmp path on FreeBSD
219 int get_tmp_path_r(int pid, char* buf, size_t bufsize) {
220     return -1;
221 }
222
223 int get_process_info(int pid, uid_t* uid, gid_t* gid, int* nspid) {
224     int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
225     struct kinfo_proc info;
226     size_t len = sizeof(info);
227
228     if (sysctl(mib, 4, &info, &len, NULL, 0) < 0 || len <= 0) {
229         return -1;
230     }
231
232     *uid = info.ki_uid;
233     *gid = info.ki_groups[0];
234     *nspid = pid;
235     return 0;
236 }
237
238 // This is a Linux-specific API; nothing to do on macOS and FreeBSD
239 int enter_ns(int pid, const char* type) {
240     return 0;
241 }
242
243 #endif