blob: c5fb8046494afea4af1f248254a66d9cfe2e8c46 [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,
134 CgroupDescriptor(1, name, cgroups[i]["Path"].asString(), cgroups[i]["Mode"].asInt(),
135 cgroups[i]["UID"].asString(), cgroups[i]["GID"].asString())));
136 }
137
138 Json::Value cgroups2 = root["Cgroups2"];
139 descriptors->emplace(std::make_pair(
140 CGROUPV2_CONTROLLER_NAME,
141 CgroupDescriptor(2, CGROUPV2_CONTROLLER_NAME, cgroups2["Path"].asString(),
142 cgroups2["Mode"].asInt(), cgroups2["UID"].asString(),
143 cgroups2["GID"].asString())));
144
145 return true;
146}
147
Suren Baghdasaryanff25a5f2019-02-02 23:12:01 -0800148// To avoid issues in sdk_mac build
149#if defined(__ANDROID__)
150
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800151static bool SetupCgroup(const CgroupDescriptor& descriptor) {
152 const CgroupController* controller = descriptor.controller();
153
154 // mkdir <path> [mode] [owner] [group]
155 if (!Mkdir(controller->path(), descriptor.mode(), descriptor.uid(), descriptor.gid())) {
156 PLOG(ERROR) << "Failed to create directory for " << controller->name() << " cgroup";
157 return false;
158 }
159
160 int result;
161 if (controller->version() == 2) {
162 result = mount("none", controller->path(), "cgroup2", MS_NODEV | MS_NOEXEC | MS_NOSUID,
163 nullptr);
164 } else {
165 // Unfortunately historically cpuset controller was mounted using a mount command
166 // different from all other controllers. This results in controller attributes not
167 // to be prepended with controller name. For example this way instead of
168 // /dev/cpuset/cpuset.cpus the attribute becomes /dev/cpuset/cpus which is what
169 // the system currently expects.
170 if (!strcmp(controller->name(), "cpuset")) {
171 // mount cpuset none /dev/cpuset nodev noexec nosuid
172 result = mount("none", controller->path(), controller->name(),
173 MS_NODEV | MS_NOEXEC | MS_NOSUID, nullptr);
174 } else {
175 // mount cgroup none <path> nodev noexec nosuid <controller>
176 result = mount("none", controller->path(), "cgroup", MS_NODEV | MS_NOEXEC | MS_NOSUID,
177 controller->name());
178 }
179 }
180
181 if (result < 0) {
182 PLOG(ERROR) << "Failed to mount " << controller->name() << " cgroup";
183 return false;
184 }
185
186 return true;
187}
188
Suren Baghdasaryanff25a5f2019-02-02 23:12:01 -0800189#else
190
191// Stubs for non-Android targets.
192static bool SetupCgroup(const CgroupDescriptor&) {
193 return false;
194}
195
196#endif
197
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800198static bool WriteRcFile(const std::map<std::string, CgroupDescriptor>& descriptors) {
199 std::string cgroup_rc_path = StringPrintf("%s/%s", CGROUPS_RC_DIR, CgroupMap::CGROUPS_RC_FILE);
200 unique_fd fd(TEMP_FAILURE_RETRY(open(cgroup_rc_path.c_str(),
201 O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC,
202 S_IRUSR | S_IRGRP | S_IROTH)));
203 if (fd < 0) {
204 PLOG(ERROR) << "open() failed for " << cgroup_rc_path;
205 return false;
206 }
207
208 CgroupFile fl;
209 fl.version_ = CgroupFile::FILE_CURR_VERSION;
210 fl.controller_count_ = descriptors.size();
211 int ret = TEMP_FAILURE_RETRY(write(fd, &fl, sizeof(fl)));
212 if (ret < 0) {
213 PLOG(ERROR) << "write() failed for " << cgroup_rc_path;
214 return false;
215 }
216
217 for (const auto& [name, descriptor] : descriptors) {
218 ret = TEMP_FAILURE_RETRY(write(fd, descriptor.controller(), sizeof(CgroupController)));
219 if (ret < 0) {
220 PLOG(ERROR) << "write() failed for " << cgroup_rc_path;
221 return false;
222 }
223 }
224
225 return true;
226}
227
228CgroupController::CgroupController(uint32_t version, const std::string& name,
229 const std::string& path) {
230 version_ = version;
231 strncpy(name_, name.c_str(), sizeof(name_) - 1);
232 name_[sizeof(name_) - 1] = '\0';
233 strncpy(path_, path.c_str(), sizeof(path_) - 1);
234 path_[sizeof(path_) - 1] = '\0';
235}
236
237std::string CgroupController::GetTasksFilePath(const std::string& path) const {
238 std::string tasks_path = path_;
239
240 if (!path.empty()) {
241 tasks_path += "/" + path;
242 }
243 return (version_ == 1) ? tasks_path + CGROUP_TASKS_FILE : tasks_path + CGROUP_TASKS_FILE_V2;
244}
245
246std::string CgroupController::GetProcsFilePath(const std::string& path, uid_t uid,
247 pid_t pid) const {
248 std::string proc_path(path_);
249 proc_path.append("/").append(path);
250 proc_path = regex_replace(proc_path, std::regex("<uid>"), std::to_string(uid));
251 proc_path = regex_replace(proc_path, std::regex("<pid>"), std::to_string(pid));
252
253 return proc_path.append(CGROUP_PROCS_FILE);
254}
255
256bool CgroupController::GetTaskGroup(int tid, std::string* group) const {
257 std::string file_name = StringPrintf("/proc/%d/cgroup", tid);
258 std::string content;
259 if (!android::base::ReadFileToString(file_name, &content)) {
260 LOG(ERROR) << "Failed to read " << file_name;
261 return false;
262 }
263
264 // if group is null and tid exists return early because
265 // user is not interested in cgroup membership
266 if (group == nullptr) {
267 return true;
268 }
269
270 std::string cg_tag = StringPrintf(":%s:", name_);
271 size_t start_pos = content.find(cg_tag);
272 if (start_pos == std::string::npos) {
273 return false;
274 }
275
276 start_pos += cg_tag.length() + 1; // skip '/'
277 size_t end_pos = content.find('\n', start_pos);
278 if (end_pos == std::string::npos) {
279 *group = content.substr(start_pos, std::string::npos);
280 } else {
281 *group = content.substr(start_pos, end_pos - start_pos);
282 }
283
284 return true;
285}
286
287CgroupDescriptor::CgroupDescriptor(uint32_t version, const std::string& name,
288 const std::string& path, mode_t mode, const std::string& uid,
289 const std::string& gid)
290 : controller_(version, name, path), mode_(mode), uid_(uid), gid_(gid) {}
291
292CgroupMap::CgroupMap() : cg_file_data_(nullptr), cg_file_size_(0) {
293 if (!LoadRcFile()) {
294 PLOG(ERROR) << "CgroupMap::LoadRcFile called for [" << getpid() << "] failed";
295 }
296}
297
298CgroupMap::~CgroupMap() {
299 if (cg_file_data_) {
300 munmap(cg_file_data_, cg_file_size_);
301 cg_file_data_ = nullptr;
302 cg_file_size_ = 0;
303 }
304}
305
306CgroupMap& CgroupMap::GetInstance() {
307 static CgroupMap instance;
308 return instance;
309}
310
311bool CgroupMap::LoadRcFile() {
312 struct stat sb;
313
314 if (cg_file_data_) {
315 // Data already initialized
316 return true;
317 }
318
319 std::string cgroup_rc_path = StringPrintf("%s/%s", CGROUPS_RC_DIR, CGROUPS_RC_FILE);
320 unique_fd fd(TEMP_FAILURE_RETRY(open(cgroup_rc_path.c_str(), O_RDONLY | O_CLOEXEC)));
321 if (fd < 0) {
322 PLOG(ERROR) << "open() failed for " << cgroup_rc_path;
323 return false;
324 }
325
326 if (fstat(fd, &sb) < 0) {
327 PLOG(ERROR) << "fstat() failed for " << cgroup_rc_path;
328 return false;
329 }
330
331 cg_file_size_ = sb.st_size;
332 if (cg_file_size_ < sizeof(CgroupFile)) {
333 PLOG(ERROR) << "Invalid file format " << cgroup_rc_path;
334 return false;
335 }
336
337 cg_file_data_ = (CgroupFile*)mmap(nullptr, cg_file_size_, PROT_READ, MAP_SHARED, fd, 0);
338 if (cg_file_data_ == MAP_FAILED) {
339 PLOG(ERROR) << "Failed to mmap " << cgroup_rc_path;
340 return false;
341 }
342
343 if (cg_file_data_->version_ != CgroupFile::FILE_CURR_VERSION) {
344 PLOG(ERROR) << cgroup_rc_path << " file version mismatch";
345 return false;
346 }
347
348 return true;
349}
350
351void CgroupMap::Print() {
352 LOG(INFO) << "File version = " << cg_file_data_->version_;
353 LOG(INFO) << "File controller count = " << cg_file_data_->controller_count_;
354
355 LOG(INFO) << "Mounted cgroups:";
356 CgroupController* controller = (CgroupController*)(cg_file_data_ + 1);
357 for (int i = 0; i < cg_file_data_->controller_count_; i++, controller++) {
358 LOG(INFO) << "\t" << controller->name() << " ver " << controller->version() << " path "
359 << controller->path();
360 }
361}
362
363bool CgroupMap::SetupCgroups() {
364 std::map<std::string, CgroupDescriptor> descriptors;
365
366 // load cgroups.json file
367 if (!ReadDescriptors(&descriptors)) {
368 PLOG(ERROR) << "Failed to load cgroup description file";
369 return false;
370 }
371
372 // setup cgroups
373 for (const auto& [name, descriptor] : descriptors) {
374 if (!SetupCgroup(descriptor)) {
375 // issue a warning and proceed with the next cgroup
376 // TODO: mark the descriptor as invalid and skip it in WriteRcFile()
377 LOG(WARNING) << "Failed to setup " << name << " cgroup";
378 }
379 }
380
381 // mkdir <CGROUPS_RC_DIR> 0711 system system
382 if (!Mkdir(CGROUPS_RC_DIR, 0711, "system", "system")) {
383 PLOG(ERROR) << "Failed to create directory for <CGROUPS_RC_FILE> file";
384 return false;
385 }
386
387 // Generate <CGROUPS_RC_FILE> file which can be directly mmapped into
388 // process memory. This optimizes performance, memory usage
389 // and limits infrormation shared with unprivileged processes
390 // to the minimum subset of information from cgroups.json
391 if (!WriteRcFile(descriptors)) {
392 LOG(ERROR) << "Failed to write " << CGROUPS_RC_FILE << " file";
393 return false;
394 }
395
396 std::string cgroup_rc_path = StringPrintf("%s/%s", CGROUPS_RC_DIR, CGROUPS_RC_FILE);
397 // chmod 0644 <cgroup_rc_path>
398 if (fchmodat(AT_FDCWD, cgroup_rc_path.c_str(), 0644, AT_SYMLINK_NOFOLLOW) < 0) {
399 LOG(ERROR) << "fchmodat() failed";
400 return false;
401 }
402
403 return true;
404}
405
406const CgroupController* CgroupMap::FindController(const std::string& name) const {
407 if (!cg_file_data_) {
408 return nullptr;
409 }
410
411 // skip the file header to get to the first controller
412 CgroupController* controller = (CgroupController*)(cg_file_data_ + 1);
413 for (int i = 0; i < cg_file_data_->controller_count_; i++, controller++) {
414 if (name == controller->name()) {
415 return controller;
416 }
417 }
418
419 return nullptr;
420}