blob: 1e66fa4ee1270c6236166e7f06c47cc2276a3a70 [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";
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -080048static constexpr const char* CGROUPS_DESC_VENDOR_FILE = "/vendor/etc/cgroups.json";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080049
50static constexpr const char* CGROUP_PROCS_FILE = "/cgroup.procs";
51static constexpr const char* CGROUP_TASKS_FILE = "/tasks";
52static constexpr const char* CGROUP_TASKS_FILE_V2 = "/cgroup.tasks";
53
54static bool Mkdir(const std::string& path, mode_t mode, const std::string& uid,
55 const std::string& gid) {
56 if (mode == 0) {
57 mode = 0755;
58 }
59
60 if (mkdir(path.c_str(), mode) != 0) {
61 /* chmod in case the directory already exists */
62 if (errno == EEXIST) {
63 if (fchmodat(AT_FDCWD, path.c_str(), mode, AT_SYMLINK_NOFOLLOW) != 0) {
64 // /acct is a special case when the directory already exists
65 // TODO: check if file mode is already what we want instead of using EROFS
66 if (errno != EROFS) {
67 PLOG(ERROR) << "fchmodat() failed for " << path;
68 return false;
69 }
70 }
71 } else {
72 PLOG(ERROR) << "mkdir() failed for " << path;
73 return false;
74 }
75 }
76
Suren Baghdasaryane3ad8882019-02-06 13:25:29 -080077 if (uid.empty()) {
78 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080079 }
80
Suren Baghdasaryane3ad8882019-02-06 13:25:29 -080081 passwd* uid_pwd = getpwnam(uid.c_str());
82 if (!uid_pwd) {
83 PLOG(ERROR) << "Unable to decode UID for '" << uid << "'";
84 return false;
85 }
86
87 uid_t pw_uid = uid_pwd->pw_uid;
88 gid_t gr_gid = -1;
89 if (!gid.empty()) {
90 group* gid_pwd = getgrnam(gid.c_str());
91 if (!gid_pwd) {
92 PLOG(ERROR) << "Unable to decode GID for '" << gid << "'";
93 return false;
94 }
95 gr_gid = gid_pwd->gr_gid;
96 }
97
98 if (lchown(path.c_str(), pw_uid, gr_gid) < 0) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080099 PLOG(ERROR) << "lchown() failed for " << path;
100 return false;
101 }
102
103 /* chown may have cleared S_ISUID and S_ISGID, chmod again */
104 if (mode & (S_ISUID | S_ISGID)) {
105 if (fchmodat(AT_FDCWD, path.c_str(), mode, AT_SYMLINK_NOFOLLOW) != 0) {
106 PLOG(ERROR) << "fchmodat() failed for " << path;
107 return false;
108 }
109 }
110
111 return true;
112}
113
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800114static bool ReadDescriptorsFromFile(const std::string& file_name,
115 std::map<std::string, CgroupDescriptor>* descriptors) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800116 std::vector<CgroupDescriptor> result;
117 std::string json_doc;
118
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800119 if (!android::base::ReadFileToString(file_name, &json_doc)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800120 PLOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800121 return false;
122 }
123
124 Json::Reader reader;
125 Json::Value root;
126 if (!reader.parse(json_doc, root)) {
127 LOG(ERROR) << "Failed to parse cgroups description: " << reader.getFormattedErrorMessages();
128 return false;
129 }
130
Suren Baghdasaryand032a922019-02-12 18:20:38 -0800131 if (root.isMember("Cgroups")) {
132 const Json::Value& cgroups = root["Cgroups"];
133 for (Json::Value::ArrayIndex i = 0; i < cgroups.size(); ++i) {
134 std::string name = cgroups[i]["Controller"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800135 auto iter = descriptors->find(name);
136 if (iter == descriptors->end()) {
137 descriptors->emplace(name, CgroupDescriptor(1, name, cgroups[i]["Path"].asString(),
Suren Baghdasaryand032a922019-02-12 18:20:38 -0800138 std::strtoul(cgroups[i]["Mode"].asString().c_str(), 0, 8),
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800139 cgroups[i]["UID"].asString(), cgroups[i]["GID"].asString()));
140 } else {
141 iter->second = CgroupDescriptor(1, name, cgroups[i]["Path"].asString(),
142 std::strtoul(cgroups[i]["Mode"].asString().c_str(), 0, 8),
143 cgroups[i]["UID"].asString(), cgroups[i]["GID"].asString());
144 }
Suren Baghdasaryand032a922019-02-12 18:20:38 -0800145 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800146 }
147
Suren Baghdasaryand032a922019-02-12 18:20:38 -0800148 if (root.isMember("Cgroups2")) {
149 const Json::Value& cgroups2 = root["Cgroups2"];
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800150 auto iter = descriptors->find(CGROUPV2_CONTROLLER_NAME);
151 if (iter == descriptors->end()) {
152 descriptors->emplace(CGROUPV2_CONTROLLER_NAME, CgroupDescriptor(2, CGROUPV2_CONTROLLER_NAME, cgroups2["Path"].asString(),
Suren Baghdasaryand032a922019-02-12 18:20:38 -0800153 std::strtoul(cgroups2["Mode"].asString().c_str(), 0, 8),
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800154 cgroups2["UID"].asString(), cgroups2["GID"].asString()));
155 } else {
156 iter->second = CgroupDescriptor(2, CGROUPV2_CONTROLLER_NAME, cgroups2["Path"].asString(),
157 std::strtoul(cgroups2["Mode"].asString().c_str(), 0, 8),
158 cgroups2["UID"].asString(), cgroups2["GID"].asString());
159 }
160 }
161
162 return true;
163}
164
165static bool ReadDescriptors(std::map<std::string, CgroupDescriptor>* descriptors) {
166 // load system cgroup descriptors
167 if (!ReadDescriptorsFromFile(CGROUPS_DESC_FILE, descriptors)) {
168 return false;
169 }
170
171 // load vendor cgroup descriptors if the file exists
172 if (!access(CGROUPS_DESC_VENDOR_FILE, F_OK) &&
173 !ReadDescriptorsFromFile(CGROUPS_DESC_VENDOR_FILE, descriptors)) {
174 return false;
Suren Baghdasaryand032a922019-02-12 18:20:38 -0800175 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800176
177 return true;
178}
179
Suren Baghdasaryanff25a5f2019-02-02 23:12:01 -0800180// To avoid issues in sdk_mac build
181#if defined(__ANDROID__)
182
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800183static bool SetupCgroup(const CgroupDescriptor& descriptor) {
184 const CgroupController* controller = descriptor.controller();
185
186 // mkdir <path> [mode] [owner] [group]
187 if (!Mkdir(controller->path(), descriptor.mode(), descriptor.uid(), descriptor.gid())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800188 LOG(ERROR) << "Failed to create directory for " << controller->name() << " cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800189 return false;
190 }
191
192 int result;
193 if (controller->version() == 2) {
194 result = mount("none", controller->path(), "cgroup2", MS_NODEV | MS_NOEXEC | MS_NOSUID,
195 nullptr);
196 } else {
197 // Unfortunately historically cpuset controller was mounted using a mount command
198 // different from all other controllers. This results in controller attributes not
199 // to be prepended with controller name. For example this way instead of
200 // /dev/cpuset/cpuset.cpus the attribute becomes /dev/cpuset/cpus which is what
201 // the system currently expects.
202 if (!strcmp(controller->name(), "cpuset")) {
203 // mount cpuset none /dev/cpuset nodev noexec nosuid
204 result = mount("none", controller->path(), controller->name(),
205 MS_NODEV | MS_NOEXEC | MS_NOSUID, nullptr);
206 } else {
207 // mount cgroup none <path> nodev noexec nosuid <controller>
208 result = mount("none", controller->path(), "cgroup", MS_NODEV | MS_NOEXEC | MS_NOSUID,
209 controller->name());
210 }
211 }
212
213 if (result < 0) {
214 PLOG(ERROR) << "Failed to mount " << controller->name() << " cgroup";
215 return false;
216 }
217
218 return true;
219}
220
Suren Baghdasaryanff25a5f2019-02-02 23:12:01 -0800221#else
222
223// Stubs for non-Android targets.
224static bool SetupCgroup(const CgroupDescriptor&) {
225 return false;
226}
227
228#endif
229
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000230// WARNING: This function should be called only from SetupCgroups and only once.
231// It intentionally leaks an FD, so additional invocation will result in additional leak.
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800232static bool WriteRcFile(const std::map<std::string, CgroupDescriptor>& descriptors) {
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000233 // WARNING: We are intentionally leaking the FD to keep the file open forever.
234 // Let init keep the FD open to prevent file mappings from becoming invalid in
235 // case the file gets deleted somehow.
236 int fd = TEMP_FAILURE_RETRY(open(CGROUPS_RC_PATH, O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC,
237 S_IRUSR | S_IRGRP | S_IROTH));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800238 if (fd < 0) {
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000239 PLOG(ERROR) << "open() failed for " << CGROUPS_RC_PATH;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800240 return false;
241 }
242
243 CgroupFile fl;
244 fl.version_ = CgroupFile::FILE_CURR_VERSION;
245 fl.controller_count_ = descriptors.size();
246 int ret = TEMP_FAILURE_RETRY(write(fd, &fl, sizeof(fl)));
247 if (ret < 0) {
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000248 PLOG(ERROR) << "write() failed for " << CGROUPS_RC_PATH;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800249 return false;
250 }
251
252 for (const auto& [name, descriptor] : descriptors) {
253 ret = TEMP_FAILURE_RETRY(write(fd, descriptor.controller(), sizeof(CgroupController)));
254 if (ret < 0) {
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000255 PLOG(ERROR) << "write() failed for " << CGROUPS_RC_PATH;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800256 return false;
257 }
258 }
259
260 return true;
261}
262
263CgroupController::CgroupController(uint32_t version, const std::string& name,
264 const std::string& path) {
265 version_ = version;
266 strncpy(name_, name.c_str(), sizeof(name_) - 1);
267 name_[sizeof(name_) - 1] = '\0';
268 strncpy(path_, path.c_str(), sizeof(path_) - 1);
269 path_[sizeof(path_) - 1] = '\0';
270}
271
272std::string CgroupController::GetTasksFilePath(const std::string& path) const {
273 std::string tasks_path = path_;
274
275 if (!path.empty()) {
276 tasks_path += "/" + path;
277 }
278 return (version_ == 1) ? tasks_path + CGROUP_TASKS_FILE : tasks_path + CGROUP_TASKS_FILE_V2;
279}
280
281std::string CgroupController::GetProcsFilePath(const std::string& path, uid_t uid,
282 pid_t pid) const {
283 std::string proc_path(path_);
284 proc_path.append("/").append(path);
285 proc_path = regex_replace(proc_path, std::regex("<uid>"), std::to_string(uid));
286 proc_path = regex_replace(proc_path, std::regex("<pid>"), std::to_string(pid));
287
288 return proc_path.append(CGROUP_PROCS_FILE);
289}
290
291bool CgroupController::GetTaskGroup(int tid, std::string* group) const {
292 std::string file_name = StringPrintf("/proc/%d/cgroup", tid);
293 std::string content;
294 if (!android::base::ReadFileToString(file_name, &content)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800295 PLOG(ERROR) << "Failed to read " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800296 return false;
297 }
298
299 // if group is null and tid exists return early because
300 // user is not interested in cgroup membership
301 if (group == nullptr) {
302 return true;
303 }
304
305 std::string cg_tag = StringPrintf(":%s:", name_);
306 size_t start_pos = content.find(cg_tag);
307 if (start_pos == std::string::npos) {
308 return false;
309 }
310
311 start_pos += cg_tag.length() + 1; // skip '/'
312 size_t end_pos = content.find('\n', start_pos);
313 if (end_pos == std::string::npos) {
314 *group = content.substr(start_pos, std::string::npos);
315 } else {
316 *group = content.substr(start_pos, end_pos - start_pos);
317 }
318
319 return true;
320}
321
322CgroupDescriptor::CgroupDescriptor(uint32_t version, const std::string& name,
323 const std::string& path, mode_t mode, const std::string& uid,
324 const std::string& gid)
325 : controller_(version, name, path), mode_(mode), uid_(uid), gid_(gid) {}
326
327CgroupMap::CgroupMap() : cg_file_data_(nullptr), cg_file_size_(0) {
328 if (!LoadRcFile()) {
Wei Wangd71d3012019-03-07 11:59:12 -0800329 LOG(ERROR) << "CgroupMap::LoadRcFile called for [" << getpid() << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800330 }
331}
332
333CgroupMap::~CgroupMap() {
334 if (cg_file_data_) {
335 munmap(cg_file_data_, cg_file_size_);
336 cg_file_data_ = nullptr;
337 cg_file_size_ = 0;
338 }
339}
340
341CgroupMap& CgroupMap::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700342 // Deliberately leak this object to avoid a race between destruction on
343 // process exit and concurrent access from another thread.
344 static auto* instance = new CgroupMap;
345 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800346}
347
348bool CgroupMap::LoadRcFile() {
349 struct stat sb;
350
351 if (cg_file_data_) {
352 // Data already initialized
353 return true;
354 }
355
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000356 unique_fd fd(TEMP_FAILURE_RETRY(open(CGROUPS_RC_PATH, O_RDONLY | O_CLOEXEC)));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800357 if (fd < 0) {
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000358 PLOG(ERROR) << "open() failed for " << CGROUPS_RC_PATH;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800359 return false;
360 }
361
362 if (fstat(fd, &sb) < 0) {
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000363 PLOG(ERROR) << "fstat() failed for " << CGROUPS_RC_PATH;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800364 return false;
365 }
366
Wei Wangd71d3012019-03-07 11:59:12 -0800367 size_t file_size = sb.st_size;
368 if (file_size < sizeof(CgroupFile)) {
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000369 LOG(ERROR) << "Invalid file format " << CGROUPS_RC_PATH;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800370 return false;
371 }
372
Wei Wangd71d3012019-03-07 11:59:12 -0800373 CgroupFile* file_data = (CgroupFile*)mmap(nullptr, file_size, PROT_READ, MAP_SHARED, fd, 0);
374 if (file_data == MAP_FAILED) {
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000375 PLOG(ERROR) << "Failed to mmap " << CGROUPS_RC_PATH;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800376 return false;
377 }
378
Wei Wangd71d3012019-03-07 11:59:12 -0800379 if (file_data->version_ != CgroupFile::FILE_CURR_VERSION) {
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000380 LOG(ERROR) << CGROUPS_RC_PATH << " file version mismatch";
Wei Wangd71d3012019-03-07 11:59:12 -0800381 munmap(file_data, file_size);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800382 return false;
383 }
384
Wei Wangd71d3012019-03-07 11:59:12 -0800385 if (file_size != sizeof(CgroupFile) + file_data->controller_count_ * sizeof(CgroupController)) {
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000386 LOG(ERROR) << CGROUPS_RC_PATH << " file has invalid size";
Wei Wangd71d3012019-03-07 11:59:12 -0800387 munmap(file_data, file_size);
388 return false;
389 }
390
391 cg_file_data_ = file_data;
392 cg_file_size_ = file_size;
393
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800394 return true;
395}
396
Wei Wangd71d3012019-03-07 11:59:12 -0800397void CgroupMap::Print() const {
398 if (!cg_file_data_) {
399 LOG(ERROR) << "CgroupMap::Print called for [" << getpid()
400 << "] failed, RC file was not initialized properly";
401 return;
402 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800403 LOG(INFO) << "File version = " << cg_file_data_->version_;
404 LOG(INFO) << "File controller count = " << cg_file_data_->controller_count_;
405
406 LOG(INFO) << "Mounted cgroups:";
407 CgroupController* controller = (CgroupController*)(cg_file_data_ + 1);
408 for (int i = 0; i < cg_file_data_->controller_count_; i++, controller++) {
409 LOG(INFO) << "\t" << controller->name() << " ver " << controller->version() << " path "
410 << controller->path();
411 }
412}
413
414bool CgroupMap::SetupCgroups() {
415 std::map<std::string, CgroupDescriptor> descriptors;
416
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000417 if (getpid() != 1) {
418 LOG(ERROR) << "Cgroup setup can be done only by init process";
419 return false;
420 }
421
422 // Make sure we do this only one time. No need for std::call_once because
423 // init is a single-threaded process
424 if (access(CGROUPS_RC_PATH, F_OK) == 0) {
425 LOG(WARNING) << "Attempt to call SetupCgroups more than once";
426 return true;
427 }
428
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800429 // load cgroups.json file
430 if (!ReadDescriptors(&descriptors)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800431 LOG(ERROR) << "Failed to load cgroup description file";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800432 return false;
433 }
434
435 // setup cgroups
436 for (const auto& [name, descriptor] : descriptors) {
437 if (!SetupCgroup(descriptor)) {
438 // issue a warning and proceed with the next cgroup
439 // TODO: mark the descriptor as invalid and skip it in WriteRcFile()
440 LOG(WARNING) << "Failed to setup " << name << " cgroup";
441 }
442 }
443
444 // mkdir <CGROUPS_RC_DIR> 0711 system system
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000445 if (!Mkdir(android::base::Dirname(CGROUPS_RC_PATH), 0711, "system", "system")) {
446 LOG(ERROR) << "Failed to create directory for " << CGROUPS_RC_PATH << " file";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800447 return false;
448 }
449
450 // Generate <CGROUPS_RC_FILE> file which can be directly mmapped into
451 // process memory. This optimizes performance, memory usage
452 // and limits infrormation shared with unprivileged processes
453 // to the minimum subset of information from cgroups.json
454 if (!WriteRcFile(descriptors)) {
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000455 LOG(ERROR) << "Failed to write " << CGROUPS_RC_PATH << " file";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800456 return false;
457 }
458
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000459 // chmod 0644 <CGROUPS_RC_PATH>
460 if (fchmodat(AT_FDCWD, CGROUPS_RC_PATH, 0644, AT_SYMLINK_NOFOLLOW) < 0) {
Wei Wangd71d3012019-03-07 11:59:12 -0800461 PLOG(ERROR) << "fchmodat() failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800462 return false;
463 }
464
465 return true;
466}
467
468const CgroupController* CgroupMap::FindController(const std::string& name) const {
469 if (!cg_file_data_) {
Wei Wangd71d3012019-03-07 11:59:12 -0800470 LOG(ERROR) << "CgroupMap::FindController called for [" << getpid()
471 << "] failed, RC file was not initialized properly";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800472 return nullptr;
473 }
474
475 // skip the file header to get to the first controller
476 CgroupController* controller = (CgroupController*)(cg_file_data_ + 1);
477 for (int i = 0; i < cg_file_data_->controller_count_; i++, controller++) {
478 if (name == controller->name()) {
479 return controller;
480 }
481 }
482
483 return nullptr;
484}