blob: 6781c7083c1d3ec51a0cce11b1bbacb7df05ee88 [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
Steven Moreland81a1b3e2024-05-20 22:31:11 +000055#ifdef INIT_FULL_SOURCES
56// on full sources, we have better information on device to
57// make this decision
58constexpr bool kAlwaysErrorUserRoot = false;
59#else
60constexpr uint64_t kBuildShippingApiLevel = BUILD_SHIPPING_API_LEVEL + 0 /* +0 if empty */;
61// on partial sources, the host build, we don't have the specific
62// vendor API level, but we can enforce things based on the
63// shipping API level.
64constexpr bool kAlwaysErrorUserRoot = kBuildShippingApiLevel > __ANDROID_API_V__;
65#endif
66
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070067Result<void> ServiceParser::ParseCapabilities(std::vector<std::string>&& args) {
68 service_->capabilities_ = 0;
69
70 if (!CapAmbientSupported()) {
71 return Error()
72 << "capabilities requested but the kernel does not support ambient capabilities";
73 }
74
75 unsigned int last_valid_cap = GetLastValidCap();
76 if (last_valid_cap >= service_->capabilities_->size()) {
77 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
78 }
79
80 for (size_t i = 1; i < args.size(); i++) {
81 const std::string& arg = args[i];
82 int res = LookupCap(arg);
83 if (res < 0) {
84 return Errorf("invalid capability '{}'", arg);
85 }
86 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
87 if (cap > last_valid_cap) {
88 return Errorf("capability '{}' not supported by the kernel", arg);
89 }
90 (*service_->capabilities_)[cap] = true;
91 }
92 return {};
93}
94
95Result<void> ServiceParser::ParseClass(std::vector<std::string>&& args) {
96 service_->classnames_ = std::set<std::string>(args.begin() + 1, args.end());
97 return {};
98}
99
100Result<void> ServiceParser::ParseConsole(std::vector<std::string>&& args) {
Tom Cherryf74b7f52019-09-23 16:16:54 -0700101 if (service_->proc_attr_.stdio_to_kmsg) {
102 return Error() << "'console' and 'stdio_to_kmsg' are mutually exclusive";
103 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700104 service_->flags_ |= SVC_CONSOLE;
105 service_->proc_attr_.console = args.size() > 1 ? "/dev/" + args[1] : "";
106 return {};
107}
108
109Result<void> ServiceParser::ParseCritical(std::vector<std::string>&& args) {
Woody Lin45215ae2019-12-26 22:22:28 +0800110 std::optional<std::string> fatal_reboot_target;
111 std::optional<std::chrono::minutes> fatal_crash_window;
112
113 for (auto it = args.begin() + 1; it != args.end(); ++it) {
114 auto arg = android::base::Split(*it, "=");
115 if (arg.size() != 2) {
116 return Error() << "critical: Argument '" << *it << "' is not supported";
117 } else if (arg[0] == "target") {
118 fatal_reboot_target = arg[1];
119 } else if (arg[0] == "window") {
120 int minutes;
121 auto window = ExpandProps(arg[1]);
122 if (!window.ok()) {
123 return Error() << "critical: Could not expand argument ': " << arg[1];
124 }
125 if (*window == "off") {
126 return {};
127 }
128 if (!ParseInt(*window, &minutes, 0)) {
129 return Error() << "critical: 'fatal_crash_window' must be an integer > 0";
130 }
131 fatal_crash_window = std::chrono::minutes(minutes);
132 } else {
133 return Error() << "critical: Argument '" << *it << "' is not supported";
134 }
135 }
136
137 if (fatal_reboot_target) {
138 service_->fatal_reboot_target_ = *fatal_reboot_target;
139 }
140 if (fatal_crash_window) {
141 service_->fatal_crash_window_ = *fatal_crash_window;
142 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700143 service_->flags_ |= SVC_CRITICAL;
144 return {};
145}
146
147Result<void> ServiceParser::ParseDisabled(std::vector<std::string>&& args) {
148 service_->flags_ |= SVC_DISABLED;
149 service_->flags_ |= SVC_RC_DISABLED;
150 return {};
151}
152
153Result<void> ServiceParser::ParseEnterNamespace(std::vector<std::string>&& args) {
154 if (args[1] != "net") {
155 return Error() << "Init only supports entering network namespaces";
156 }
157 if (!service_->namespaces_.namespaces_to_enter.empty()) {
158 return Error() << "Only one network namespace may be entered";
159 }
160 // Network namespaces require that /sys is remounted, otherwise the old adapters will still be
161 // present. Therefore, they also require mount namespaces.
162 service_->namespaces_.flags |= CLONE_NEWNS;
163 service_->namespaces_.namespaces_to_enter.emplace_back(CLONE_NEWNET, std::move(args[2]));
164 return {};
165}
166
Daniel Rosenbergde766882022-12-01 15:44:31 -0800167Result<void> ServiceParser::ParseGentleKill(std::vector<std::string>&& args) {
168 service_->flags_ |= SVC_GENTLE_KILL;
169 return {};
170}
171
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700172Result<void> ServiceParser::ParseGroup(std::vector<std::string>&& args) {
173 auto gid = DecodeUid(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900174 if (!gid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700175 return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
176 }
177 service_->proc_attr_.gid = *gid;
178
179 for (std::size_t n = 2; n < args.size(); n++) {
180 gid = DecodeUid(args[n]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900181 if (!gid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700182 return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
183 }
184 service_->proc_attr_.supp_gids.emplace_back(*gid);
185 }
186 return {};
187}
188
189Result<void> ServiceParser::ParsePriority(std::vector<std::string>&& args) {
190 service_->proc_attr_.priority = 0;
191 if (!ParseInt(args[1], &service_->proc_attr_.priority,
192 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
193 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
Henri Chataing6bdb5f82023-11-01 17:25:37 +0000194 return Errorf("process priority value must be range {} - {}",
195 static_cast<int>(ANDROID_PRIORITY_HIGHEST),
196 static_cast<int>(ANDROID_PRIORITY_LOWEST));
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700197 }
198 return {};
199}
200
201Result<void> ServiceParser::ParseInterface(std::vector<std::string>&& args) {
202 const std::string& interface_name = args[1];
203 const std::string& instance_name = args[2];
204
Jon Spivack16fb3f92019-07-26 13:14:42 -0700205 // AIDL services don't use fully qualified names and instead just use "interface aidl <name>"
206 if (interface_name != "aidl") {
207 FQName fq_name;
208 if (!FQName::parse(interface_name, &fq_name)) {
209 return Error() << "Invalid fully-qualified name for interface '" << interface_name
210 << "'";
211 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700212
Jon Spivack16fb3f92019-07-26 13:14:42 -0700213 if (!fq_name.isFullyQualified()) {
214 return Error() << "Interface name not fully-qualified '" << interface_name << "'";
215 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700216
Jon Spivack16fb3f92019-07-26 13:14:42 -0700217 if (fq_name.isValidValueName()) {
218 return Error() << "Interface name must not be a value name '" << interface_name << "'";
219 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700220 }
221
222 const std::string fullname = interface_name + "/" + instance_name;
223
224 for (const auto& svc : *service_list_) {
Alexander Koskoviche5f05202022-03-06 15:51:51 -0700225 if (svc->interfaces().count(fullname) > 0 && !service_->is_override()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700226 return Error() << "Interface '" << fullname << "' redefined in " << service_->name()
227 << " but is already defined by " << svc->name();
228 }
229 }
230
231 service_->interfaces_.insert(fullname);
232
233 return {};
234}
235
236Result<void> ServiceParser::ParseIoprio(std::vector<std::string>&& args) {
237 if (!ParseInt(args[2], &service_->proc_attr_.ioprio_pri, 0, 7)) {
238 return Error() << "priority value must be range 0 - 7";
239 }
240
241 if (args[1] == "rt") {
242 service_->proc_attr_.ioprio_class = IoSchedClass_RT;
243 } else if (args[1] == "be") {
244 service_->proc_attr_.ioprio_class = IoSchedClass_BE;
245 } else if (args[1] == "idle") {
246 service_->proc_attr_.ioprio_class = IoSchedClass_IDLE;
247 } else {
248 return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
249 }
250
251 return {};
252}
253
254Result<void> ServiceParser::ParseKeycodes(std::vector<std::string>&& args) {
255 auto it = args.begin() + 1;
256 if (args.size() == 2 && StartsWith(args[1], "$")) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700257 auto expanded = ExpandProps(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900258 if (!expanded.ok()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700259 return expanded.error();
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700260 }
261
262 // If the property is not set, it defaults to none, in which case there are no keycodes
263 // for this service.
Bernie Innocenti1cc76df2020-02-03 23:54:02 +0900264 if (*expanded == "none") {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700265 return {};
266 }
267
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700268 args = Split(*expanded, ",");
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700269 it = args.begin();
270 }
271
272 for (; it != args.end(); ++it) {
273 int code;
274 if (ParseInt(*it, &code, 0, KEY_MAX)) {
275 for (auto& key : service_->keycodes_) {
276 if (key == code) return Error() << "duplicate keycode: " << *it;
277 }
278 service_->keycodes_.insert(
279 std::upper_bound(service_->keycodes_.begin(), service_->keycodes_.end(), code),
280 code);
281 } else {
282 return Error() << "invalid keycode: " << *it;
283 }
284 }
285 return {};
286}
287
288Result<void> ServiceParser::ParseOneshot(std::vector<std::string>&& args) {
289 service_->flags_ |= SVC_ONESHOT;
290 return {};
291}
292
293Result<void> ServiceParser::ParseOnrestart(std::vector<std::string>&& args) {
294 args.erase(args.begin());
295 int line = service_->onrestart_.NumCommands() + 1;
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900296 if (auto result = service_->onrestart_.AddCommand(std::move(args), line); !result.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700297 return Error() << "cannot add Onrestart command: " << result.error();
298 }
299 return {};
300}
301
302Result<void> ServiceParser::ParseNamespace(std::vector<std::string>&& args) {
303 for (size_t i = 1; i < args.size(); i++) {
304 if (args[i] == "pid") {
305 service_->namespaces_.flags |= CLONE_NEWPID;
306 // PID namespaces require mount namespaces.
307 service_->namespaces_.flags |= CLONE_NEWNS;
308 } else if (args[i] == "mnt") {
309 service_->namespaces_.flags |= CLONE_NEWNS;
310 } else {
311 return Error() << "namespace must be 'pid' or 'mnt'";
312 }
313 }
314 return {};
315}
316
317Result<void> ServiceParser::ParseOomScoreAdjust(std::vector<std::string>&& args) {
Suren Baghdasaryanc29c2ba2019-10-22 17:18:42 -0700318 if (!ParseInt(args[1], &service_->oom_score_adjust_, MIN_OOM_SCORE_ADJUST,
319 MAX_OOM_SCORE_ADJUST)) {
320 return Error() << "oom_score_adjust value must be in range " << MIN_OOM_SCORE_ADJUST
321 << " - +" << MAX_OOM_SCORE_ADJUST;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700322 }
323 return {};
324}
325
326Result<void> ServiceParser::ParseOverride(std::vector<std::string>&& args) {
327 service_->override_ = true;
328 return {};
329}
330
331Result<void> ServiceParser::ParseMemcgSwappiness(std::vector<std::string>&& args) {
332 if (!ParseInt(args[1], &service_->swappiness_, 0)) {
333 return Error() << "swappiness value must be equal or greater than 0";
334 }
335 return {};
336}
337
338Result<void> ServiceParser::ParseMemcgLimitInBytes(std::vector<std::string>&& args) {
339 if (!ParseInt(args[1], &service_->limit_in_bytes_, 0)) {
340 return Error() << "limit_in_bytes value must be equal or greater than 0";
341 }
342 return {};
343}
344
345Result<void> ServiceParser::ParseMemcgLimitPercent(std::vector<std::string>&& args) {
346 if (!ParseInt(args[1], &service_->limit_percent_, 0)) {
347 return Error() << "limit_percent value must be equal or greater than 0";
348 }
349 return {};
350}
351
352Result<void> ServiceParser::ParseMemcgLimitProperty(std::vector<std::string>&& args) {
353 service_->limit_property_ = std::move(args[1]);
354 return {};
355}
356
357Result<void> ServiceParser::ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args) {
358 if (!ParseInt(args[1], &service_->soft_limit_in_bytes_, 0)) {
359 return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
360 }
361 return {};
362}
363
364Result<void> ServiceParser::ParseProcessRlimit(std::vector<std::string>&& args) {
365 auto rlimit = ParseRlimit(args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900366 if (!rlimit.ok()) return rlimit.error();
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700367
368 service_->proc_attr_.rlimits.emplace_back(*rlimit);
369 return {};
370}
371
Tom Cherry60971e62019-09-10 10:40:47 -0700372Result<void> ServiceParser::ParseRebootOnFailure(std::vector<std::string>&& args) {
373 if (service_->on_failure_reboot_target_) {
374 return Error() << "Only one reboot_on_failure command may be specified";
375 }
376 if (!StartsWith(args[1], "shutdown") && !StartsWith(args[1], "reboot")) {
377 return Error()
378 << "reboot_on_failure commands must begin with either 'shutdown' or 'reboot'";
379 }
380 service_->on_failure_reboot_target_ = std::move(args[1]);
381 return {};
382}
383
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700384Result<void> ServiceParser::ParseRestartPeriod(std::vector<std::string>&& args) {
385 int period;
Jiyong Park0d277d72023-06-09 09:52:49 +0900386 if (!ParseInt(args[1], &period, 0)) {
387 return Error() << "restart_period value must be an integer >= 0";
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700388 }
389 service_->restart_period_ = std::chrono::seconds(period);
390 return {};
391}
392
393Result<void> ServiceParser::ParseSeclabel(std::vector<std::string>&& args) {
394 service_->seclabel_ = std::move(args[1]);
395 return {};
396}
397
398Result<void> ServiceParser::ParseSigstop(std::vector<std::string>&& args) {
399 service_->sigstop_ = true;
400 return {};
401}
402
403Result<void> ServiceParser::ParseSetenv(std::vector<std::string>&& args) {
404 service_->environment_vars_.emplace_back(std::move(args[1]), std::move(args[2]));
405 return {};
406}
407
408Result<void> ServiceParser::ParseShutdown(std::vector<std::string>&& args) {
409 if (args[1] == "critical") {
410 service_->flags_ |= SVC_SHUTDOWN_CRITICAL;
411 return {};
412 }
413 return Error() << "Invalid shutdown option";
414}
415
Suren Baghdasaryanc9c0bba2020-04-30 11:58:39 -0700416Result<void> ServiceParser::ParseTaskProfiles(std::vector<std::string>&& args) {
417 args.erase(args.begin());
Suren Baghdasaryan746ede92022-03-31 21:15:11 +0000418 if (service_->task_profiles_.empty()) {
419 service_->task_profiles_ = std::move(args);
420 } else {
421 // Some task profiles might have been added during writepid conversions
422 service_->task_profiles_.insert(service_->task_profiles_.end(),
423 std::make_move_iterator(args.begin()),
424 std::make_move_iterator(args.end()));
425 args.clear();
426 }
Suren Baghdasaryanc9c0bba2020-04-30 11:58:39 -0700427 return {};
428}
429
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700430Result<void> ServiceParser::ParseTimeoutPeriod(std::vector<std::string>&& args) {
431 int period;
432 if (!ParseInt(args[1], &period, 1)) {
433 return Error() << "timeout_period value must be an integer >= 1";
434 }
435 service_->timeout_period_ = std::chrono::seconds(period);
436 return {};
437}
438
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700439// name type perm [ uid gid context ]
440Result<void> ServiceParser::ParseSocket(std::vector<std::string>&& args) {
441 SocketDescriptor socket;
442 socket.name = std::move(args[1]);
443
444 auto types = Split(args[2], "+");
445 if (types[0] == "stream") {
446 socket.type = SOCK_STREAM;
447 } else if (types[0] == "dgram") {
448 socket.type = SOCK_DGRAM;
449 } else if (types[0] == "seqpacket") {
450 socket.type = SOCK_SEQPACKET;
451 } else {
452 return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket', got '" << types[0]
453 << "' instead.";
454 }
455
Adam Langleyecc14a52022-05-11 22:32:47 +0000456 for (size_t i = 1; i < types.size(); i++) {
457 if (types[i] == "passcred") {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700458 socket.passcred = true;
Adam Langleyecc14a52022-05-11 22:32:47 +0000459 } else if (types[i] == "listen") {
460 socket.listen = true;
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700461 } else {
Adam Langleyecc14a52022-05-11 22:32:47 +0000462 return Error() << "Unknown socket type decoration '" << types[i]
463 << "'. Known values are ['passcred', 'listen']";
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700464 }
465 }
466
467 errno = 0;
468 char* end = nullptr;
469 socket.perm = strtol(args[3].c_str(), &end, 8);
470 if (errno != 0) {
471 return ErrnoError() << "Unable to parse permissions '" << args[3] << "'";
472 }
473 if (end == args[3].c_str() || *end != '\0') {
474 errno = EINVAL;
475 return ErrnoError() << "Unable to parse permissions '" << args[3] << "'";
476 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700477
478 if (args.size() > 4) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700479 auto uid = DecodeUid(args[4]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900480 if (!uid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700481 return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
482 }
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700483 socket.uid = *uid;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700484 }
485
486 if (args.size() > 5) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700487 auto gid = DecodeUid(args[5]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900488 if (!gid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700489 return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
490 }
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700491 socket.gid = *gid;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700492 }
493
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700494 socket.context = args.size() > 6 ? args[6] : "";
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700495
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700496 auto old = std::find_if(service_->sockets_.begin(), service_->sockets_.end(),
497 [&socket](const auto& other) { return socket.name == other.name; });
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700498
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700499 if (old != service_->sockets_.end()) {
500 return Error() << "duplicate socket descriptor '" << socket.name << "'";
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700501 }
502
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700503 service_->sockets_.emplace_back(std::move(socket));
504
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700505 return {};
506}
507
Tom Cherryf74b7f52019-09-23 16:16:54 -0700508Result<void> ServiceParser::ParseStdioToKmsg(std::vector<std::string>&& args) {
509 if (service_->flags_ & SVC_CONSOLE) {
510 return Error() << "'stdio_to_kmsg' and 'console' are mutually exclusive";
511 }
512 service_->proc_attr_.stdio_to_kmsg = true;
513 return {};
514}
515
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700516// name type
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700517Result<void> ServiceParser::ParseFile(std::vector<std::string>&& args) {
518 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
519 return Error() << "file type must be 'r', 'w' or 'rw'";
520 }
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700521
522 FileDescriptor file;
523 file.type = args[2];
524
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700525 auto file_name = ExpandProps(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900526 if (!file_name.ok()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700527 return Error() << "Could not expand file path ': " << file_name.error();
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700528 }
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700529 file.name = *file_name;
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700530 if (file.name[0] != '/' || file.name.find("../") != std::string::npos) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700531 return Error() << "file name must not be relative";
532 }
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700533
534 auto old = std::find_if(service_->files_.begin(), service_->files_.end(),
535 [&file](const auto& other) { return other.name == file.name; });
536
537 if (old != service_->files_.end()) {
538 return Error() << "duplicate file descriptor '" << file.name << "'";
539 }
540
541 service_->files_.emplace_back(std::move(file));
542
543 return {};
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700544}
545
546Result<void> ServiceParser::ParseUser(std::vector<std::string>&& args) {
547 auto uid = DecodeUid(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900548 if (!uid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700549 return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
550 }
Steven Morelandf5d22ef2023-04-03 23:29:22 +0000551 service_->proc_attr_.parsed_uid = *uid;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700552 return {};
553}
554
Suren Baghdasaryan746ede92022-03-31 21:15:11 +0000555// Convert legacy paths used to migrate processes between cgroups using writepid command.
556// We can't get these paths from TaskProfiles because profile definitions are changing
557// when we migrate to cgroups v2 while these hardcoded paths stay the same.
558static std::optional<const std::string> ConvertTaskFileToProfile(const std::string& file) {
559 static const std::map<const std::string, const std::string> map = {
560 {"/dev/stune/top-app/tasks", "MaxPerformance"},
561 {"/dev/stune/foreground/tasks", "HighPerformance"},
562 {"/dev/cpuset/camera-daemon/tasks", "CameraServiceCapacity"},
563 {"/dev/cpuset/foreground/tasks", "ProcessCapacityHigh"},
564 {"/dev/cpuset/system-background/tasks", "ServiceCapacityLow"},
565 {"/dev/stune/nnapi-hal/tasks", "NNApiHALPerformance"},
566 {"/dev/blkio/background/tasks", "LowIoPriority"},
567 };
568 auto iter = map.find(file);
569 return iter == map.end() ? std::nullopt : std::make_optional<const std::string>(iter->second);
570}
571
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700572Result<void> ServiceParser::ParseWritepid(std::vector<std::string>&& args) {
573 args.erase(args.begin());
Suren Baghdasaryan746ede92022-03-31 21:15:11 +0000574 // Convert any cgroup writes into appropriate task_profiles
575 for (auto iter = args.begin(); iter != args.end();) {
576 auto task_profile = ConvertTaskFileToProfile(*iter);
577 if (task_profile) {
578 LOG(WARNING) << "'writepid " << *iter << "' is converted into 'task_profiles "
579 << task_profile.value() << "' for service " << service_->name();
580 service_->task_profiles_.push_back(task_profile.value());
581 iter = args.erase(iter);
582 } else {
583 ++iter;
584 }
585 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700586 service_->writepid_files_ = std::move(args);
587 return {};
588}
589
590Result<void> ServiceParser::ParseUpdatable(std::vector<std::string>&& args) {
591 service_->updatable_ = true;
592 return {};
593}
594
Tom Cherryd52a5b32019-07-22 16:05:36 -0700595const KeywordMap<ServiceParser::OptionParser>& ServiceParser::GetParserMap() const {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700596 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
597 // clang-format off
Tom Cherryd52a5b32019-07-22 16:05:36 -0700598 static const KeywordMap<ServiceParser::OptionParser> parser_map = {
Tom Cherry60971e62019-09-10 10:40:47 -0700599 {"capabilities", {0, kMax, &ServiceParser::ParseCapabilities}},
600 {"class", {1, kMax, &ServiceParser::ParseClass}},
601 {"console", {0, 1, &ServiceParser::ParseConsole}},
Woody Lin45215ae2019-12-26 22:22:28 +0800602 {"critical", {0, 2, &ServiceParser::ParseCritical}},
Tom Cherry60971e62019-09-10 10:40:47 -0700603 {"disabled", {0, 0, &ServiceParser::ParseDisabled}},
604 {"enter_namespace", {2, 2, &ServiceParser::ParseEnterNamespace}},
605 {"file", {2, 2, &ServiceParser::ParseFile}},
Daniel Rosenbergde766882022-12-01 15:44:31 -0800606 {"gentle_kill", {0, 0, &ServiceParser::ParseGentleKill}},
Tom Cherry60971e62019-09-10 10:40:47 -0700607 {"group", {1, NR_SVC_SUPP_GIDS + 1, &ServiceParser::ParseGroup}},
608 {"interface", {2, 2, &ServiceParser::ParseInterface}},
609 {"ioprio", {2, 2, &ServiceParser::ParseIoprio}},
610 {"keycodes", {1, kMax, &ServiceParser::ParseKeycodes}},
611 {"memcg.limit_in_bytes", {1, 1, &ServiceParser::ParseMemcgLimitInBytes}},
612 {"memcg.limit_percent", {1, 1, &ServiceParser::ParseMemcgLimitPercent}},
613 {"memcg.limit_property", {1, 1, &ServiceParser::ParseMemcgLimitProperty}},
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700614 {"memcg.soft_limit_in_bytes",
Tom Cherry60971e62019-09-10 10:40:47 -0700615 {1, 1, &ServiceParser::ParseMemcgSoftLimitInBytes}},
616 {"memcg.swappiness", {1, 1, &ServiceParser::ParseMemcgSwappiness}},
617 {"namespace", {1, 2, &ServiceParser::ParseNamespace}},
618 {"oneshot", {0, 0, &ServiceParser::ParseOneshot}},
619 {"onrestart", {1, kMax, &ServiceParser::ParseOnrestart}},
620 {"oom_score_adjust", {1, 1, &ServiceParser::ParseOomScoreAdjust}},
621 {"override", {0, 0, &ServiceParser::ParseOverride}},
622 {"priority", {1, 1, &ServiceParser::ParsePriority}},
623 {"reboot_on_failure", {1, 1, &ServiceParser::ParseRebootOnFailure}},
624 {"restart_period", {1, 1, &ServiceParser::ParseRestartPeriod}},
625 {"rlimit", {3, 3, &ServiceParser::ParseProcessRlimit}},
626 {"seclabel", {1, 1, &ServiceParser::ParseSeclabel}},
627 {"setenv", {2, 2, &ServiceParser::ParseSetenv}},
628 {"shutdown", {1, 1, &ServiceParser::ParseShutdown}},
629 {"sigstop", {0, 0, &ServiceParser::ParseSigstop}},
630 {"socket", {3, 6, &ServiceParser::ParseSocket}},
Tom Cherryf74b7f52019-09-23 16:16:54 -0700631 {"stdio_to_kmsg", {0, 0, &ServiceParser::ParseStdioToKmsg}},
Suren Baghdasaryanc9c0bba2020-04-30 11:58:39 -0700632 {"task_profiles", {1, kMax, &ServiceParser::ParseTaskProfiles}},
Tom Cherry60971e62019-09-10 10:40:47 -0700633 {"timeout_period", {1, 1, &ServiceParser::ParseTimeoutPeriod}},
634 {"updatable", {0, 0, &ServiceParser::ParseUpdatable}},
635 {"user", {1, 1, &ServiceParser::ParseUser}},
636 {"writepid", {1, kMax, &ServiceParser::ParseWritepid}},
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700637 };
638 // clang-format on
Tom Cherryd52a5b32019-07-22 16:05:36 -0700639 return parser_map;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700640}
641
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700642Result<void> ServiceParser::ParseSection(std::vector<std::string>&& args,
643 const std::string& filename, int line) {
644 if (args.size() < 3) {
645 return Error() << "services must have a name and a program";
646 }
647
648 const std::string& name = args[1];
649 if (!IsValidName(name)) {
650 return Error() << "invalid service name '" << name << "'";
651 }
652
653 filename_ = filename;
654
655 Subcontext* restart_action_subcontext = nullptr;
Tom Cherry14c24722019-09-18 13:47:19 -0700656 if (subcontext_ && subcontext_->PathMatchesSubcontext(filename)) {
657 restart_action_subcontext = subcontext_;
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700658 }
659
660 std::vector<std::string> str_args(args.begin() + 2, args.end());
661
662 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_P__) {
663 if (str_args[0] == "/sbin/watchdogd") {
664 str_args[0] = "/system/bin/watchdogd";
665 }
666 }
Yifan Hong8fb7f772019-10-16 14:22:12 -0700667 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
668 if (str_args[0] == "/charger") {
669 str_args[0] = "/system/bin/charger";
670 }
671 }
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700672
Deyao Rendf40ed12022-07-14 22:51:10 +0000673 service_ = std::make_unique<Service>(name, restart_action_subcontext, filename, str_args);
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700674 return {};
675}
676
677Result<void> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700678 if (!service_) {
679 return {};
680 }
681
Tom Cherryd52a5b32019-07-22 16:05:36 -0700682 auto parser = GetParserMap().Find(args);
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700683
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900684 if (!parser.ok()) return parser.error();
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700685
686 return std::invoke(*parser, this, std::move(args));
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700687}
688
689Result<void> ServiceParser::EndSection() {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700690 if (!service_) {
691 return {};
692 }
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700693
Steven Morelandf5d22ef2023-04-03 23:29:22 +0000694 if (service_->proc_attr_.parsed_uid == std::nullopt) {
Steven Moreland81a1b3e2024-05-20 22:31:11 +0000695 if (kAlwaysErrorUserRoot ||
696 android::base::GetIntProperty("ro.vendor.api_level", 0) > 202404) {
Steven Morelande5349192023-04-24 23:54:59 +0000697 return Error() << "No user specified for service '" << service_->name()
Steven Morelanda8a2c5a2024-05-20 21:56:19 +0000698 << "', so it would have been root.";
Steven Morelande5349192023-04-24 23:54:59 +0000699 } else {
700 LOG(WARNING) << "No user specified for service '" << service_->name()
Steven Morelanda8a2c5a2024-05-20 21:56:19 +0000701 << "', so it is root.";
Steven Morelande5349192023-04-24 23:54:59 +0000702 }
Steven Morelandf5d22ef2023-04-03 23:29:22 +0000703 }
704
Daniel Norman3f42a762019-07-09 11:00:53 -0700705 if (interface_inheritance_hierarchy_) {
Daniel Normand2533c32019-08-02 15:13:50 -0700706 if (const auto& check_hierarchy_result = CheckInterfaceInheritanceHierarchy(
707 service_->interfaces(), *interface_inheritance_hierarchy_);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900708 !check_hierarchy_result.ok()) {
Daniel Normand2533c32019-08-02 15:13:50 -0700709 return Error() << check_hierarchy_result.error();
Daniel Norman3f42a762019-07-09 11:00:53 -0700710 }
711 }
712
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100713 if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__) {
714 if ((service_->flags() & SVC_CRITICAL) != 0 && (service_->flags() & SVC_ONESHOT) != 0) {
715 return Error() << "service '" << service_->name()
716 << "' can't be both critical and oneshot";
717 }
718 }
719
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700720 Service* old_service = service_list_->FindService(service_->name());
721 if (old_service) {
722 if (!service_->is_override()) {
723 return Error() << "ignored duplicate definition of service '" << service_->name()
724 << "'";
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700725 }
726
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700727 if (StartsWith(filename_, "/apex/") && !old_service->is_updatable()) {
728 return Error() << "cannot update a non-updatable service '" << service_->name()
729 << "' with a config in APEX";
730 }
731
Daniel Normanf597fa52020-11-09 17:28:24 -0800732 std::string context = service_->subcontext() ? service_->subcontext()->context() : "";
733 std::string old_context =
734 old_service->subcontext() ? old_service->subcontext()->context() : "";
735 if (context != old_context) {
736 return Error() << "service '" << service_->name() << "' overrides another service "
737 << "across the treble boundary.";
738 }
739
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700740 service_list_->RemoveService(*old_service);
741 old_service = nullptr;
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700742 }
743
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700744 service_list_->AddService(std::move(service_));
745
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700746 return {};
747}
748
749bool ServiceParser::IsValidName(const std::string& name) const {
750 // Property names can be any length, but may only contain certain characters.
751 // Property values can contain any characters, but may only be a certain length.
752 // (The latter restriction is needed because `start` and `stop` work by writing
753 // the service name to the "ctl.start" and "ctl.stop" properties.)
754 return IsLegalPropertyName("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
755}
756
757} // namespace init
758} // namespace android