blob: 88ce364c49b76b03827bd7abe395f2cadd2695b2 [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 Cherry2aeb1ad2019-06-26 10:46:20 -070020
Daniel Norman3f42a762019-07-09 11:00:53 -070021#include <algorithm>
22#include <sstream>
23
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070024#include <android-base/logging.h>
25#include <android-base/parseint.h>
26#include <android-base/strings.h>
27#include <hidl-util/FQName.h>
28#include <system/thread_defs.h>
29
30#include "rlimit_parser.h"
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070031#include "util.h"
32
33#if defined(__ANDROID__)
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070034#include <android/api-level.h>
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070035#include <sys/system_properties.h>
36
37#include "selinux.h"
38#else
39#include "host_init_stubs.h"
40#endif
41
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070042using android::base::ParseInt;
43using android::base::Split;
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070044using android::base::StartsWith;
45
46namespace android {
47namespace init {
48
Tom Cherryb1ffb1d2019-06-26 11:22:52 -070049Result<void> ServiceParser::ParseCapabilities(std::vector<std::string>&& args) {
50 service_->capabilities_ = 0;
51
52 if (!CapAmbientSupported()) {
53 return Error()
54 << "capabilities requested but the kernel does not support ambient capabilities";
55 }
56
57 unsigned int last_valid_cap = GetLastValidCap();
58 if (last_valid_cap >= service_->capabilities_->size()) {
59 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
60 }
61
62 for (size_t i = 1; i < args.size(); i++) {
63 const std::string& arg = args[i];
64 int res = LookupCap(arg);
65 if (res < 0) {
66 return Errorf("invalid capability '{}'", arg);
67 }
68 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
69 if (cap > last_valid_cap) {
70 return Errorf("capability '{}' not supported by the kernel", arg);
71 }
72 (*service_->capabilities_)[cap] = true;
73 }
74 return {};
75}
76
77Result<void> ServiceParser::ParseClass(std::vector<std::string>&& args) {
78 service_->classnames_ = std::set<std::string>(args.begin() + 1, args.end());
79 return {};
80}
81
82Result<void> ServiceParser::ParseConsole(std::vector<std::string>&& args) {
83 service_->flags_ |= SVC_CONSOLE;
84 service_->proc_attr_.console = args.size() > 1 ? "/dev/" + args[1] : "";
85 return {};
86}
87
88Result<void> ServiceParser::ParseCritical(std::vector<std::string>&& args) {
89 service_->flags_ |= SVC_CRITICAL;
90 return {};
91}
92
93Result<void> ServiceParser::ParseDisabled(std::vector<std::string>&& args) {
94 service_->flags_ |= SVC_DISABLED;
95 service_->flags_ |= SVC_RC_DISABLED;
96 return {};
97}
98
99Result<void> ServiceParser::ParseEnterNamespace(std::vector<std::string>&& args) {
100 if (args[1] != "net") {
101 return Error() << "Init only supports entering network namespaces";
102 }
103 if (!service_->namespaces_.namespaces_to_enter.empty()) {
104 return Error() << "Only one network namespace may be entered";
105 }
106 // Network namespaces require that /sys is remounted, otherwise the old adapters will still be
107 // present. Therefore, they also require mount namespaces.
108 service_->namespaces_.flags |= CLONE_NEWNS;
109 service_->namespaces_.namespaces_to_enter.emplace_back(CLONE_NEWNET, std::move(args[2]));
110 return {};
111}
112
113Result<void> ServiceParser::ParseGroup(std::vector<std::string>&& args) {
114 auto gid = DecodeUid(args[1]);
115 if (!gid) {
116 return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
117 }
118 service_->proc_attr_.gid = *gid;
119
120 for (std::size_t n = 2; n < args.size(); n++) {
121 gid = DecodeUid(args[n]);
122 if (!gid) {
123 return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
124 }
125 service_->proc_attr_.supp_gids.emplace_back(*gid);
126 }
127 return {};
128}
129
130Result<void> ServiceParser::ParsePriority(std::vector<std::string>&& args) {
131 service_->proc_attr_.priority = 0;
132 if (!ParseInt(args[1], &service_->proc_attr_.priority,
133 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
134 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
135 return Errorf("process priority value must be range {} - {}", ANDROID_PRIORITY_HIGHEST,
136 ANDROID_PRIORITY_LOWEST);
137 }
138 return {};
139}
140
141Result<void> ServiceParser::ParseInterface(std::vector<std::string>&& args) {
142 const std::string& interface_name = args[1];
143 const std::string& instance_name = args[2];
144
145 FQName fq_name;
146 if (!FQName::parse(interface_name, &fq_name)) {
147 return Error() << "Invalid fully-qualified name for interface '" << interface_name << "'";
148 }
149
150 if (!fq_name.isFullyQualified()) {
151 return Error() << "Interface name not fully-qualified '" << interface_name << "'";
152 }
153
154 if (fq_name.isValidValueName()) {
155 return Error() << "Interface name must not be a value name '" << interface_name << "'";
156 }
157
158 const std::string fullname = interface_name + "/" + instance_name;
159
160 for (const auto& svc : *service_list_) {
161 if (svc->interfaces().count(fullname) > 0) {
162 return Error() << "Interface '" << fullname << "' redefined in " << service_->name()
163 << " but is already defined by " << svc->name();
164 }
165 }
166
167 service_->interfaces_.insert(fullname);
168
169 return {};
170}
171
172Result<void> ServiceParser::ParseIoprio(std::vector<std::string>&& args) {
173 if (!ParseInt(args[2], &service_->proc_attr_.ioprio_pri, 0, 7)) {
174 return Error() << "priority value must be range 0 - 7";
175 }
176
177 if (args[1] == "rt") {
178 service_->proc_attr_.ioprio_class = IoSchedClass_RT;
179 } else if (args[1] == "be") {
180 service_->proc_attr_.ioprio_class = IoSchedClass_BE;
181 } else if (args[1] == "idle") {
182 service_->proc_attr_.ioprio_class = IoSchedClass_IDLE;
183 } else {
184 return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
185 }
186
187 return {};
188}
189
190Result<void> ServiceParser::ParseKeycodes(std::vector<std::string>&& args) {
191 auto it = args.begin() + 1;
192 if (args.size() == 2 && StartsWith(args[1], "$")) {
193 std::string expanded;
194 if (!expand_props(args[1], &expanded)) {
195 return Error() << "Could not expand property '" << args[1] << "'";
196 }
197
198 // If the property is not set, it defaults to none, in which case there are no keycodes
199 // for this service.
200 if (expanded == "none") {
201 return {};
202 }
203
204 args = Split(expanded, ",");
205 it = args.begin();
206 }
207
208 for (; it != args.end(); ++it) {
209 int code;
210 if (ParseInt(*it, &code, 0, KEY_MAX)) {
211 for (auto& key : service_->keycodes_) {
212 if (key == code) return Error() << "duplicate keycode: " << *it;
213 }
214 service_->keycodes_.insert(
215 std::upper_bound(service_->keycodes_.begin(), service_->keycodes_.end(), code),
216 code);
217 } else {
218 return Error() << "invalid keycode: " << *it;
219 }
220 }
221 return {};
222}
223
224Result<void> ServiceParser::ParseOneshot(std::vector<std::string>&& args) {
225 service_->flags_ |= SVC_ONESHOT;
226 return {};
227}
228
229Result<void> ServiceParser::ParseOnrestart(std::vector<std::string>&& args) {
230 args.erase(args.begin());
231 int line = service_->onrestart_.NumCommands() + 1;
232 if (auto result = service_->onrestart_.AddCommand(std::move(args), line); !result) {
233 return Error() << "cannot add Onrestart command: " << result.error();
234 }
235 return {};
236}
237
238Result<void> ServiceParser::ParseNamespace(std::vector<std::string>&& args) {
239 for (size_t i = 1; i < args.size(); i++) {
240 if (args[i] == "pid") {
241 service_->namespaces_.flags |= CLONE_NEWPID;
242 // PID namespaces require mount namespaces.
243 service_->namespaces_.flags |= CLONE_NEWNS;
244 } else if (args[i] == "mnt") {
245 service_->namespaces_.flags |= CLONE_NEWNS;
246 } else {
247 return Error() << "namespace must be 'pid' or 'mnt'";
248 }
249 }
250 return {};
251}
252
253Result<void> ServiceParser::ParseOomScoreAdjust(std::vector<std::string>&& args) {
254 if (!ParseInt(args[1], &service_->oom_score_adjust_, -1000, 1000)) {
255 return Error() << "oom_score_adjust value must be in range -1000 - +1000";
256 }
257 return {};
258}
259
260Result<void> ServiceParser::ParseOverride(std::vector<std::string>&& args) {
261 service_->override_ = true;
262 return {};
263}
264
265Result<void> ServiceParser::ParseMemcgSwappiness(std::vector<std::string>&& args) {
266 if (!ParseInt(args[1], &service_->swappiness_, 0)) {
267 return Error() << "swappiness value must be equal or greater than 0";
268 }
269 return {};
270}
271
272Result<void> ServiceParser::ParseMemcgLimitInBytes(std::vector<std::string>&& args) {
273 if (!ParseInt(args[1], &service_->limit_in_bytes_, 0)) {
274 return Error() << "limit_in_bytes value must be equal or greater than 0";
275 }
276 return {};
277}
278
279Result<void> ServiceParser::ParseMemcgLimitPercent(std::vector<std::string>&& args) {
280 if (!ParseInt(args[1], &service_->limit_percent_, 0)) {
281 return Error() << "limit_percent value must be equal or greater than 0";
282 }
283 return {};
284}
285
286Result<void> ServiceParser::ParseMemcgLimitProperty(std::vector<std::string>&& args) {
287 service_->limit_property_ = std::move(args[1]);
288 return {};
289}
290
291Result<void> ServiceParser::ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args) {
292 if (!ParseInt(args[1], &service_->soft_limit_in_bytes_, 0)) {
293 return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
294 }
295 return {};
296}
297
298Result<void> ServiceParser::ParseProcessRlimit(std::vector<std::string>&& args) {
299 auto rlimit = ParseRlimit(args);
300 if (!rlimit) return rlimit.error();
301
302 service_->proc_attr_.rlimits.emplace_back(*rlimit);
303 return {};
304}
305
306Result<void> ServiceParser::ParseRestartPeriod(std::vector<std::string>&& args) {
307 int period;
308 if (!ParseInt(args[1], &period, 5)) {
309 return Error() << "restart_period value must be an integer >= 5";
310 }
311 service_->restart_period_ = std::chrono::seconds(period);
312 return {};
313}
314
315Result<void> ServiceParser::ParseSeclabel(std::vector<std::string>&& args) {
316 service_->seclabel_ = std::move(args[1]);
317 return {};
318}
319
320Result<void> ServiceParser::ParseSigstop(std::vector<std::string>&& args) {
321 service_->sigstop_ = true;
322 return {};
323}
324
325Result<void> ServiceParser::ParseSetenv(std::vector<std::string>&& args) {
326 service_->environment_vars_.emplace_back(std::move(args[1]), std::move(args[2]));
327 return {};
328}
329
330Result<void> ServiceParser::ParseShutdown(std::vector<std::string>&& args) {
331 if (args[1] == "critical") {
332 service_->flags_ |= SVC_SHUTDOWN_CRITICAL;
333 return {};
334 }
335 return Error() << "Invalid shutdown option";
336}
337
338Result<void> ServiceParser::ParseTimeoutPeriod(std::vector<std::string>&& args) {
339 int period;
340 if (!ParseInt(args[1], &period, 1)) {
341 return Error() << "timeout_period value must be an integer >= 1";
342 }
343 service_->timeout_period_ = std::chrono::seconds(period);
344 return {};
345}
346
347template <typename T>
348Result<void> ServiceParser::AddDescriptor(std::vector<std::string>&& args) {
349 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
350 Result<uid_t> uid = 0;
351 Result<gid_t> gid = 0;
352 std::string context = args.size() > 6 ? args[6] : "";
353
354 if (args.size() > 4) {
355 uid = DecodeUid(args[4]);
356 if (!uid) {
357 return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
358 }
359 }
360
361 if (args.size() > 5) {
362 gid = DecodeUid(args[5]);
363 if (!gid) {
364 return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
365 }
366 }
367
368 auto descriptor = std::make_unique<T>(args[1], args[2], *uid, *gid, perm, context);
369
370 auto old = std::find_if(
371 service_->descriptors_.begin(), service_->descriptors_.end(),
372 [&descriptor](const auto& other) { return descriptor.get() == other.get(); });
373
374 if (old != service_->descriptors_.end()) {
375 return Error() << "duplicate descriptor " << args[1] << " " << args[2];
376 }
377
378 service_->descriptors_.emplace_back(std::move(descriptor));
379 return {};
380}
381
382// name type perm [ uid gid context ]
383Result<void> ServiceParser::ParseSocket(std::vector<std::string>&& args) {
384 if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") &&
385 !StartsWith(args[2], "seqpacket")) {
386 return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket'";
387 }
388 return AddDescriptor<SocketInfo>(std::move(args));
389}
390
391// name type perm [ uid gid context ]
392Result<void> ServiceParser::ParseFile(std::vector<std::string>&& args) {
393 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
394 return Error() << "file type must be 'r', 'w' or 'rw'";
395 }
396 std::string expanded;
397 if (!expand_props(args[1], &expanded)) {
398 return Error() << "Could not expand property in file path '" << args[1] << "'";
399 }
400 args[1] = std::move(expanded);
401 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
402 return Error() << "file name must not be relative";
403 }
404 return AddDescriptor<FileInfo>(std::move(args));
405}
406
407Result<void> ServiceParser::ParseUser(std::vector<std::string>&& args) {
408 auto uid = DecodeUid(args[1]);
409 if (!uid) {
410 return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
411 }
412 service_->proc_attr_.uid = *uid;
413 return {};
414}
415
416Result<void> ServiceParser::ParseWritepid(std::vector<std::string>&& args) {
417 args.erase(args.begin());
418 service_->writepid_files_ = std::move(args);
419 return {};
420}
421
422Result<void> ServiceParser::ParseUpdatable(std::vector<std::string>&& args) {
423 service_->updatable_ = true;
424 return {};
425}
426
427class ServiceParser::OptionParserMap : public KeywordMap<OptionParser> {
428 public:
429 OptionParserMap() {}
430
431 private:
432 const Map& map() const override;
433};
434
435const ServiceParser::OptionParserMap::Map& ServiceParser::OptionParserMap::map() const {
436 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
437 // clang-format off
438 static const Map option_parsers = {
439 {"capabilities",
440 {0, kMax, &ServiceParser::ParseCapabilities}},
441 {"class", {1, kMax, &ServiceParser::ParseClass}},
442 {"console", {0, 1, &ServiceParser::ParseConsole}},
443 {"critical", {0, 0, &ServiceParser::ParseCritical}},
444 {"disabled", {0, 0, &ServiceParser::ParseDisabled}},
445 {"enter_namespace",
446 {2, 2, &ServiceParser::ParseEnterNamespace}},
447 {"file", {2, 2, &ServiceParser::ParseFile}},
448 {"group", {1, NR_SVC_SUPP_GIDS + 1, &ServiceParser::ParseGroup}},
449 {"interface", {2, 2, &ServiceParser::ParseInterface}},
450 {"ioprio", {2, 2, &ServiceParser::ParseIoprio}},
451 {"keycodes", {1, kMax, &ServiceParser::ParseKeycodes}},
452 {"memcg.limit_in_bytes",
453 {1, 1, &ServiceParser::ParseMemcgLimitInBytes}},
454 {"memcg.limit_percent",
455 {1, 1, &ServiceParser::ParseMemcgLimitPercent}},
456 {"memcg.limit_property",
457 {1, 1, &ServiceParser::ParseMemcgLimitProperty}},
458 {"memcg.soft_limit_in_bytes",
459 {1, 1, &ServiceParser::ParseMemcgSoftLimitInBytes}},
460 {"memcg.swappiness",
461 {1, 1, &ServiceParser::ParseMemcgSwappiness}},
462 {"namespace", {1, 2, &ServiceParser::ParseNamespace}},
463 {"oneshot", {0, 0, &ServiceParser::ParseOneshot}},
464 {"onrestart", {1, kMax, &ServiceParser::ParseOnrestart}},
465 {"oom_score_adjust",
466 {1, 1, &ServiceParser::ParseOomScoreAdjust}},
467 {"override", {0, 0, &ServiceParser::ParseOverride}},
468 {"priority", {1, 1, &ServiceParser::ParsePriority}},
469 {"restart_period",
470 {1, 1, &ServiceParser::ParseRestartPeriod}},
471 {"rlimit", {3, 3, &ServiceParser::ParseProcessRlimit}},
472 {"seclabel", {1, 1, &ServiceParser::ParseSeclabel}},
473 {"setenv", {2, 2, &ServiceParser::ParseSetenv}},
474 {"shutdown", {1, 1, &ServiceParser::ParseShutdown}},
475 {"sigstop", {0, 0, &ServiceParser::ParseSigstop}},
476 {"socket", {3, 6, &ServiceParser::ParseSocket}},
477 {"timeout_period",
478 {1, 1, &ServiceParser::ParseTimeoutPeriod}},
479 {"updatable", {0, 0, &ServiceParser::ParseUpdatable}},
480 {"user", {1, 1, &ServiceParser::ParseUser}},
481 {"writepid", {1, kMax, &ServiceParser::ParseWritepid}},
482 };
483 // clang-format on
484 return option_parsers;
485}
486
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700487Result<void> ServiceParser::ParseSection(std::vector<std::string>&& args,
488 const std::string& filename, int line) {
489 if (args.size() < 3) {
490 return Error() << "services must have a name and a program";
491 }
492
493 const std::string& name = args[1];
494 if (!IsValidName(name)) {
495 return Error() << "invalid service name '" << name << "'";
496 }
497
498 filename_ = filename;
499
500 Subcontext* restart_action_subcontext = nullptr;
501 if (subcontexts_) {
502 for (auto& subcontext : *subcontexts_) {
503 if (StartsWith(filename, subcontext.path_prefix())) {
504 restart_action_subcontext = &subcontext;
505 break;
506 }
507 }
508 }
509
510 std::vector<std::string> str_args(args.begin() + 2, args.end());
511
512 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_P__) {
513 if (str_args[0] == "/sbin/watchdogd") {
514 str_args[0] = "/system/bin/watchdogd";
515 }
516 }
517
518 service_ = std::make_unique<Service>(name, restart_action_subcontext, str_args);
519 return {};
520}
521
522Result<void> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700523 if (!service_) {
524 return {};
525 }
526
527 static const OptionParserMap parser_map;
528 auto parser = parser_map.FindFunction(args);
529
530 if (!parser) return parser.error();
531
532 return std::invoke(*parser, this, std::move(args));
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700533}
534
535Result<void> ServiceParser::EndSection() {
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700536 if (!service_) {
537 return {};
538 }
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700539
Daniel Norman3f42a762019-07-09 11:00:53 -0700540 if (interface_inheritance_hierarchy_) {
541 std::set<std::string> interface_names;
542 for (const std::string& intf : service_->interfaces()) {
543 interface_names.insert(Split(intf, "/")[0]);
544 }
545 std::ostringstream error_stream;
546 for (const std::string& intf : interface_names) {
547 if (interface_inheritance_hierarchy_->count(intf) == 0) {
548 error_stream << "\nInterface is not in the known set of hidl_interfaces: '" << intf
549 << "'. Please ensure the interface is spelled correctly and built "
550 << "by a hidl_interface target.";
551 continue;
552 }
553 const std::set<std::string>& required_interfaces =
554 (*interface_inheritance_hierarchy_)[intf];
555 std::set<std::string> diff;
556 std::set_difference(required_interfaces.begin(), required_interfaces.end(),
557 interface_names.begin(), interface_names.end(),
558 std::inserter(diff, diff.begin()));
559 if (!diff.empty()) {
560 error_stream << "\nInterface '" << intf << "' requires its full inheritance "
561 << "hierarchy to be listed in this init_rc file. Missing "
562 << "interfaces: [" << base::Join(diff, " ") << "]";
563 }
564 }
565 const std::string& errors = error_stream.str();
566 if (!errors.empty()) {
567 return Error() << errors;
568 }
569 }
570
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700571 Service* old_service = service_list_->FindService(service_->name());
572 if (old_service) {
573 if (!service_->is_override()) {
574 return Error() << "ignored duplicate definition of service '" << service_->name()
575 << "'";
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700576 }
577
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700578 if (StartsWith(filename_, "/apex/") && !old_service->is_updatable()) {
579 return Error() << "cannot update a non-updatable service '" << service_->name()
580 << "' with a config in APEX";
581 }
582
583 service_list_->RemoveService(*old_service);
584 old_service = nullptr;
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700585 }
586
Tom Cherryb1ffb1d2019-06-26 11:22:52 -0700587 service_list_->AddService(std::move(service_));
588
Tom Cherry2aeb1ad2019-06-26 10:46:20 -0700589 return {};
590}
591
592bool ServiceParser::IsValidName(const std::string& name) const {
593 // Property names can be any length, but may only contain certain characters.
594 // Property values can contain any characters, but may only be a certain length.
595 // (The latter restriction is needed because `start` and `stop` work by writing
596 // the service name to the "ctl.start" and "ctl.stop" properties.)
597 return IsLegalPropertyName("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
598}
599
600} // namespace init
601} // namespace android