blob: 9e914ee7c292753002b4ffb6f9fd393c00e61fc2 [file] [log] [blame]
Tom Cherry2aeb1ad2019-06-26 10:46:20 -07001/*
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#include "service_parser.h"
18
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070019#include <linux/input.h>
Tom Cherry2e4c85f2019-07-09 13:33:36 -070020#include <stdlib.h>
21#include <sys/socket.h>
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070022
Daniel Norman3f42a762019-07-09 11:00:53 -070023#include <algorithm>
24#include <sstream>
25
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070026#include <android-base/logging.h>
27#include <android-base/parseint.h>
28#include <android-base/strings.h>
29#include <hidl-util/FQName.h>
Suren Baghdasaryan746ede92022-03-31 21:15:11 +000030#include <processgroup/processgroup.h>
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070031#include <system/thread_defs.h>
32
Suren Baghdasaryanc29c2ba2019-10-22 17:18:42 -070033#include "lmkd_service.h"
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070034#include "rlimit_parser.h"
Tom Cherry2e4c85f2019-07-09 13:33:36 -070035#include "service_utils.h"
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070036#include "util.h"
37
Tom Cherrya2f91362020-02-20 10:50:00 -080038#ifdef INIT_FULL_SOURCES
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070039#include <android/api-level.h>
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070040#include <sys/system_properties.h>
41
42#include "selinux.h"
43#else
44#include "host_init_stubs.h"
45#endif
46
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070047using android::base::ParseInt;
48using android::base::Split;
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070049using android::base::StartsWith;
50
51namespace android {
52namespace init {
53
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070054Result<void> ServiceParser::ParseCapabilities(std::vector<std::string>&& args) {
55 service_->capabilities_ = 0;
56
57 if (!CapAmbientSupported()) {
58 return Error()
59 << "capabilities requested but the kernel does not support ambient capabilities";
60 }
61
62 unsigned int last_valid_cap = GetLastValidCap();
63 if (last_valid_cap >= service_->capabilities_->size()) {
64 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
65 }
66
67 for (size_t i = 1; i < args.size(); i++) {
68 const std::string& arg = args[i];
69 int res = LookupCap(arg);
70 if (res < 0) {
71 return Errorf("invalid capability '{}'", arg);
72 }
73 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
74 if (cap > last_valid_cap) {
75 return Errorf("capability '{}' not supported by the kernel", arg);
76 }
77 (*service_->capabilities_)[cap] = true;
78 }
79 return {};
80}
81
82Result<void> ServiceParser::ParseClass(std::vector<std::string>&& args) {
83 service_->classnames_ = std::set<std::string>(args.begin() + 1, args.end());
84 return {};
85}
86
87Result<void> ServiceParser::ParseConsole(std::vector<std::string>&& args) {
Tom Cherryf74b7f52019-09-23 16:16:54 -070088 if (service_->proc_attr_.stdio_to_kmsg) {
89 return Error() << "'console' and 'stdio_to_kmsg' are mutually exclusive";
90 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070091 service_->flags_ |= SVC_CONSOLE;
92 service_->proc_attr_.console = args.size() > 1 ? "/dev/" + args[1] : "";
93 return {};
94}
95
96Result<void> ServiceParser::ParseCritical(std::vector<std::string>&& args) {
Woody Lin45215ae2019-12-26 22:22:28 +080097 std::optional<std::string> fatal_reboot_target;
98 std::optional<std::chrono::minutes> fatal_crash_window;
99
100 for (auto it = args.begin() + 1; it != args.end(); ++it) {
101 auto arg = android::base::Split(*it, "=");
102 if (arg.size() != 2) {
103 return Error() << "critical: Argument '" << *it << "' is not supported";
104 } else if (arg[0] == "target") {
105 fatal_reboot_target = arg[1];
106 } else if (arg[0] == "window") {
107 int minutes;
108 auto window = ExpandProps(arg[1]);
109 if (!window.ok()) {
110 return Error() << "critical: Could not expand argument ': " << arg[1];
111 }
112 if (*window == "off") {
113 return {};
114 }
115 if (!ParseInt(*window, &minutes, 0)) {
116 return Error() << "critical: 'fatal_crash_window' must be an integer > 0";
117 }
118 fatal_crash_window = std::chrono::minutes(minutes);
119 } else {
120 return Error() << "critical: Argument '" << *it << "' is not supported";
121 }
122 }
123
124 if (fatal_reboot_target) {
125 service_->fatal_reboot_target_ = *fatal_reboot_target;
126 }
127 if (fatal_crash_window) {
128 service_->fatal_crash_window_ = *fatal_crash_window;
129 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700130 service_->flags_ |= SVC_CRITICAL;
131 return {};
132}
133
134Result<void> ServiceParser::ParseDisabled(std::vector<std::string>&& args) {
135 service_->flags_ |= SVC_DISABLED;
136 service_->flags_ |= SVC_RC_DISABLED;
137 return {};
138}
139
140Result<void> ServiceParser::ParseEnterNamespace(std::vector<std::string>&& args) {
141 if (args[1] != "net") {
142 return Error() << "Init only supports entering network namespaces";
143 }
144 if (!service_->namespaces_.namespaces_to_enter.empty()) {
145 return Error() << "Only one network namespace may be entered";
146 }
147 // Network namespaces require that /sys is remounted, otherwise the old adapters will still be
148 // present. Therefore, they also require mount namespaces.
149 service_->namespaces_.flags |= CLONE_NEWNS;
150 service_->namespaces_.namespaces_to_enter.emplace_back(CLONE_NEWNET, std::move(args[2]));
151 return {};
152}
153
154Result<void> ServiceParser::ParseGroup(std::vector<std::string>&& args) {
155 auto gid = DecodeUid(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900156 if (!gid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700157 return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
158 }
159 service_->proc_attr_.gid = *gid;
160
161 for (std::size_t n = 2; n < args.size(); n++) {
162 gid = DecodeUid(args[n]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900163 if (!gid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700164 return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
165 }
166 service_->proc_attr_.supp_gids.emplace_back(*gid);
167 }
168 return {};
169}
170
171Result<void> ServiceParser::ParsePriority(std::vector<std::string>&& args) {
172 service_->proc_attr_.priority = 0;
173 if (!ParseInt(args[1], &service_->proc_attr_.priority,
174 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
175 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
176 return Errorf("process priority value must be range {} - {}", ANDROID_PRIORITY_HIGHEST,
177 ANDROID_PRIORITY_LOWEST);
178 }
179 return {};
180}
181
182Result<void> ServiceParser::ParseInterface(std::vector<std::string>&& args) {
183 const std::string& interface_name = args[1];
184 const std::string& instance_name = args[2];
185
Jon Spivack16fb3f92019-07-26 13:14:42 -0700186 // AIDL services don't use fully qualified names and instead just use "interface aidl <name>"
187 if (interface_name != "aidl") {
188 FQName fq_name;
189 if (!FQName::parse(interface_name, &fq_name)) {
190 return Error() << "Invalid fully-qualified name for interface '" << interface_name
191 << "'";
192 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700193
Jon Spivack16fb3f92019-07-26 13:14:42 -0700194 if (!fq_name.isFullyQualified()) {
195 return Error() << "Interface name not fully-qualified '" << interface_name << "'";
196 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700197
Jon Spivack16fb3f92019-07-26 13:14:42 -0700198 if (fq_name.isValidValueName()) {
199 return Error() << "Interface name must not be a value name '" << interface_name << "'";
200 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700201 }
202
203 const std::string fullname = interface_name + "/" + instance_name;
204
205 for (const auto& svc : *service_list_) {
Alexander Koskoviche5f05202022-03-06 15:51:51 -0700206 if (svc->interfaces().count(fullname) > 0 && !service_->is_override()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700207 return Error() << "Interface '" << fullname << "' redefined in " << service_->name()
208 << " but is already defined by " << svc->name();
209 }
210 }
211
212 service_->interfaces_.insert(fullname);
213
214 return {};
215}
216
217Result<void> ServiceParser::ParseIoprio(std::vector<std::string>&& args) {
218 if (!ParseInt(args[2], &service_->proc_attr_.ioprio_pri, 0, 7)) {
219 return Error() << "priority value must be range 0 - 7";
220 }
221
222 if (args[1] == "rt") {
223 service_->proc_attr_.ioprio_class = IoSchedClass_RT;
224 } else if (args[1] == "be") {
225 service_->proc_attr_.ioprio_class = IoSchedClass_BE;
226 } else if (args[1] == "idle") {
227 service_->proc_attr_.ioprio_class = IoSchedClass_IDLE;
228 } else {
229 return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
230 }
231
232 return {};
233}
234
235Result<void> ServiceParser::ParseKeycodes(std::vector<std::string>&& args) {
236 auto it = args.begin() + 1;
237 if (args.size() == 2 && StartsWith(args[1], "$")) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700238 auto expanded = ExpandProps(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900239 if (!expanded.ok()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700240 return expanded.error();
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700241 }
242
243 // If the property is not set, it defaults to none, in which case there are no keycodes
244 // for this service.
Bernie Innocenti1cc76df2020-02-03 23:54:02 +0900245 if (*expanded == "none") {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700246 return {};
247 }
248
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700249 args = Split(*expanded, ",");
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700250 it = args.begin();
251 }
252
253 for (; it != args.end(); ++it) {
254 int code;
255 if (ParseInt(*it, &code, 0, KEY_MAX)) {
256 for (auto& key : service_->keycodes_) {
257 if (key == code) return Error() << "duplicate keycode: " << *it;
258 }
259 service_->keycodes_.insert(
260 std::upper_bound(service_->keycodes_.begin(), service_->keycodes_.end(), code),
261 code);
262 } else {
263 return Error() << "invalid keycode: " << *it;
264 }
265 }
266 return {};
267}
268
269Result<void> ServiceParser::ParseOneshot(std::vector<std::string>&& args) {
270 service_->flags_ |= SVC_ONESHOT;
271 return {};
272}
273
274Result<void> ServiceParser::ParseOnrestart(std::vector<std::string>&& args) {
275 args.erase(args.begin());
276 int line = service_->onrestart_.NumCommands() + 1;
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900277 if (auto result = service_->onrestart_.AddCommand(std::move(args), line); !result.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700278 return Error() << "cannot add Onrestart command: " << result.error();
279 }
280 return {};
281}
282
283Result<void> ServiceParser::ParseNamespace(std::vector<std::string>&& args) {
284 for (size_t i = 1; i < args.size(); i++) {
285 if (args[i] == "pid") {
286 service_->namespaces_.flags |= CLONE_NEWPID;
287 // PID namespaces require mount namespaces.
288 service_->namespaces_.flags |= CLONE_NEWNS;
289 } else if (args[i] == "mnt") {
290 service_->namespaces_.flags |= CLONE_NEWNS;
291 } else {
292 return Error() << "namespace must be 'pid' or 'mnt'";
293 }
294 }
295 return {};
296}
297
298Result<void> ServiceParser::ParseOomScoreAdjust(std::vector<std::string>&& args) {
Suren Baghdasaryanc29c2ba2019-10-22 17:18:42 -0700299 if (!ParseInt(args[1], &service_->oom_score_adjust_, MIN_OOM_SCORE_ADJUST,
300 MAX_OOM_SCORE_ADJUST)) {
301 return Error() << "oom_score_adjust value must be in range " << MIN_OOM_SCORE_ADJUST
302 << " - +" << MAX_OOM_SCORE_ADJUST;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700303 }
304 return {};
305}
306
307Result<void> ServiceParser::ParseOverride(std::vector<std::string>&& args) {
308 service_->override_ = true;
309 return {};
310}
311
312Result<void> ServiceParser::ParseMemcgSwappiness(std::vector<std::string>&& args) {
313 if (!ParseInt(args[1], &service_->swappiness_, 0)) {
314 return Error() << "swappiness value must be equal or greater than 0";
315 }
316 return {};
317}
318
319Result<void> ServiceParser::ParseMemcgLimitInBytes(std::vector<std::string>&& args) {
320 if (!ParseInt(args[1], &service_->limit_in_bytes_, 0)) {
321 return Error() << "limit_in_bytes value must be equal or greater than 0";
322 }
323 return {};
324}
325
326Result<void> ServiceParser::ParseMemcgLimitPercent(std::vector<std::string>&& args) {
327 if (!ParseInt(args[1], &service_->limit_percent_, 0)) {
328 return Error() << "limit_percent value must be equal or greater than 0";
329 }
330 return {};
331}
332
333Result<void> ServiceParser::ParseMemcgLimitProperty(std::vector<std::string>&& args) {
334 service_->limit_property_ = std::move(args[1]);
335 return {};
336}
337
338Result<void> ServiceParser::ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args) {
339 if (!ParseInt(args[1], &service_->soft_limit_in_bytes_, 0)) {
340 return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
341 }
342 return {};
343}
344
345Result<void> ServiceParser::ParseProcessRlimit(std::vector<std::string>&& args) {
346 auto rlimit = ParseRlimit(args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900347 if (!rlimit.ok()) return rlimit.error();
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700348
349 service_->proc_attr_.rlimits.emplace_back(*rlimit);
350 return {};
351}
352
Tom Cherry60971e62019-09-10 10:40:47 -0700353Result<void> ServiceParser::ParseRebootOnFailure(std::vector<std::string>&& args) {
354 if (service_->on_failure_reboot_target_) {
355 return Error() << "Only one reboot_on_failure command may be specified";
356 }
357 if (!StartsWith(args[1], "shutdown") && !StartsWith(args[1], "reboot")) {
358 return Error()
359 << "reboot_on_failure commands must begin with either 'shutdown' or 'reboot'";
360 }
361 service_->on_failure_reboot_target_ = std::move(args[1]);
362 return {};
363}
364
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700365Result<void> ServiceParser::ParseRestartPeriod(std::vector<std::string>&& args) {
366 int period;
367 if (!ParseInt(args[1], &period, 5)) {
368 return Error() << "restart_period value must be an integer >= 5";
369 }
370 service_->restart_period_ = std::chrono::seconds(period);
371 return {};
372}
373
374Result<void> ServiceParser::ParseSeclabel(std::vector<std::string>&& args) {
375 service_->seclabel_ = std::move(args[1]);
376 return {};
377}
378
379Result<void> ServiceParser::ParseSigstop(std::vector<std::string>&& args) {
380 service_->sigstop_ = true;
381 return {};
382}
383
384Result<void> ServiceParser::ParseSetenv(std::vector<std::string>&& args) {
385 service_->environment_vars_.emplace_back(std::move(args[1]), std::move(args[2]));
386 return {};
387}
388
389Result<void> ServiceParser::ParseShutdown(std::vector<std::string>&& args) {
390 if (args[1] == "critical") {
391 service_->flags_ |= SVC_SHUTDOWN_CRITICAL;
392 return {};
393 }
394 return Error() << "Invalid shutdown option";
395}
396
Suren Baghdasaryanc9c0bba2020-04-30 11:58:39 -0700397Result<void> ServiceParser::ParseTaskProfiles(std::vector<std::string>&& args) {
398 args.erase(args.begin());
Suren Baghdasaryan746ede92022-03-31 21:15:11 +0000399 if (service_->task_profiles_.empty()) {
400 service_->task_profiles_ = std::move(args);
401 } else {
402 // Some task profiles might have been added during writepid conversions
403 service_->task_profiles_.insert(service_->task_profiles_.end(),
404 std::make_move_iterator(args.begin()),
405 std::make_move_iterator(args.end()));
406 args.clear();
407 }
Suren Baghdasaryanc9c0bba2020-04-30 11:58:39 -0700408 return {};
409}
410
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700411Result<void> ServiceParser::ParseTimeoutPeriod(std::vector<std::string>&& args) {
412 int period;
413 if (!ParseInt(args[1], &period, 1)) {
414 return Error() << "timeout_period value must be an integer >= 1";
415 }
416 service_->timeout_period_ = std::chrono::seconds(period);
417 return {};
418}
419
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700420// name type perm [ uid gid context ]
421Result<void> ServiceParser::ParseSocket(std::vector<std::string>&& args) {
422 SocketDescriptor socket;
423 socket.name = std::move(args[1]);
424
425 auto types = Split(args[2], "+");
426 if (types[0] == "stream") {
427 socket.type = SOCK_STREAM;
428 } else if (types[0] == "dgram") {
429 socket.type = SOCK_DGRAM;
430 } else if (types[0] == "seqpacket") {
431 socket.type = SOCK_SEQPACKET;
432 } else {
433 return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket', got '" << types[0]
434 << "' instead.";
435 }
436
437 if (types.size() > 1) {
438 if (types.size() == 2 && types[1] == "passcred") {
439 socket.passcred = true;
440 } else {
441 return Error() << "Only 'passcred' may be used to modify the socket type";
442 }
443 }
444
445 errno = 0;
446 char* end = nullptr;
447 socket.perm = strtol(args[3].c_str(), &end, 8);
448 if (errno != 0) {
449 return ErrnoError() << "Unable to parse permissions '" << args[3] << "'";
450 }
451 if (end == args[3].c_str() || *end != '\0') {
452 errno = EINVAL;
453 return ErrnoError() << "Unable to parse permissions '" << args[3] << "'";
454 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700455
456 if (args.size() > 4) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700457 auto uid = DecodeUid(args[4]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900458 if (!uid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700459 return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
460 }
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700461 socket.uid = *uid;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700462 }
463
464 if (args.size() > 5) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700465 auto gid = DecodeUid(args[5]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900466 if (!gid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700467 return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
468 }
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700469 socket.gid = *gid;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700470 }
471
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700472 socket.context = args.size() > 6 ? args[6] : "";
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700473
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700474 auto old = std::find_if(service_->sockets_.begin(), service_->sockets_.end(),
475 [&socket](const auto& other) { return socket.name == other.name; });
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700476
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700477 if (old != service_->sockets_.end()) {
478 return Error() << "duplicate socket descriptor '" << socket.name << "'";
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700479 }
480
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700481 service_->sockets_.emplace_back(std::move(socket));
482
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700483 return {};
484}
485
Tom Cherryf74b7f52019-09-23 16:16:54 -0700486Result<void> ServiceParser::ParseStdioToKmsg(std::vector<std::string>&& args) {
487 if (service_->flags_ & SVC_CONSOLE) {
488 return Error() << "'stdio_to_kmsg' and 'console' are mutually exclusive";
489 }
490 service_->proc_attr_.stdio_to_kmsg = true;
491 return {};
492}
493
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700494// name type
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700495Result<void> ServiceParser::ParseFile(std::vector<std::string>&& args) {
496 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
497 return Error() << "file type must be 'r', 'w' or 'rw'";
498 }
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700499
500 FileDescriptor file;
501 file.type = args[2];
502
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700503 auto file_name = ExpandProps(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900504 if (!file_name.ok()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700505 return Error() << "Could not expand file path ': " << file_name.error();
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700506 }
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700507 file.name = *file_name;
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700508 if (file.name[0] != '/' || file.name.find("../") != std::string::npos) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700509 return Error() << "file name must not be relative";
510 }
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700511
512 auto old = std::find_if(service_->files_.begin(), service_->files_.end(),
513 [&file](const auto& other) { return other.name == file.name; });
514
515 if (old != service_->files_.end()) {
516 return Error() << "duplicate file descriptor '" << file.name << "'";
517 }
518
519 service_->files_.emplace_back(std::move(file));
520
521 return {};
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700522}
523
524Result<void> ServiceParser::ParseUser(std::vector<std::string>&& args) {
525 auto uid = DecodeUid(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900526 if (!uid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700527 return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
528 }
529 service_->proc_attr_.uid = *uid;
530 return {};
531}
532
Suren Baghdasaryan746ede92022-03-31 21:15:11 +0000533// Convert legacy paths used to migrate processes between cgroups using writepid command.
534// We can't get these paths from TaskProfiles because profile definitions are changing
535// when we migrate to cgroups v2 while these hardcoded paths stay the same.
536static std::optional<const std::string> ConvertTaskFileToProfile(const std::string& file) {
537 static const std::map<const std::string, const std::string> map = {
538 {"/dev/stune/top-app/tasks", "MaxPerformance"},
539 {"/dev/stune/foreground/tasks", "HighPerformance"},
540 {"/dev/cpuset/camera-daemon/tasks", "CameraServiceCapacity"},
541 {"/dev/cpuset/foreground/tasks", "ProcessCapacityHigh"},
542 {"/dev/cpuset/system-background/tasks", "ServiceCapacityLow"},
543 {"/dev/stune/nnapi-hal/tasks", "NNApiHALPerformance"},
544 {"/dev/blkio/background/tasks", "LowIoPriority"},
545 };
546 auto iter = map.find(file);
547 return iter == map.end() ? std::nullopt : std::make_optional<const std::string>(iter->second);
548}
549
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700550Result<void> ServiceParser::ParseWritepid(std::vector<std::string>&& args) {
551 args.erase(args.begin());
Suren Baghdasaryan746ede92022-03-31 21:15:11 +0000552 // Convert any cgroup writes into appropriate task_profiles
553 for (auto iter = args.begin(); iter != args.end();) {
554 auto task_profile = ConvertTaskFileToProfile(*iter);
555 if (task_profile) {
556 LOG(WARNING) << "'writepid " << *iter << "' is converted into 'task_profiles "
557 << task_profile.value() << "' for service " << service_->name();
558 service_->task_profiles_.push_back(task_profile.value());
559 iter = args.erase(iter);
560 } else {
561 ++iter;
562 }
563 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700564 service_->writepid_files_ = std::move(args);
565 return {};
566}
567
568Result<void> ServiceParser::ParseUpdatable(std::vector<std::string>&& args) {
569 service_->updatable_ = true;
570 return {};
571}
572
Tom Cherryd52a5b32019-07-22 16:05:36 -0700573const KeywordMap<ServiceParser::OptionParser>& ServiceParser::GetParserMap() const {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700574 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
575 // clang-format off
Tom Cherryd52a5b32019-07-22 16:05:36 -0700576 static const KeywordMap<ServiceParser::OptionParser> parser_map = {
Tom Cherry60971e62019-09-10 10:40:47 -0700577 {"capabilities", {0, kMax, &ServiceParser::ParseCapabilities}},
578 {"class", {1, kMax, &ServiceParser::ParseClass}},
579 {"console", {0, 1, &ServiceParser::ParseConsole}},
Woody Lin45215ae2019-12-26 22:22:28 +0800580 {"critical", {0, 2, &ServiceParser::ParseCritical}},
Tom Cherry60971e62019-09-10 10:40:47 -0700581 {"disabled", {0, 0, &ServiceParser::ParseDisabled}},
582 {"enter_namespace", {2, 2, &ServiceParser::ParseEnterNamespace}},
583 {"file", {2, 2, &ServiceParser::ParseFile}},
584 {"group", {1, NR_SVC_SUPP_GIDS + 1, &ServiceParser::ParseGroup}},
585 {"interface", {2, 2, &ServiceParser::ParseInterface}},
586 {"ioprio", {2, 2, &ServiceParser::ParseIoprio}},
587 {"keycodes", {1, kMax, &ServiceParser::ParseKeycodes}},
588 {"memcg.limit_in_bytes", {1, 1, &ServiceParser::ParseMemcgLimitInBytes}},
589 {"memcg.limit_percent", {1, 1, &ServiceParser::ParseMemcgLimitPercent}},
590 {"memcg.limit_property", {1, 1, &ServiceParser::ParseMemcgLimitProperty}},
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700591 {"memcg.soft_limit_in_bytes",
Tom Cherry60971e62019-09-10 10:40:47 -0700592 {1, 1, &ServiceParser::ParseMemcgSoftLimitInBytes}},
593 {"memcg.swappiness", {1, 1, &ServiceParser::ParseMemcgSwappiness}},
594 {"namespace", {1, 2, &ServiceParser::ParseNamespace}},
595 {"oneshot", {0, 0, &ServiceParser::ParseOneshot}},
596 {"onrestart", {1, kMax, &ServiceParser::ParseOnrestart}},
597 {"oom_score_adjust", {1, 1, &ServiceParser::ParseOomScoreAdjust}},
598 {"override", {0, 0, &ServiceParser::ParseOverride}},
599 {"priority", {1, 1, &ServiceParser::ParsePriority}},
600 {"reboot_on_failure", {1, 1, &ServiceParser::ParseRebootOnFailure}},
601 {"restart_period", {1, 1, &ServiceParser::ParseRestartPeriod}},
602 {"rlimit", {3, 3, &ServiceParser::ParseProcessRlimit}},
603 {"seclabel", {1, 1, &ServiceParser::ParseSeclabel}},
604 {"setenv", {2, 2, &ServiceParser::ParseSetenv}},
605 {"shutdown", {1, 1, &ServiceParser::ParseShutdown}},
606 {"sigstop", {0, 0, &ServiceParser::ParseSigstop}},
607 {"socket", {3, 6, &ServiceParser::ParseSocket}},
Tom Cherryf74b7f52019-09-23 16:16:54 -0700608 {"stdio_to_kmsg", {0, 0, &ServiceParser::ParseStdioToKmsg}},
Suren Baghdasaryanc9c0bba2020-04-30 11:58:39 -0700609 {"task_profiles", {1, kMax, &ServiceParser::ParseTaskProfiles}},
Tom Cherry60971e62019-09-10 10:40:47 -0700610 {"timeout_period", {1, 1, &ServiceParser::ParseTimeoutPeriod}},
611 {"updatable", {0, 0, &ServiceParser::ParseUpdatable}},
612 {"user", {1, 1, &ServiceParser::ParseUser}},
613 {"writepid", {1, kMax, &ServiceParser::ParseWritepid}},
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700614 };
615 // clang-format on
Tom Cherryd52a5b32019-07-22 16:05:36 -0700616 return parser_map;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700617}
618
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700619Result<void> ServiceParser::ParseSection(std::vector<std::string>&& args,
620 const std::string& filename, int line) {
621 if (args.size() < 3) {
622 return Error() << "services must have a name and a program";
623 }
624
625 const std::string& name = args[1];
626 if (!IsValidName(name)) {
627 return Error() << "invalid service name '" << name << "'";
628 }
629
630 filename_ = filename;
631
632 Subcontext* restart_action_subcontext = nullptr;
Tom Cherry14c24722019-09-18 13:47:19 -0700633 if (subcontext_ && subcontext_->PathMatchesSubcontext(filename)) {
634 restart_action_subcontext = subcontext_;
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700635 }
636
637 std::vector<std::string> str_args(args.begin() + 2, args.end());
638
639 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_P__) {
640 if (str_args[0] == "/sbin/watchdogd") {
641 str_args[0] = "/system/bin/watchdogd";
642 }
643 }
Yifan Hong8fb7f772019-10-16 14:22:12 -0700644 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
645 if (str_args[0] == "/charger") {
646 str_args[0] = "/system/bin/charger";
647 }
648 }
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700649
Nikita Ioffe091c4d12019-12-05 12:35:19 +0000650 service_ = std::make_unique<Service>(name, restart_action_subcontext, str_args, from_apex_);
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700651 return {};
652}
653
654Result<void> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700655 if (!service_) {
656 return {};
657 }
658
Tom Cherryd52a5b32019-07-22 16:05:36 -0700659 auto parser = GetParserMap().Find(args);
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700660
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900661 if (!parser.ok()) return parser.error();
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700662
663 return std::invoke(*parser, this, std::move(args));
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700664}
665
666Result<void> ServiceParser::EndSection() {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700667 if (!service_) {
668 return {};
669 }
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700670
Daniel Norman3f42a762019-07-09 11:00:53 -0700671 if (interface_inheritance_hierarchy_) {
Daniel Normand2533c32019-08-02 15:13:50 -0700672 if (const auto& check_hierarchy_result = CheckInterfaceInheritanceHierarchy(
673 service_->interfaces(), *interface_inheritance_hierarchy_);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900674 !check_hierarchy_result.ok()) {
Daniel Normand2533c32019-08-02 15:13:50 -0700675 return Error() << check_hierarchy_result.error();
Daniel Norman3f42a762019-07-09 11:00:53 -0700676 }
677 }
678
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100679 if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__) {
680 if ((service_->flags() & SVC_CRITICAL) != 0 && (service_->flags() & SVC_ONESHOT) != 0) {
681 return Error() << "service '" << service_->name()
682 << "' can't be both critical and oneshot";
683 }
684 }
685
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700686 Service* old_service = service_list_->FindService(service_->name());
687 if (old_service) {
688 if (!service_->is_override()) {
689 return Error() << "ignored duplicate definition of service '" << service_->name()
690 << "'";
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700691 }
692
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700693 if (StartsWith(filename_, "/apex/") && !old_service->is_updatable()) {
694 return Error() << "cannot update a non-updatable service '" << service_->name()
695 << "' with a config in APEX";
696 }
697
Daniel Normanf597fa52020-11-09 17:28:24 -0800698 std::string context = service_->subcontext() ? service_->subcontext()->context() : "";
699 std::string old_context =
700 old_service->subcontext() ? old_service->subcontext()->context() : "";
701 if (context != old_context) {
702 return Error() << "service '" << service_->name() << "' overrides another service "
703 << "across the treble boundary.";
704 }
705
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700706 service_list_->RemoveService(*old_service);
707 old_service = nullptr;
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700708 }
709
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700710 service_list_->AddService(std::move(service_));
711
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700712 return {};
713}
714
715bool ServiceParser::IsValidName(const std::string& name) const {
716 // Property names can be any length, but may only contain certain characters.
717 // Property values can contain any characters, but may only be a certain length.
718 // (The latter restriction is needed because `start` and `stop` work by writing
719 // the service name to the "ctl.start" and "ctl.stop" properties.)
720 return IsLegalPropertyName("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
721}
722
723} // namespace init
724} // namespace android