blob: cd8ef94a78f951400d0d1348d4c1606acaf46776 [file] [log] [blame]
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001/*
2 * Copyright (C) 2019 The Android Open Source Project
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//#define LOG_NDEBUG 0
18#define LOG_TAG "libprocessgroup"
19
20#include <errno.h>
21#include <fcntl.h>
Suren Baghdasaryane3ad8882019-02-06 13:25:29 -080022#include <grp.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080023#include <pwd.h>
24#include <sys/mman.h>
25#include <sys/mount.h>
26#include <sys/stat.h>
27#include <sys/types.h>
28#include <time.h>
29#include <unistd.h>
30
31#include <regex>
32
33#include <android-base/file.h>
34#include <android-base/logging.h>
35#include <android-base/properties.h>
36#include <android-base/stringprintf.h>
37#include <android-base/unique_fd.h>
38#include <cgroup_map.h>
39#include <json/reader.h>
40#include <json/value.h>
41#include <processgroup/processgroup.h>
42
43using android::base::GetBoolProperty;
44using android::base::StringPrintf;
45using android::base::unique_fd;
46
47static constexpr const char* CGROUPS_DESC_FILE = "/etc/cgroups.json";
48
49static constexpr const char* CGROUP_PROCS_FILE = "/cgroup.procs";
50static constexpr const char* CGROUP_TASKS_FILE = "/tasks";
51static constexpr const char* CGROUP_TASKS_FILE_V2 = "/cgroup.tasks";
52
53static bool Mkdir(const std::string& path, mode_t mode, const std::string& uid,
54 const std::string& gid) {
55 if (mode == 0) {
56 mode = 0755;
57 }
58
59 if (mkdir(path.c_str(), mode) != 0) {
60 /* chmod in case the directory already exists */
61 if (errno == EEXIST) {
62 if (fchmodat(AT_FDCWD, path.c_str(), mode, AT_SYMLINK_NOFOLLOW) != 0) {
63 // /acct is a special case when the directory already exists
64 // TODO: check if file mode is already what we want instead of using EROFS
65 if (errno != EROFS) {
66 PLOG(ERROR) << "fchmodat() failed for " << path;
67 return false;
68 }
69 }
70 } else {
71 PLOG(ERROR) << "mkdir() failed for " << path;
72 return false;
73 }
74 }
75
Suren Baghdasaryane3ad8882019-02-06 13:25:29 -080076 if (uid.empty()) {
77 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080078 }
79
Suren Baghdasaryane3ad8882019-02-06 13:25:29 -080080 passwd* uid_pwd = getpwnam(uid.c_str());
81 if (!uid_pwd) {
82 PLOG(ERROR) << "Unable to decode UID for '" << uid << "'";
83 return false;
84 }
85
86 uid_t pw_uid = uid_pwd->pw_uid;
87 gid_t gr_gid = -1;
88 if (!gid.empty()) {
89 group* gid_pwd = getgrnam(gid.c_str());
90 if (!gid_pwd) {
91 PLOG(ERROR) << "Unable to decode GID for '" << gid << "'";
92 return false;
93 }
94 gr_gid = gid_pwd->gr_gid;
95 }
96
97 if (lchown(path.c_str(), pw_uid, gr_gid) < 0) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080098 PLOG(ERROR) << "lchown() failed for " << path;
99 return false;
100 }
101
102 /* chown may have cleared S_ISUID and S_ISGID, chmod again */
103 if (mode & (S_ISUID | S_ISGID)) {
104 if (fchmodat(AT_FDCWD, path.c_str(), mode, AT_SYMLINK_NOFOLLOW) != 0) {
105 PLOG(ERROR) << "fchmodat() failed for " << path;
106 return false;
107 }
108 }
109
110 return true;
111}
112
113static bool ReadDescriptors(std::map<std::string, CgroupDescriptor>* descriptors) {
114 std::vector<CgroupDescriptor> result;
115 std::string json_doc;
116
117 if (!android::base::ReadFileToString(CGROUPS_DESC_FILE, &json_doc)) {
118 LOG(ERROR) << "Failed to read task profiles from " << CGROUPS_DESC_FILE;
119 return false;
120 }
121
122 Json::Reader reader;
123 Json::Value root;
124 if (!reader.parse(json_doc, root)) {
125 LOG(ERROR) << "Failed to parse cgroups description: " << reader.getFormattedErrorMessages();
126 return false;
127 }
128
129 Json::Value cgroups = root["Cgroups"];
130 for (Json::Value::ArrayIndex i = 0; i < cgroups.size(); ++i) {
131 std::string name = cgroups[i]["Controller"].asString();
132 descriptors->emplace(std::make_pair(
133 name,
Suren Baghdasaryanc7602312019-02-02 16:09:17 -0800134 CgroupDescriptor(1, name, cgroups[i]["Path"].asString(),
135 std::strtoul(cgroups[i]["Mode"].asString().c_str(), 0, 8),
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800136 cgroups[i]["UID"].asString(), cgroups[i]["GID"].asString())));
137 }
138
139 Json::Value cgroups2 = root["Cgroups2"];
140 descriptors->emplace(std::make_pair(
141 CGROUPV2_CONTROLLER_NAME,
142 CgroupDescriptor(2, CGROUPV2_CONTROLLER_NAME, cgroups2["Path"].asString(),
Suren Baghdasaryanc7602312019-02-02 16:09:17 -0800143 std::strtoul(cgroups2["Mode"].asString().c_str(), 0, 8),
144 cgroups2["UID"].asString(), cgroups2["GID"].asString())));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800145
146 return true;
147}
148
Suren Baghdasaryanff25a5f2019-02-02 23:12:01 -0800149// To avoid issues in sdk_mac build
150#if defined(__ANDROID__)
151
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800152static bool SetupCgroup(const CgroupDescriptor& descriptor) {
153 const CgroupController* controller = descriptor.controller();
154
155 // mkdir <path> [mode] [owner] [group]
156 if (!Mkdir(controller->path(), descriptor.mode(), descriptor.uid(), descriptor.gid())) {
157 PLOG(ERROR) << "Failed to create directory for " << controller->name() << " cgroup";
158 return false;
159 }
160
161 int result;
162 if (controller->version() == 2) {
163 result = mount("none", controller->path(), "cgroup2", MS_NODEV | MS_NOEXEC | MS_NOSUID,
164 nullptr);
165 } else {
166 // Unfortunately historically cpuset controller was mounted using a mount command
167 // different from all other controllers. This results in controller attributes not
168 // to be prepended with controller name. For example this way instead of
169 // /dev/cpuset/cpuset.cpus the attribute becomes /dev/cpuset/cpus which is what
170 // the system currently expects.
171 if (!strcmp(controller->name(), "cpuset")) {
172 // mount cpuset none /dev/cpuset nodev noexec nosuid
173 result = mount("none", controller->path(), controller->name(),
174 MS_NODEV | MS_NOEXEC | MS_NOSUID, nullptr);
175 } else {
176 // mount cgroup none <path> nodev noexec nosuid <controller>
177 result = mount("none", controller->path(), "cgroup", MS_NODEV | MS_NOEXEC | MS_NOSUID,
178 controller->name());
179 }
180 }
181
182 if (result < 0) {
183 PLOG(ERROR) << "Failed to mount " << controller->name() << " cgroup";
184 return false;
185 }
186
187 return true;
188}
189
Suren Baghdasaryanff25a5f2019-02-02 23:12:01 -0800190#else
191
192// Stubs for non-Android targets.
193static bool SetupCgroup(const CgroupDescriptor&) {
194 return false;
195}
196
197#endif
198
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800199static bool WriteRcFile(const std::map<std::string, CgroupDescriptor>& descriptors) {
200 std::string cgroup_rc_path = StringPrintf("%s/%s", CGROUPS_RC_DIR, CgroupMap::CGROUPS_RC_FILE);
201 unique_fd fd(TEMP_FAILURE_RETRY(open(cgroup_rc_path.c_str(),
202 O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC,
203 S_IRUSR | S_IRGRP | S_IROTH)));
204 if (fd < 0) {
205 PLOG(ERROR) << "open() failed for " << cgroup_rc_path;
206 return false;
207 }
208
209 CgroupFile fl;
210 fl.version_ = CgroupFile::FILE_CURR_VERSION;
211 fl.controller_count_ = descriptors.size();
212 int ret = TEMP_FAILURE_RETRY(write(fd, &fl, sizeof(fl)));
213 if (ret < 0) {
214 PLOG(ERROR) << "write() failed for " << cgroup_rc_path;
215 return false;
216 }
217
218 for (const auto& [name, descriptor] : descriptors) {
219 ret = TEMP_FAILURE_RETRY(write(fd, descriptor.controller(), sizeof(CgroupController)));
220 if (ret < 0) {
221 PLOG(ERROR) << "write() failed for " << cgroup_rc_path;
222 return false;
223 }
224 }
225
226 return true;
227}
228
229CgroupController::CgroupController(uint32_t version, const std::string& name,
230 const std::string& path) {
231 version_ = version;
232 strncpy(name_, name.c_str(), sizeof(name_) - 1);
233 name_[sizeof(name_) - 1] = '\0';
234 strncpy(path_, path.c_str(), sizeof(path_) - 1);
235 path_[sizeof(path_) - 1] = '\0';
236}
237
238std::string CgroupController::GetTasksFilePath(const std::string& path) const {
239 std::string tasks_path = path_;
240
241 if (!path.empty()) {
242 tasks_path += "/" + path;
243 }
244 return (version_ == 1) ? tasks_path + CGROUP_TASKS_FILE : tasks_path + CGROUP_TASKS_FILE_V2;
245}
246
247std::string CgroupController::GetProcsFilePath(const std::string& path, uid_t uid,
248 pid_t pid) const {
249 std::string proc_path(path_);
250 proc_path.append("/").append(path);
251 proc_path = regex_replace(proc_path, std::regex("<uid>"), std::to_string(uid));
252 proc_path = regex_replace(proc_path, std::regex("<pid>"), std::to_string(pid));
253
254 return proc_path.append(CGROUP_PROCS_FILE);
255}
256
257bool CgroupController::GetTaskGroup(int tid, std::string* group) const {
258 std::string file_name = StringPrintf("/proc/%d/cgroup", tid);
259 std::string content;
260 if (!android::base::ReadFileToString(file_name, &content)) {
261 LOG(ERROR) << "Failed to read " << file_name;
262 return false;
263 }
264
265 // if group is null and tid exists return early because
266 // user is not interested in cgroup membership
267 if (group == nullptr) {
268 return true;
269 }
270
271 std::string cg_tag = StringPrintf(":%s:", name_);
272 size_t start_pos = content.find(cg_tag);
273 if (start_pos == std::string::npos) {
274 return false;
275 }
276
277 start_pos += cg_tag.length() + 1; // skip '/'
278 size_t end_pos = content.find('\n', start_pos);
279 if (end_pos == std::string::npos) {
280 *group = content.substr(start_pos, std::string::npos);
281 } else {
282 *group = content.substr(start_pos, end_pos - start_pos);
283 }
284
285 return true;
286}
287
288CgroupDescriptor::CgroupDescriptor(uint32_t version, const std::string& name,
289 const std::string& path, mode_t mode, const std::string& uid,
290 const std::string& gid)
291 : controller_(version, name, path), mode_(mode), uid_(uid), gid_(gid) {}
292
293CgroupMap::CgroupMap() : cg_file_data_(nullptr), cg_file_size_(0) {
294 if (!LoadRcFile()) {
295 PLOG(ERROR) << "CgroupMap::LoadRcFile called for [" << getpid() << "] failed";
296 }
297}
298
299CgroupMap::~CgroupMap() {
300 if (cg_file_data_) {
301 munmap(cg_file_data_, cg_file_size_);
302 cg_file_data_ = nullptr;
303 cg_file_size_ = 0;
304 }
305}
306
307CgroupMap& CgroupMap::GetInstance() {
308 static CgroupMap instance;
309 return instance;
310}
311
312bool CgroupMap::LoadRcFile() {
313 struct stat sb;
314
315 if (cg_file_data_) {
316 // Data already initialized
317 return true;
318 }
319
320 std::string cgroup_rc_path = StringPrintf("%s/%s", CGROUPS_RC_DIR, CGROUPS_RC_FILE);
321 unique_fd fd(TEMP_FAILURE_RETRY(open(cgroup_rc_path.c_str(), O_RDONLY | O_CLOEXEC)));
322 if (fd < 0) {
323 PLOG(ERROR) << "open() failed for " << cgroup_rc_path;
324 return false;
325 }
326
327 if (fstat(fd, &sb) < 0) {
328 PLOG(ERROR) << "fstat() failed for " << cgroup_rc_path;
329 return false;
330 }
331
332 cg_file_size_ = sb.st_size;
333 if (cg_file_size_ < sizeof(CgroupFile)) {
334 PLOG(ERROR) << "Invalid file format " << cgroup_rc_path;
335 return false;
336 }
337
338 cg_file_data_ = (CgroupFile*)mmap(nullptr, cg_file_size_, PROT_READ, MAP_SHARED, fd, 0);
339 if (cg_file_data_ == MAP_FAILED) {
340 PLOG(ERROR) << "Failed to mmap " << cgroup_rc_path;
341 return false;
342 }
343
344 if (cg_file_data_->version_ != CgroupFile::FILE_CURR_VERSION) {
345 PLOG(ERROR) << cgroup_rc_path << " file version mismatch";
346 return false;
347 }
348
349 return true;
350}
351
352void CgroupMap::Print() {
353 LOG(INFO) << "File version = " << cg_file_data_->version_;
354 LOG(INFO) << "File controller count = " << cg_file_data_->controller_count_;
355
356 LOG(INFO) << "Mounted cgroups:";
357 CgroupController* controller = (CgroupController*)(cg_file_data_ + 1);
358 for (int i = 0; i < cg_file_data_->controller_count_; i++, controller++) {
359 LOG(INFO) << "\t" << controller->name() << " ver " << controller->version() << " path "
360 << controller->path();
361 }
362}
363
364bool CgroupMap::SetupCgroups() {
365 std::map<std::string, CgroupDescriptor> descriptors;
366
367 // load cgroups.json file
368 if (!ReadDescriptors(&descriptors)) {
369 PLOG(ERROR) << "Failed to load cgroup description file";
370 return false;
371 }
372
373 // setup cgroups
374 for (const auto& [name, descriptor] : descriptors) {
375 if (!SetupCgroup(descriptor)) {
376 // issue a warning and proceed with the next cgroup
377 // TODO: mark the descriptor as invalid and skip it in WriteRcFile()
378 LOG(WARNING) << "Failed to setup " << name << " cgroup";
379 }
380 }
381
382 // mkdir <CGROUPS_RC_DIR> 0711 system system
383 if (!Mkdir(CGROUPS_RC_DIR, 0711, "system", "system")) {
384 PLOG(ERROR) << "Failed to create directory for <CGROUPS_RC_FILE> file";
385 return false;
386 }
387
388 // Generate <CGROUPS_RC_FILE> file which can be directly mmapped into
389 // process memory. This optimizes performance, memory usage
390 // and limits infrormation shared with unprivileged processes
391 // to the minimum subset of information from cgroups.json
392 if (!WriteRcFile(descriptors)) {
393 LOG(ERROR) << "Failed to write " << CGROUPS_RC_FILE << " file";
394 return false;
395 }
396
397 std::string cgroup_rc_path = StringPrintf("%s/%s", CGROUPS_RC_DIR, CGROUPS_RC_FILE);
398 // chmod 0644 <cgroup_rc_path>
399 if (fchmodat(AT_FDCWD, cgroup_rc_path.c_str(), 0644, AT_SYMLINK_NOFOLLOW) < 0) {
400 LOG(ERROR) << "fchmodat() failed";
401 return false;
402 }
403
404 return true;
405}
406
407const CgroupController* CgroupMap::FindController(const std::string& name) const {
408 if (!cg_file_data_) {
409 return nullptr;
410 }
411
412 // skip the file header to get to the first controller
413 CgroupController* controller = (CgroupController*)(cg_file_data_ + 1);
414 for (int i = 0; i < cg_file_data_->controller_count_; i++, controller++) {
415 if (name == controller->name()) {
416 return controller;
417 }
418 }
419
420 return nullptr;
421}