blob: 92e350be607c647f14f33c9e8a4d301413960f9a [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>
Steven Morelande5349192023-04-24 23:54:59 +000028#include <android-base/properties.h>
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070029#include <android-base/strings.h>
30#include <hidl-util/FQName.h>
Suren Baghdasaryan746ede92022-03-31 21:15:11 +000031#include <processgroup/processgroup.h>
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070032#include <system/thread_defs.h>
33
Suren Baghdasaryanc29c2ba2019-10-22 17:18:42 -070034#include "lmkd_service.h"
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070035#include "rlimit_parser.h"
Tom Cherry2e4c85f2019-07-09 13:33:36 -070036#include "service_utils.h"
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070037#include "util.h"
38
Tom Cherrya2f91362020-02-20 10:50:00 -080039#ifdef INIT_FULL_SOURCES
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070040#include <android/api-level.h>
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070041#include <sys/system_properties.h>
42
43#include "selinux.h"
44#else
45#include "host_init_stubs.h"
46#endif
47
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070048using android::base::ParseInt;
49using android::base::Split;
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070050using android::base::StartsWith;
51
52namespace android {
53namespace init {
54
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070055Result<void> ServiceParser::ParseCapabilities(std::vector<std::string>&& args) {
56 service_->capabilities_ = 0;
57
58 if (!CapAmbientSupported()) {
59 return Error()
60 << "capabilities requested but the kernel does not support ambient capabilities";
61 }
62
63 unsigned int last_valid_cap = GetLastValidCap();
64 if (last_valid_cap >= service_->capabilities_->size()) {
65 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
66 }
67
68 for (size_t i = 1; i < args.size(); i++) {
69 const std::string& arg = args[i];
70 int res = LookupCap(arg);
71 if (res < 0) {
72 return Errorf("invalid capability '{}'", arg);
73 }
74 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
75 if (cap > last_valid_cap) {
76 return Errorf("capability '{}' not supported by the kernel", arg);
77 }
78 (*service_->capabilities_)[cap] = true;
79 }
80 return {};
81}
82
83Result<void> ServiceParser::ParseClass(std::vector<std::string>&& args) {
84 service_->classnames_ = std::set<std::string>(args.begin() + 1, args.end());
85 return {};
86}
87
88Result<void> ServiceParser::ParseConsole(std::vector<std::string>&& args) {
Tom Cherryf74b7f52019-09-23 16:16:54 -070089 if (service_->proc_attr_.stdio_to_kmsg) {
90 return Error() << "'console' and 'stdio_to_kmsg' are mutually exclusive";
91 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070092 service_->flags_ |= SVC_CONSOLE;
93 service_->proc_attr_.console = args.size() > 1 ? "/dev/" + args[1] : "";
94 return {};
95}
96
97Result<void> ServiceParser::ParseCritical(std::vector<std::string>&& args) {
Woody Lin45215ae2019-12-26 22:22:28 +080098 std::optional<std::string> fatal_reboot_target;
99 std::optional<std::chrono::minutes> fatal_crash_window;
100
101 for (auto it = args.begin() + 1; it != args.end(); ++it) {
102 auto arg = android::base::Split(*it, "=");
103 if (arg.size() != 2) {
104 return Error() << "critical: Argument '" << *it << "' is not supported";
105 } else if (arg[0] == "target") {
106 fatal_reboot_target = arg[1];
107 } else if (arg[0] == "window") {
108 int minutes;
109 auto window = ExpandProps(arg[1]);
110 if (!window.ok()) {
111 return Error() << "critical: Could not expand argument ': " << arg[1];
112 }
113 if (*window == "off") {
114 return {};
115 }
116 if (!ParseInt(*window, &minutes, 0)) {
117 return Error() << "critical: 'fatal_crash_window' must be an integer > 0";
118 }
119 fatal_crash_window = std::chrono::minutes(minutes);
120 } else {
121 return Error() << "critical: Argument '" << *it << "' is not supported";
122 }
123 }
124
125 if (fatal_reboot_target) {
126 service_->fatal_reboot_target_ = *fatal_reboot_target;
127 }
128 if (fatal_crash_window) {
129 service_->fatal_crash_window_ = *fatal_crash_window;
130 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700131 service_->flags_ |= SVC_CRITICAL;
132 return {};
133}
134
135Result<void> ServiceParser::ParseDisabled(std::vector<std::string>&& args) {
136 service_->flags_ |= SVC_DISABLED;
137 service_->flags_ |= SVC_RC_DISABLED;
138 return {};
139}
140
141Result<void> ServiceParser::ParseEnterNamespace(std::vector<std::string>&& args) {
142 if (args[1] != "net") {
143 return Error() << "Init only supports entering network namespaces";
144 }
145 if (!service_->namespaces_.namespaces_to_enter.empty()) {
146 return Error() << "Only one network namespace may be entered";
147 }
148 // Network namespaces require that /sys is remounted, otherwise the old adapters will still be
149 // present. Therefore, they also require mount namespaces.
150 service_->namespaces_.flags |= CLONE_NEWNS;
151 service_->namespaces_.namespaces_to_enter.emplace_back(CLONE_NEWNET, std::move(args[2]));
152 return {};
153}
154
Daniel Rosenbergde766882022-12-01 15:44:31 -0800155Result<void> ServiceParser::ParseGentleKill(std::vector<std::string>&& args) {
156 service_->flags_ |= SVC_GENTLE_KILL;
157 return {};
158}
159
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700160Result<void> ServiceParser::ParseGroup(std::vector<std::string>&& args) {
161 auto gid = DecodeUid(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900162 if (!gid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700163 return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
164 }
165 service_->proc_attr_.gid = *gid;
166
167 for (std::size_t n = 2; n < args.size(); n++) {
168 gid = DecodeUid(args[n]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900169 if (!gid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700170 return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
171 }
172 service_->proc_attr_.supp_gids.emplace_back(*gid);
173 }
174 return {};
175}
176
177Result<void> ServiceParser::ParsePriority(std::vector<std::string>&& args) {
178 service_->proc_attr_.priority = 0;
179 if (!ParseInt(args[1], &service_->proc_attr_.priority,
180 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
181 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
Henri Chataing6bdb5f82023-11-01 17:25:37 +0000182 return Errorf("process priority value must be range {} - {}",
183 static_cast<int>(ANDROID_PRIORITY_HIGHEST),
184 static_cast<int>(ANDROID_PRIORITY_LOWEST));
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700185 }
186 return {};
187}
188
189Result<void> ServiceParser::ParseInterface(std::vector<std::string>&& args) {
190 const std::string& interface_name = args[1];
191 const std::string& instance_name = args[2];
192
Jon Spivack16fb3f92019-07-26 13:14:42 -0700193 // AIDL services don't use fully qualified names and instead just use "interface aidl <name>"
194 if (interface_name != "aidl") {
195 FQName fq_name;
196 if (!FQName::parse(interface_name, &fq_name)) {
197 return Error() << "Invalid fully-qualified name for interface '" << interface_name
198 << "'";
199 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700200
Jon Spivack16fb3f92019-07-26 13:14:42 -0700201 if (!fq_name.isFullyQualified()) {
202 return Error() << "Interface name not fully-qualified '" << interface_name << "'";
203 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700204
Jon Spivack16fb3f92019-07-26 13:14:42 -0700205 if (fq_name.isValidValueName()) {
206 return Error() << "Interface name must not be a value name '" << interface_name << "'";
207 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700208 }
209
210 const std::string fullname = interface_name + "/" + instance_name;
211
212 for (const auto& svc : *service_list_) {
Alexander Koskoviche5f05202022-03-06 15:51:51 -0700213 if (svc->interfaces().count(fullname) > 0 && !service_->is_override()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700214 return Error() << "Interface '" << fullname << "' redefined in " << service_->name()
215 << " but is already defined by " << svc->name();
216 }
217 }
218
219 service_->interfaces_.insert(fullname);
220
221 return {};
222}
223
224Result<void> ServiceParser::ParseIoprio(std::vector<std::string>&& args) {
225 if (!ParseInt(args[2], &service_->proc_attr_.ioprio_pri, 0, 7)) {
226 return Error() << "priority value must be range 0 - 7";
227 }
228
229 if (args[1] == "rt") {
230 service_->proc_attr_.ioprio_class = IoSchedClass_RT;
231 } else if (args[1] == "be") {
232 service_->proc_attr_.ioprio_class = IoSchedClass_BE;
233 } else if (args[1] == "idle") {
234 service_->proc_attr_.ioprio_class = IoSchedClass_IDLE;
235 } else {
236 return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
237 }
238
239 return {};
240}
241
242Result<void> ServiceParser::ParseKeycodes(std::vector<std::string>&& args) {
243 auto it = args.begin() + 1;
244 if (args.size() == 2 && StartsWith(args[1], "$")) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700245 auto expanded = ExpandProps(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900246 if (!expanded.ok()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700247 return expanded.error();
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700248 }
249
250 // If the property is not set, it defaults to none, in which case there are no keycodes
251 // for this service.
Bernie Innocenti1cc76df2020-02-03 23:54:02 +0900252 if (*expanded == "none") {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700253 return {};
254 }
255
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700256 args = Split(*expanded, ",");
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700257 it = args.begin();
258 }
259
260 for (; it != args.end(); ++it) {
261 int code;
262 if (ParseInt(*it, &code, 0, KEY_MAX)) {
263 for (auto& key : service_->keycodes_) {
264 if (key == code) return Error() << "duplicate keycode: " << *it;
265 }
266 service_->keycodes_.insert(
267 std::upper_bound(service_->keycodes_.begin(), service_->keycodes_.end(), code),
268 code);
269 } else {
270 return Error() << "invalid keycode: " << *it;
271 }
272 }
273 return {};
274}
275
276Result<void> ServiceParser::ParseOneshot(std::vector<std::string>&& args) {
277 service_->flags_ |= SVC_ONESHOT;
278 return {};
279}
280
281Result<void> ServiceParser::ParseOnrestart(std::vector<std::string>&& args) {
282 args.erase(args.begin());
283 int line = service_->onrestart_.NumCommands() + 1;
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900284 if (auto result = service_->onrestart_.AddCommand(std::move(args), line); !result.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700285 return Error() << "cannot add Onrestart command: " << result.error();
286 }
287 return {};
288}
289
290Result<void> ServiceParser::ParseNamespace(std::vector<std::string>&& args) {
291 for (size_t i = 1; i < args.size(); i++) {
292 if (args[i] == "pid") {
293 service_->namespaces_.flags |= CLONE_NEWPID;
294 // PID namespaces require mount namespaces.
295 service_->namespaces_.flags |= CLONE_NEWNS;
296 } else if (args[i] == "mnt") {
297 service_->namespaces_.flags |= CLONE_NEWNS;
298 } else {
299 return Error() << "namespace must be 'pid' or 'mnt'";
300 }
301 }
302 return {};
303}
304
305Result<void> ServiceParser::ParseOomScoreAdjust(std::vector<std::string>&& args) {
Suren Baghdasaryanc29c2ba2019-10-22 17:18:42 -0700306 if (!ParseInt(args[1], &service_->oom_score_adjust_, MIN_OOM_SCORE_ADJUST,
307 MAX_OOM_SCORE_ADJUST)) {
308 return Error() << "oom_score_adjust value must be in range " << MIN_OOM_SCORE_ADJUST
309 << " - +" << MAX_OOM_SCORE_ADJUST;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700310 }
311 return {};
312}
313
314Result<void> ServiceParser::ParseOverride(std::vector<std::string>&& args) {
315 service_->override_ = true;
316 return {};
317}
318
319Result<void> ServiceParser::ParseMemcgSwappiness(std::vector<std::string>&& args) {
320 if (!ParseInt(args[1], &service_->swappiness_, 0)) {
321 return Error() << "swappiness value must be equal or greater than 0";
322 }
323 return {};
324}
325
326Result<void> ServiceParser::ParseMemcgLimitInBytes(std::vector<std::string>&& args) {
327 if (!ParseInt(args[1], &service_->limit_in_bytes_, 0)) {
328 return Error() << "limit_in_bytes value must be equal or greater than 0";
329 }
330 return {};
331}
332
333Result<void> ServiceParser::ParseMemcgLimitPercent(std::vector<std::string>&& args) {
334 if (!ParseInt(args[1], &service_->limit_percent_, 0)) {
335 return Error() << "limit_percent value must be equal or greater than 0";
336 }
337 return {};
338}
339
340Result<void> ServiceParser::ParseMemcgLimitProperty(std::vector<std::string>&& args) {
341 service_->limit_property_ = std::move(args[1]);
342 return {};
343}
344
345Result<void> ServiceParser::ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args) {
346 if (!ParseInt(args[1], &service_->soft_limit_in_bytes_, 0)) {
347 return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
348 }
349 return {};
350}
351
352Result<void> ServiceParser::ParseProcessRlimit(std::vector<std::string>&& args) {
353 auto rlimit = ParseRlimit(args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900354 if (!rlimit.ok()) return rlimit.error();
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700355
356 service_->proc_attr_.rlimits.emplace_back(*rlimit);
357 return {};
358}
359
Tom Cherry60971e62019-09-10 10:40:47 -0700360Result<void> ServiceParser::ParseRebootOnFailure(std::vector<std::string>&& args) {
361 if (service_->on_failure_reboot_target_) {
362 return Error() << "Only one reboot_on_failure command may be specified";
363 }
364 if (!StartsWith(args[1], "shutdown") && !StartsWith(args[1], "reboot")) {
365 return Error()
366 << "reboot_on_failure commands must begin with either 'shutdown' or 'reboot'";
367 }
368 service_->on_failure_reboot_target_ = std::move(args[1]);
369 return {};
370}
371
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700372Result<void> ServiceParser::ParseRestartPeriod(std::vector<std::string>&& args) {
373 int period;
Jiyong Park0d277d72023-06-09 09:52:49 +0900374 if (!ParseInt(args[1], &period, 0)) {
375 return Error() << "restart_period value must be an integer >= 0";
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700376 }
377 service_->restart_period_ = std::chrono::seconds(period);
378 return {};
379}
380
381Result<void> ServiceParser::ParseSeclabel(std::vector<std::string>&& args) {
382 service_->seclabel_ = std::move(args[1]);
383 return {};
384}
385
386Result<void> ServiceParser::ParseSigstop(std::vector<std::string>&& args) {
387 service_->sigstop_ = true;
388 return {};
389}
390
391Result<void> ServiceParser::ParseSetenv(std::vector<std::string>&& args) {
392 service_->environment_vars_.emplace_back(std::move(args[1]), std::move(args[2]));
393 return {};
394}
395
396Result<void> ServiceParser::ParseShutdown(std::vector<std::string>&& args) {
397 if (args[1] == "critical") {
398 service_->flags_ |= SVC_SHUTDOWN_CRITICAL;
399 return {};
400 }
401 return Error() << "Invalid shutdown option";
402}
403
Suren Baghdasaryanc9c0bba2020-04-30 11:58:39 -0700404Result<void> ServiceParser::ParseTaskProfiles(std::vector<std::string>&& args) {
405 args.erase(args.begin());
Suren Baghdasaryan746ede92022-03-31 21:15:11 +0000406 if (service_->task_profiles_.empty()) {
407 service_->task_profiles_ = std::move(args);
408 } else {
409 // Some task profiles might have been added during writepid conversions
410 service_->task_profiles_.insert(service_->task_profiles_.end(),
411 std::make_move_iterator(args.begin()),
412 std::make_move_iterator(args.end()));
413 args.clear();
414 }
Suren Baghdasaryanc9c0bba2020-04-30 11:58:39 -0700415 return {};
416}
417
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700418Result<void> ServiceParser::ParseTimeoutPeriod(std::vector<std::string>&& args) {
419 int period;
420 if (!ParseInt(args[1], &period, 1)) {
421 return Error() << "timeout_period value must be an integer >= 1";
422 }
423 service_->timeout_period_ = std::chrono::seconds(period);
424 return {};
425}
426
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700427// name type perm [ uid gid context ]
428Result<void> ServiceParser::ParseSocket(std::vector<std::string>&& args) {
429 SocketDescriptor socket;
430 socket.name = std::move(args[1]);
431
432 auto types = Split(args[2], "+");
433 if (types[0] == "stream") {
434 socket.type = SOCK_STREAM;
435 } else if (types[0] == "dgram") {
436 socket.type = SOCK_DGRAM;
437 } else if (types[0] == "seqpacket") {
438 socket.type = SOCK_SEQPACKET;
439 } else {
440 return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket', got '" << types[0]
441 << "' instead.";
442 }
443
Adam Langleyecc14a52022-05-11 22:32:47 +0000444 for (size_t i = 1; i < types.size(); i++) {
445 if (types[i] == "passcred") {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700446 socket.passcred = true;
Adam Langleyecc14a52022-05-11 22:32:47 +0000447 } else if (types[i] == "listen") {
448 socket.listen = true;
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700449 } else {
Adam Langleyecc14a52022-05-11 22:32:47 +0000450 return Error() << "Unknown socket type decoration '" << types[i]
451 << "'. Known values are ['passcred', 'listen']";
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700452 }
453 }
454
455 errno = 0;
456 char* end = nullptr;
457 socket.perm = strtol(args[3].c_str(), &end, 8);
458 if (errno != 0) {
459 return ErrnoError() << "Unable to parse permissions '" << args[3] << "'";
460 }
461 if (end == args[3].c_str() || *end != '\0') {
462 errno = EINVAL;
463 return ErrnoError() << "Unable to parse permissions '" << args[3] << "'";
464 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700465
466 if (args.size() > 4) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700467 auto uid = DecodeUid(args[4]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900468 if (!uid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700469 return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
470 }
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700471 socket.uid = *uid;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700472 }
473
474 if (args.size() > 5) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700475 auto gid = DecodeUid(args[5]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900476 if (!gid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700477 return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
478 }
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700479 socket.gid = *gid;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700480 }
481
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700482 socket.context = args.size() > 6 ? args[6] : "";
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700483
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700484 auto old = std::find_if(service_->sockets_.begin(), service_->sockets_.end(),
485 [&socket](const auto& other) { return socket.name == other.name; });
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700486
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700487 if (old != service_->sockets_.end()) {
488 return Error() << "duplicate socket descriptor '" << socket.name << "'";
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700489 }
490
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700491 service_->sockets_.emplace_back(std::move(socket));
492
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700493 return {};
494}
495
Tom Cherryf74b7f52019-09-23 16:16:54 -0700496Result<void> ServiceParser::ParseStdioToKmsg(std::vector<std::string>&& args) {
497 if (service_->flags_ & SVC_CONSOLE) {
498 return Error() << "'stdio_to_kmsg' and 'console' are mutually exclusive";
499 }
500 service_->proc_attr_.stdio_to_kmsg = true;
501 return {};
502}
503
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700504// name type
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700505Result<void> ServiceParser::ParseFile(std::vector<std::string>&& args) {
506 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
507 return Error() << "file type must be 'r', 'w' or 'rw'";
508 }
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700509
510 FileDescriptor file;
511 file.type = args[2];
512
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700513 auto file_name = ExpandProps(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900514 if (!file_name.ok()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700515 return Error() << "Could not expand file path ': " << file_name.error();
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700516 }
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700517 file.name = *file_name;
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700518 if (file.name[0] != '/' || file.name.find("../") != std::string::npos) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700519 return Error() << "file name must not be relative";
520 }
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700521
522 auto old = std::find_if(service_->files_.begin(), service_->files_.end(),
523 [&file](const auto& other) { return other.name == file.name; });
524
525 if (old != service_->files_.end()) {
526 return Error() << "duplicate file descriptor '" << file.name << "'";
527 }
528
529 service_->files_.emplace_back(std::move(file));
530
531 return {};
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700532}
533
534Result<void> ServiceParser::ParseUser(std::vector<std::string>&& args) {
535 auto uid = DecodeUid(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900536 if (!uid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700537 return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
538 }
Steven Morelandf5d22ef2023-04-03 23:29:22 +0000539 service_->proc_attr_.parsed_uid = *uid;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700540 return {};
541}
542
Suren Baghdasaryan746ede92022-03-31 21:15:11 +0000543// Convert legacy paths used to migrate processes between cgroups using writepid command.
544// We can't get these paths from TaskProfiles because profile definitions are changing
545// when we migrate to cgroups v2 while these hardcoded paths stay the same.
546static std::optional<const std::string> ConvertTaskFileToProfile(const std::string& file) {
547 static const std::map<const std::string, const std::string> map = {
548 {"/dev/stune/top-app/tasks", "MaxPerformance"},
549 {"/dev/stune/foreground/tasks", "HighPerformance"},
550 {"/dev/cpuset/camera-daemon/tasks", "CameraServiceCapacity"},
551 {"/dev/cpuset/foreground/tasks", "ProcessCapacityHigh"},
552 {"/dev/cpuset/system-background/tasks", "ServiceCapacityLow"},
553 {"/dev/stune/nnapi-hal/tasks", "NNApiHALPerformance"},
554 {"/dev/blkio/background/tasks", "LowIoPriority"},
555 };
556 auto iter = map.find(file);
557 return iter == map.end() ? std::nullopt : std::make_optional<const std::string>(iter->second);
558}
559
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700560Result<void> ServiceParser::ParseWritepid(std::vector<std::string>&& args) {
561 args.erase(args.begin());
Suren Baghdasaryan746ede92022-03-31 21:15:11 +0000562 // Convert any cgroup writes into appropriate task_profiles
563 for (auto iter = args.begin(); iter != args.end();) {
564 auto task_profile = ConvertTaskFileToProfile(*iter);
565 if (task_profile) {
566 LOG(WARNING) << "'writepid " << *iter << "' is converted into 'task_profiles "
567 << task_profile.value() << "' for service " << service_->name();
568 service_->task_profiles_.push_back(task_profile.value());
569 iter = args.erase(iter);
570 } else {
571 ++iter;
572 }
573 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700574 service_->writepid_files_ = std::move(args);
575 return {};
576}
577
578Result<void> ServiceParser::ParseUpdatable(std::vector<std::string>&& args) {
579 service_->updatable_ = true;
580 return {};
581}
582
Tom Cherryd52a5b32019-07-22 16:05:36 -0700583const KeywordMap<ServiceParser::OptionParser>& ServiceParser::GetParserMap() const {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700584 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
585 // clang-format off
Tom Cherryd52a5b32019-07-22 16:05:36 -0700586 static const KeywordMap<ServiceParser::OptionParser> parser_map = {
Tom Cherry60971e62019-09-10 10:40:47 -0700587 {"capabilities", {0, kMax, &ServiceParser::ParseCapabilities}},
588 {"class", {1, kMax, &ServiceParser::ParseClass}},
589 {"console", {0, 1, &ServiceParser::ParseConsole}},
Woody Lin45215ae2019-12-26 22:22:28 +0800590 {"critical", {0, 2, &ServiceParser::ParseCritical}},
Tom Cherry60971e62019-09-10 10:40:47 -0700591 {"disabled", {0, 0, &ServiceParser::ParseDisabled}},
592 {"enter_namespace", {2, 2, &ServiceParser::ParseEnterNamespace}},
593 {"file", {2, 2, &ServiceParser::ParseFile}},
Daniel Rosenbergde766882022-12-01 15:44:31 -0800594 {"gentle_kill", {0, 0, &ServiceParser::ParseGentleKill}},
Tom Cherry60971e62019-09-10 10:40:47 -0700595 {"group", {1, NR_SVC_SUPP_GIDS + 1, &ServiceParser::ParseGroup}},
596 {"interface", {2, 2, &ServiceParser::ParseInterface}},
597 {"ioprio", {2, 2, &ServiceParser::ParseIoprio}},
598 {"keycodes", {1, kMax, &ServiceParser::ParseKeycodes}},
599 {"memcg.limit_in_bytes", {1, 1, &ServiceParser::ParseMemcgLimitInBytes}},
600 {"memcg.limit_percent", {1, 1, &ServiceParser::ParseMemcgLimitPercent}},
601 {"memcg.limit_property", {1, 1, &ServiceParser::ParseMemcgLimitProperty}},
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700602 {"memcg.soft_limit_in_bytes",
Tom Cherry60971e62019-09-10 10:40:47 -0700603 {1, 1, &ServiceParser::ParseMemcgSoftLimitInBytes}},
604 {"memcg.swappiness", {1, 1, &ServiceParser::ParseMemcgSwappiness}},
605 {"namespace", {1, 2, &ServiceParser::ParseNamespace}},
606 {"oneshot", {0, 0, &ServiceParser::ParseOneshot}},
607 {"onrestart", {1, kMax, &ServiceParser::ParseOnrestart}},
608 {"oom_score_adjust", {1, 1, &ServiceParser::ParseOomScoreAdjust}},
609 {"override", {0, 0, &ServiceParser::ParseOverride}},
610 {"priority", {1, 1, &ServiceParser::ParsePriority}},
611 {"reboot_on_failure", {1, 1, &ServiceParser::ParseRebootOnFailure}},
612 {"restart_period", {1, 1, &ServiceParser::ParseRestartPeriod}},
613 {"rlimit", {3, 3, &ServiceParser::ParseProcessRlimit}},
614 {"seclabel", {1, 1, &ServiceParser::ParseSeclabel}},
615 {"setenv", {2, 2, &ServiceParser::ParseSetenv}},
616 {"shutdown", {1, 1, &ServiceParser::ParseShutdown}},
617 {"sigstop", {0, 0, &ServiceParser::ParseSigstop}},
618 {"socket", {3, 6, &ServiceParser::ParseSocket}},
Tom Cherryf74b7f52019-09-23 16:16:54 -0700619 {"stdio_to_kmsg", {0, 0, &ServiceParser::ParseStdioToKmsg}},
Suren Baghdasaryanc9c0bba2020-04-30 11:58:39 -0700620 {"task_profiles", {1, kMax, &ServiceParser::ParseTaskProfiles}},
Tom Cherry60971e62019-09-10 10:40:47 -0700621 {"timeout_period", {1, 1, &ServiceParser::ParseTimeoutPeriod}},
622 {"updatable", {0, 0, &ServiceParser::ParseUpdatable}},
623 {"user", {1, 1, &ServiceParser::ParseUser}},
624 {"writepid", {1, kMax, &ServiceParser::ParseWritepid}},
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700625 };
626 // clang-format on
Tom Cherryd52a5b32019-07-22 16:05:36 -0700627 return parser_map;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700628}
629
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700630Result<void> ServiceParser::ParseSection(std::vector<std::string>&& args,
631 const std::string& filename, int line) {
632 if (args.size() < 3) {
633 return Error() << "services must have a name and a program";
634 }
635
636 const std::string& name = args[1];
637 if (!IsValidName(name)) {
638 return Error() << "invalid service name '" << name << "'";
639 }
640
641 filename_ = filename;
642
643 Subcontext* restart_action_subcontext = nullptr;
Tom Cherry14c24722019-09-18 13:47:19 -0700644 if (subcontext_ && subcontext_->PathMatchesSubcontext(filename)) {
645 restart_action_subcontext = subcontext_;
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700646 }
647
648 std::vector<std::string> str_args(args.begin() + 2, args.end());
649
650 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_P__) {
651 if (str_args[0] == "/sbin/watchdogd") {
652 str_args[0] = "/system/bin/watchdogd";
653 }
654 }
Yifan Hong8fb7f772019-10-16 14:22:12 -0700655 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
656 if (str_args[0] == "/charger") {
657 str_args[0] = "/system/bin/charger";
658 }
659 }
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700660
Deyao Rendf40ed12022-07-14 22:51:10 +0000661 service_ = std::make_unique<Service>(name, restart_action_subcontext, filename, str_args);
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700662 return {};
663}
664
665Result<void> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700666 if (!service_) {
667 return {};
668 }
669
Tom Cherryd52a5b32019-07-22 16:05:36 -0700670 auto parser = GetParserMap().Find(args);
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700671
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900672 if (!parser.ok()) return parser.error();
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700673
674 return std::invoke(*parser, this, std::move(args));
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700675}
676
677Result<void> ServiceParser::EndSection() {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700678 if (!service_) {
679 return {};
680 }
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700681
Steven Morelandf5d22ef2023-04-03 23:29:22 +0000682 if (service_->proc_attr_.parsed_uid == std::nullopt) {
Steven Morelande5349192023-04-24 23:54:59 +0000683 if (android::base::GetIntProperty("ro.vendor.api_level", 0) > __ANDROID_API_U__) {
684 return Error() << "No user specified for service '" << service_->name()
685 << "'. Defaults to root.";
686 } else {
687 LOG(WARNING) << "No user specified for service '" << service_->name()
688 << "'. Defaults to root.";
689 }
Steven Morelandf5d22ef2023-04-03 23:29:22 +0000690 }
691
Daniel Norman3f42a762019-07-09 11:00:53 -0700692 if (interface_inheritance_hierarchy_) {
Daniel Normand2533c32019-08-02 15:13:50 -0700693 if (const auto& check_hierarchy_result = CheckInterfaceInheritanceHierarchy(
694 service_->interfaces(), *interface_inheritance_hierarchy_);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900695 !check_hierarchy_result.ok()) {
Daniel Normand2533c32019-08-02 15:13:50 -0700696 return Error() << check_hierarchy_result.error();
Daniel Norman3f42a762019-07-09 11:00:53 -0700697 }
698 }
699
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100700 if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__) {
701 if ((service_->flags() & SVC_CRITICAL) != 0 && (service_->flags() & SVC_ONESHOT) != 0) {
702 return Error() << "service '" << service_->name()
703 << "' can't be both critical and oneshot";
704 }
705 }
706
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700707 Service* old_service = service_list_->FindService(service_->name());
708 if (old_service) {
709 if (!service_->is_override()) {
710 return Error() << "ignored duplicate definition of service '" << service_->name()
711 << "'";
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700712 }
713
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700714 if (StartsWith(filename_, "/apex/") && !old_service->is_updatable()) {
715 return Error() << "cannot update a non-updatable service '" << service_->name()
716 << "' with a config in APEX";
717 }
718
Daniel Normanf597fa52020-11-09 17:28:24 -0800719 std::string context = service_->subcontext() ? service_->subcontext()->context() : "";
720 std::string old_context =
721 old_service->subcontext() ? old_service->subcontext()->context() : "";
722 if (context != old_context) {
723 return Error() << "service '" << service_->name() << "' overrides another service "
724 << "across the treble boundary.";
725 }
726
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700727 service_list_->RemoveService(*old_service);
728 old_service = nullptr;
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700729 }
730
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700731 service_list_->AddService(std::move(service_));
732
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700733 return {};
734}
735
736bool ServiceParser::IsValidName(const std::string& name) const {
737 // Property names can be any length, but may only contain certain characters.
738 // Property values can contain any characters, but may only be a certain length.
739 // (The latter restriction is needed because `start` and `stop` work by writing
740 // the service name to the "ctl.start" and "ctl.stop" properties.)
741 return IsLegalPropertyName("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
742}
743
744} // namespace init
745} // namespace android