blob: d46e1f7544bd48fa24b7964a49a755a49a05f010 [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))) {
182 return Errorf("process priority value must be range {} - {}", ANDROID_PRIORITY_HIGHEST,
183 ANDROID_PRIORITY_LOWEST);
184 }
185 return {};
186}
187
188Result<void> ServiceParser::ParseInterface(std::vector<std::string>&& args) {
189 const std::string& interface_name = args[1];
190 const std::string& instance_name = args[2];
191
Jon Spivack16fb3f92019-07-26 13:14:42 -0700192 // AIDL services don't use fully qualified names and instead just use "interface aidl <name>"
193 if (interface_name != "aidl") {
194 FQName fq_name;
195 if (!FQName::parse(interface_name, &fq_name)) {
196 return Error() << "Invalid fully-qualified name for interface '" << interface_name
197 << "'";
198 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700199
Jon Spivack16fb3f92019-07-26 13:14:42 -0700200 if (!fq_name.isFullyQualified()) {
201 return Error() << "Interface name not fully-qualified '" << interface_name << "'";
202 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700203
Jon Spivack16fb3f92019-07-26 13:14:42 -0700204 if (fq_name.isValidValueName()) {
205 return Error() << "Interface name must not be a value name '" << interface_name << "'";
206 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700207 }
208
209 const std::string fullname = interface_name + "/" + instance_name;
210
211 for (const auto& svc : *service_list_) {
Alexander Koskoviche5f05202022-03-06 15:51:51 -0700212 if (svc->interfaces().count(fullname) > 0 && !service_->is_override()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700213 return Error() << "Interface '" << fullname << "' redefined in " << service_->name()
214 << " but is already defined by " << svc->name();
215 }
216 }
217
218 service_->interfaces_.insert(fullname);
219
220 return {};
221}
222
223Result<void> ServiceParser::ParseIoprio(std::vector<std::string>&& args) {
224 if (!ParseInt(args[2], &service_->proc_attr_.ioprio_pri, 0, 7)) {
225 return Error() << "priority value must be range 0 - 7";
226 }
227
228 if (args[1] == "rt") {
229 service_->proc_attr_.ioprio_class = IoSchedClass_RT;
230 } else if (args[1] == "be") {
231 service_->proc_attr_.ioprio_class = IoSchedClass_BE;
232 } else if (args[1] == "idle") {
233 service_->proc_attr_.ioprio_class = IoSchedClass_IDLE;
234 } else {
235 return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
236 }
237
238 return {};
239}
240
241Result<void> ServiceParser::ParseKeycodes(std::vector<std::string>&& args) {
242 auto it = args.begin() + 1;
243 if (args.size() == 2 && StartsWith(args[1], "$")) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700244 auto expanded = ExpandProps(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900245 if (!expanded.ok()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700246 return expanded.error();
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700247 }
248
249 // If the property is not set, it defaults to none, in which case there are no keycodes
250 // for this service.
Bernie Innocenti1cc76df2020-02-03 23:54:02 +0900251 if (*expanded == "none") {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700252 return {};
253 }
254
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700255 args = Split(*expanded, ",");
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700256 it = args.begin();
257 }
258
259 for (; it != args.end(); ++it) {
260 int code;
261 if (ParseInt(*it, &code, 0, KEY_MAX)) {
262 for (auto& key : service_->keycodes_) {
263 if (key == code) return Error() << "duplicate keycode: " << *it;
264 }
265 service_->keycodes_.insert(
266 std::upper_bound(service_->keycodes_.begin(), service_->keycodes_.end(), code),
267 code);
268 } else {
269 return Error() << "invalid keycode: " << *it;
270 }
271 }
272 return {};
273}
274
275Result<void> ServiceParser::ParseOneshot(std::vector<std::string>&& args) {
276 service_->flags_ |= SVC_ONESHOT;
277 return {};
278}
279
280Result<void> ServiceParser::ParseOnrestart(std::vector<std::string>&& args) {
281 args.erase(args.begin());
282 int line = service_->onrestart_.NumCommands() + 1;
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900283 if (auto result = service_->onrestart_.AddCommand(std::move(args), line); !result.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700284 return Error() << "cannot add Onrestart command: " << result.error();
285 }
286 return {};
287}
288
289Result<void> ServiceParser::ParseNamespace(std::vector<std::string>&& args) {
290 for (size_t i = 1; i < args.size(); i++) {
291 if (args[i] == "pid") {
292 service_->namespaces_.flags |= CLONE_NEWPID;
293 // PID namespaces require mount namespaces.
294 service_->namespaces_.flags |= CLONE_NEWNS;
295 } else if (args[i] == "mnt") {
296 service_->namespaces_.flags |= CLONE_NEWNS;
297 } else {
298 return Error() << "namespace must be 'pid' or 'mnt'";
299 }
300 }
301 return {};
302}
303
304Result<void> ServiceParser::ParseOomScoreAdjust(std::vector<std::string>&& args) {
Suren Baghdasaryanc29c2ba2019-10-22 17:18:42 -0700305 if (!ParseInt(args[1], &service_->oom_score_adjust_, MIN_OOM_SCORE_ADJUST,
306 MAX_OOM_SCORE_ADJUST)) {
307 return Error() << "oom_score_adjust value must be in range " << MIN_OOM_SCORE_ADJUST
308 << " - +" << MAX_OOM_SCORE_ADJUST;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700309 }
310 return {};
311}
312
313Result<void> ServiceParser::ParseOverride(std::vector<std::string>&& args) {
314 service_->override_ = true;
315 return {};
316}
317
318Result<void> ServiceParser::ParseMemcgSwappiness(std::vector<std::string>&& args) {
319 if (!ParseInt(args[1], &service_->swappiness_, 0)) {
320 return Error() << "swappiness value must be equal or greater than 0";
321 }
322 return {};
323}
324
325Result<void> ServiceParser::ParseMemcgLimitInBytes(std::vector<std::string>&& args) {
326 if (!ParseInt(args[1], &service_->limit_in_bytes_, 0)) {
327 return Error() << "limit_in_bytes value must be equal or greater than 0";
328 }
329 return {};
330}
331
332Result<void> ServiceParser::ParseMemcgLimitPercent(std::vector<std::string>&& args) {
333 if (!ParseInt(args[1], &service_->limit_percent_, 0)) {
334 return Error() << "limit_percent value must be equal or greater than 0";
335 }
336 return {};
337}
338
339Result<void> ServiceParser::ParseMemcgLimitProperty(std::vector<std::string>&& args) {
340 service_->limit_property_ = std::move(args[1]);
341 return {};
342}
343
344Result<void> ServiceParser::ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args) {
345 if (!ParseInt(args[1], &service_->soft_limit_in_bytes_, 0)) {
346 return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
347 }
348 return {};
349}
350
351Result<void> ServiceParser::ParseProcessRlimit(std::vector<std::string>&& args) {
352 auto rlimit = ParseRlimit(args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900353 if (!rlimit.ok()) return rlimit.error();
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700354
355 service_->proc_attr_.rlimits.emplace_back(*rlimit);
356 return {};
357}
358
Tom Cherry60971e62019-09-10 10:40:47 -0700359Result<void> ServiceParser::ParseRebootOnFailure(std::vector<std::string>&& args) {
360 if (service_->on_failure_reboot_target_) {
361 return Error() << "Only one reboot_on_failure command may be specified";
362 }
363 if (!StartsWith(args[1], "shutdown") && !StartsWith(args[1], "reboot")) {
364 return Error()
365 << "reboot_on_failure commands must begin with either 'shutdown' or 'reboot'";
366 }
367 service_->on_failure_reboot_target_ = std::move(args[1]);
368 return {};
369}
370
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700371Result<void> ServiceParser::ParseRestartPeriod(std::vector<std::string>&& args) {
372 int period;
373 if (!ParseInt(args[1], &period, 5)) {
374 return Error() << "restart_period value must be an integer >= 5";
375 }
376 service_->restart_period_ = std::chrono::seconds(period);
377 return {};
378}
379
380Result<void> ServiceParser::ParseSeclabel(std::vector<std::string>&& args) {
381 service_->seclabel_ = std::move(args[1]);
382 return {};
383}
384
385Result<void> ServiceParser::ParseSigstop(std::vector<std::string>&& args) {
386 service_->sigstop_ = true;
387 return {};
388}
389
390Result<void> ServiceParser::ParseSetenv(std::vector<std::string>&& args) {
391 service_->environment_vars_.emplace_back(std::move(args[1]), std::move(args[2]));
392 return {};
393}
394
395Result<void> ServiceParser::ParseShutdown(std::vector<std::string>&& args) {
396 if (args[1] == "critical") {
397 service_->flags_ |= SVC_SHUTDOWN_CRITICAL;
398 return {};
399 }
400 return Error() << "Invalid shutdown option";
401}
402
Suren Baghdasaryanc9c0bba2020-04-30 11:58:39 -0700403Result<void> ServiceParser::ParseTaskProfiles(std::vector<std::string>&& args) {
404 args.erase(args.begin());
Suren Baghdasaryan746ede92022-03-31 21:15:11 +0000405 if (service_->task_profiles_.empty()) {
406 service_->task_profiles_ = std::move(args);
407 } else {
408 // Some task profiles might have been added during writepid conversions
409 service_->task_profiles_.insert(service_->task_profiles_.end(),
410 std::make_move_iterator(args.begin()),
411 std::make_move_iterator(args.end()));
412 args.clear();
413 }
Suren Baghdasaryanc9c0bba2020-04-30 11:58:39 -0700414 return {};
415}
416
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700417Result<void> ServiceParser::ParseTimeoutPeriod(std::vector<std::string>&& args) {
418 int period;
419 if (!ParseInt(args[1], &period, 1)) {
420 return Error() << "timeout_period value must be an integer >= 1";
421 }
422 service_->timeout_period_ = std::chrono::seconds(period);
423 return {};
424}
425
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700426// name type perm [ uid gid context ]
427Result<void> ServiceParser::ParseSocket(std::vector<std::string>&& args) {
428 SocketDescriptor socket;
429 socket.name = std::move(args[1]);
430
431 auto types = Split(args[2], "+");
432 if (types[0] == "stream") {
433 socket.type = SOCK_STREAM;
434 } else if (types[0] == "dgram") {
435 socket.type = SOCK_DGRAM;
436 } else if (types[0] == "seqpacket") {
437 socket.type = SOCK_SEQPACKET;
438 } else {
439 return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket', got '" << types[0]
440 << "' instead.";
441 }
442
Adam Langleyecc14a52022-05-11 22:32:47 +0000443 for (size_t i = 1; i < types.size(); i++) {
444 if (types[i] == "passcred") {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700445 socket.passcred = true;
Adam Langleyecc14a52022-05-11 22:32:47 +0000446 } else if (types[i] == "listen") {
447 socket.listen = true;
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700448 } else {
Adam Langleyecc14a52022-05-11 22:32:47 +0000449 return Error() << "Unknown socket type decoration '" << types[i]
450 << "'. Known values are ['passcred', 'listen']";
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700451 }
452 }
453
454 errno = 0;
455 char* end = nullptr;
456 socket.perm = strtol(args[3].c_str(), &end, 8);
457 if (errno != 0) {
458 return ErrnoError() << "Unable to parse permissions '" << args[3] << "'";
459 }
460 if (end == args[3].c_str() || *end != '\0') {
461 errno = EINVAL;
462 return ErrnoError() << "Unable to parse permissions '" << args[3] << "'";
463 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700464
465 if (args.size() > 4) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700466 auto uid = DecodeUid(args[4]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900467 if (!uid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700468 return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
469 }
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700470 socket.uid = *uid;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700471 }
472
473 if (args.size() > 5) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700474 auto gid = DecodeUid(args[5]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900475 if (!gid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700476 return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
477 }
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700478 socket.gid = *gid;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700479 }
480
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700481 socket.context = args.size() > 6 ? args[6] : "";
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700482
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700483 auto old = std::find_if(service_->sockets_.begin(), service_->sockets_.end(),
484 [&socket](const auto& other) { return socket.name == other.name; });
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700485
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700486 if (old != service_->sockets_.end()) {
487 return Error() << "duplicate socket descriptor '" << socket.name << "'";
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700488 }
489
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700490 service_->sockets_.emplace_back(std::move(socket));
491
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700492 return {};
493}
494
Tom Cherryf74b7f52019-09-23 16:16:54 -0700495Result<void> ServiceParser::ParseStdioToKmsg(std::vector<std::string>&& args) {
496 if (service_->flags_ & SVC_CONSOLE) {
497 return Error() << "'stdio_to_kmsg' and 'console' are mutually exclusive";
498 }
499 service_->proc_attr_.stdio_to_kmsg = true;
500 return {};
501}
502
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700503// name type
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700504Result<void> ServiceParser::ParseFile(std::vector<std::string>&& args) {
505 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
506 return Error() << "file type must be 'r', 'w' or 'rw'";
507 }
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700508
509 FileDescriptor file;
510 file.type = args[2];
511
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700512 auto file_name = ExpandProps(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900513 if (!file_name.ok()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700514 return Error() << "Could not expand file path ': " << file_name.error();
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700515 }
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700516 file.name = *file_name;
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700517 if (file.name[0] != '/' || file.name.find("../") != std::string::npos) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700518 return Error() << "file name must not be relative";
519 }
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700520
521 auto old = std::find_if(service_->files_.begin(), service_->files_.end(),
522 [&file](const auto& other) { return other.name == file.name; });
523
524 if (old != service_->files_.end()) {
525 return Error() << "duplicate file descriptor '" << file.name << "'";
526 }
527
528 service_->files_.emplace_back(std::move(file));
529
530 return {};
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700531}
532
533Result<void> ServiceParser::ParseUser(std::vector<std::string>&& args) {
534 auto uid = DecodeUid(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900535 if (!uid.ok()) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700536 return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
537 }
Steven Morelandf5d22ef2023-04-03 23:29:22 +0000538 service_->proc_attr_.parsed_uid = *uid;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700539 return {};
540}
541
Suren Baghdasaryan746ede92022-03-31 21:15:11 +0000542// Convert legacy paths used to migrate processes between cgroups using writepid command.
543// We can't get these paths from TaskProfiles because profile definitions are changing
544// when we migrate to cgroups v2 while these hardcoded paths stay the same.
545static std::optional<const std::string> ConvertTaskFileToProfile(const std::string& file) {
546 static const std::map<const std::string, const std::string> map = {
547 {"/dev/stune/top-app/tasks", "MaxPerformance"},
548 {"/dev/stune/foreground/tasks", "HighPerformance"},
549 {"/dev/cpuset/camera-daemon/tasks", "CameraServiceCapacity"},
550 {"/dev/cpuset/foreground/tasks", "ProcessCapacityHigh"},
551 {"/dev/cpuset/system-background/tasks", "ServiceCapacityLow"},
552 {"/dev/stune/nnapi-hal/tasks", "NNApiHALPerformance"},
553 {"/dev/blkio/background/tasks", "LowIoPriority"},
554 };
555 auto iter = map.find(file);
556 return iter == map.end() ? std::nullopt : std::make_optional<const std::string>(iter->second);
557}
558
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700559Result<void> ServiceParser::ParseWritepid(std::vector<std::string>&& args) {
560 args.erase(args.begin());
Suren Baghdasaryan746ede92022-03-31 21:15:11 +0000561 // Convert any cgroup writes into appropriate task_profiles
562 for (auto iter = args.begin(); iter != args.end();) {
563 auto task_profile = ConvertTaskFileToProfile(*iter);
564 if (task_profile) {
565 LOG(WARNING) << "'writepid " << *iter << "' is converted into 'task_profiles "
566 << task_profile.value() << "' for service " << service_->name();
567 service_->task_profiles_.push_back(task_profile.value());
568 iter = args.erase(iter);
569 } else {
570 ++iter;
571 }
572 }
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700573 service_->writepid_files_ = std::move(args);
574 return {};
575}
576
577Result<void> ServiceParser::ParseUpdatable(std::vector<std::string>&& args) {
578 service_->updatable_ = true;
579 return {};
580}
581
Tom Cherryd52a5b32019-07-22 16:05:36 -0700582const KeywordMap<ServiceParser::OptionParser>& ServiceParser::GetParserMap() const {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700583 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
584 // clang-format off
Tom Cherryd52a5b32019-07-22 16:05:36 -0700585 static const KeywordMap<ServiceParser::OptionParser> parser_map = {
Tom Cherry60971e62019-09-10 10:40:47 -0700586 {"capabilities", {0, kMax, &ServiceParser::ParseCapabilities}},
587 {"class", {1, kMax, &ServiceParser::ParseClass}},
588 {"console", {0, 1, &ServiceParser::ParseConsole}},
Woody Lin45215ae2019-12-26 22:22:28 +0800589 {"critical", {0, 2, &ServiceParser::ParseCritical}},
Tom Cherry60971e62019-09-10 10:40:47 -0700590 {"disabled", {0, 0, &ServiceParser::ParseDisabled}},
591 {"enter_namespace", {2, 2, &ServiceParser::ParseEnterNamespace}},
592 {"file", {2, 2, &ServiceParser::ParseFile}},
Daniel Rosenbergde766882022-12-01 15:44:31 -0800593 {"gentle_kill", {0, 0, &ServiceParser::ParseGentleKill}},
Tom Cherry60971e62019-09-10 10:40:47 -0700594 {"group", {1, NR_SVC_SUPP_GIDS + 1, &ServiceParser::ParseGroup}},
595 {"interface", {2, 2, &ServiceParser::ParseInterface}},
596 {"ioprio", {2, 2, &ServiceParser::ParseIoprio}},
597 {"keycodes", {1, kMax, &ServiceParser::ParseKeycodes}},
598 {"memcg.limit_in_bytes", {1, 1, &ServiceParser::ParseMemcgLimitInBytes}},
599 {"memcg.limit_percent", {1, 1, &ServiceParser::ParseMemcgLimitPercent}},
600 {"memcg.limit_property", {1, 1, &ServiceParser::ParseMemcgLimitProperty}},
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700601 {"memcg.soft_limit_in_bytes",
Tom Cherry60971e62019-09-10 10:40:47 -0700602 {1, 1, &ServiceParser::ParseMemcgSoftLimitInBytes}},
603 {"memcg.swappiness", {1, 1, &ServiceParser::ParseMemcgSwappiness}},
604 {"namespace", {1, 2, &ServiceParser::ParseNamespace}},
605 {"oneshot", {0, 0, &ServiceParser::ParseOneshot}},
606 {"onrestart", {1, kMax, &ServiceParser::ParseOnrestart}},
607 {"oom_score_adjust", {1, 1, &ServiceParser::ParseOomScoreAdjust}},
608 {"override", {0, 0, &ServiceParser::ParseOverride}},
609 {"priority", {1, 1, &ServiceParser::ParsePriority}},
610 {"reboot_on_failure", {1, 1, &ServiceParser::ParseRebootOnFailure}},
611 {"restart_period", {1, 1, &ServiceParser::ParseRestartPeriod}},
612 {"rlimit", {3, 3, &ServiceParser::ParseProcessRlimit}},
613 {"seclabel", {1, 1, &ServiceParser::ParseSeclabel}},
614 {"setenv", {2, 2, &ServiceParser::ParseSetenv}},
615 {"shutdown", {1, 1, &ServiceParser::ParseShutdown}},
616 {"sigstop", {0, 0, &ServiceParser::ParseSigstop}},
617 {"socket", {3, 6, &ServiceParser::ParseSocket}},
Tom Cherryf74b7f52019-09-23 16:16:54 -0700618 {"stdio_to_kmsg", {0, 0, &ServiceParser::ParseStdioToKmsg}},
Suren Baghdasaryanc9c0bba2020-04-30 11:58:39 -0700619 {"task_profiles", {1, kMax, &ServiceParser::ParseTaskProfiles}},
Tom Cherry60971e62019-09-10 10:40:47 -0700620 {"timeout_period", {1, 1, &ServiceParser::ParseTimeoutPeriod}},
621 {"updatable", {0, 0, &ServiceParser::ParseUpdatable}},
622 {"user", {1, 1, &ServiceParser::ParseUser}},
623 {"writepid", {1, kMax, &ServiceParser::ParseWritepid}},
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700624 };
625 // clang-format on
Tom Cherryd52a5b32019-07-22 16:05:36 -0700626 return parser_map;
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700627}
628
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700629Result<void> ServiceParser::ParseSection(std::vector<std::string>&& args,
630 const std::string& filename, int line) {
631 if (args.size() < 3) {
632 return Error() << "services must have a name and a program";
633 }
634
635 const std::string& name = args[1];
636 if (!IsValidName(name)) {
637 return Error() << "invalid service name '" << name << "'";
638 }
639
640 filename_ = filename;
641
642 Subcontext* restart_action_subcontext = nullptr;
Tom Cherry14c24722019-09-18 13:47:19 -0700643 if (subcontext_ && subcontext_->PathMatchesSubcontext(filename)) {
644 restart_action_subcontext = subcontext_;
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700645 }
646
647 std::vector<std::string> str_args(args.begin() + 2, args.end());
648
649 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_P__) {
650 if (str_args[0] == "/sbin/watchdogd") {
651 str_args[0] = "/system/bin/watchdogd";
652 }
653 }
Yifan Hong8fb7f772019-10-16 14:22:12 -0700654 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
655 if (str_args[0] == "/charger") {
656 str_args[0] = "/system/bin/charger";
657 }
658 }
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700659
Deyao Rendf40ed12022-07-14 22:51:10 +0000660 service_ = std::make_unique<Service>(name, restart_action_subcontext, filename, str_args);
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700661 return {};
662}
663
664Result<void> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700665 if (!service_) {
666 return {};
667 }
668
Tom Cherryd52a5b32019-07-22 16:05:36 -0700669 auto parser = GetParserMap().Find(args);
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700670
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900671 if (!parser.ok()) return parser.error();
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700672
673 return std::invoke(*parser, this, std::move(args));
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700674}
675
676Result<void> ServiceParser::EndSection() {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700677 if (!service_) {
678 return {};
679 }
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700680
Steven Morelandf5d22ef2023-04-03 23:29:22 +0000681 if (service_->proc_attr_.parsed_uid == std::nullopt) {
Steven Morelande5349192023-04-24 23:54:59 +0000682 if (android::base::GetIntProperty("ro.vendor.api_level", 0) > __ANDROID_API_U__) {
683 return Error() << "No user specified for service '" << service_->name()
684 << "'. Defaults to root.";
685 } else {
686 LOG(WARNING) << "No user specified for service '" << service_->name()
687 << "'. Defaults to root.";
688 }
Steven Morelandf5d22ef2023-04-03 23:29:22 +0000689 }
690
Daniel Norman3f42a762019-07-09 11:00:53 -0700691 if (interface_inheritance_hierarchy_) {
Daniel Normand2533c32019-08-02 15:13:50 -0700692 if (const auto& check_hierarchy_result = CheckInterfaceInheritanceHierarchy(
693 service_->interfaces(), *interface_inheritance_hierarchy_);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900694 !check_hierarchy_result.ok()) {
Daniel Normand2533c32019-08-02 15:13:50 -0700695 return Error() << check_hierarchy_result.error();
Daniel Norman3f42a762019-07-09 11:00:53 -0700696 }
697 }
698
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100699 if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__) {
700 if ((service_->flags() & SVC_CRITICAL) != 0 && (service_->flags() & SVC_ONESHOT) != 0) {
701 return Error() << "service '" << service_->name()
702 << "' can't be both critical and oneshot";
703 }
704 }
705
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700706 Service* old_service = service_list_->FindService(service_->name());
707 if (old_service) {
708 if (!service_->is_override()) {
709 return Error() << "ignored duplicate definition of service '" << service_->name()
710 << "'";
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700711 }
712
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700713 if (StartsWith(filename_, "/apex/") && !old_service->is_updatable()) {
714 return Error() << "cannot update a non-updatable service '" << service_->name()
715 << "' with a config in APEX";
716 }
717
Daniel Normanf597fa52020-11-09 17:28:24 -0800718 std::string context = service_->subcontext() ? service_->subcontext()->context() : "";
719 std::string old_context =
720 old_service->subcontext() ? old_service->subcontext()->context() : "";
721 if (context != old_context) {
722 return Error() << "service '" << service_->name() << "' overrides another service "
723 << "across the treble boundary.";
724 }
725
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700726 service_list_->RemoveService(*old_service);
727 old_service = nullptr;
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700728 }
729
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700730 service_list_->AddService(std::move(service_));
731
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700732 return {};
733}
734
735bool ServiceParser::IsValidName(const std::string& name) const {
736 // Property names can be any length, but may only contain certain characters.
737 // Property values can contain any characters, but may only be a certain length.
738 // (The latter restriction is needed because `start` and `stop` work by writing
739 // the service name to the "ctl.start" and "ctl.stop" properties.)
740 return IsLegalPropertyName("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
741}
742
743} // namespace init
744} // namespace android