• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
19 #include <linux/input.h>
20 #include <stdlib.h>
21 #include <sys/socket.h>
22 
23 #include <algorithm>
24 #include <sstream>
25 
26 #include <android-base/logging.h>
27 #include <android-base/parseint.h>
28 #include <android-base/strings.h>
29 #include <hidl-util/FQName.h>
30 #include <system/thread_defs.h>
31 
32 #include "lmkd_service.h"
33 #include "rlimit_parser.h"
34 #include "service_utils.h"
35 #include "util.h"
36 
37 #ifdef INIT_FULL_SOURCES
38 #include <android/api-level.h>
39 #include <sys/system_properties.h>
40 
41 #include "selinux.h"
42 #else
43 #include "host_init_stubs.h"
44 #endif
45 
46 using android::base::ParseInt;
47 using android::base::Split;
48 using android::base::StartsWith;
49 
50 namespace android {
51 namespace init {
52 
ParseCapabilities(std::vector<std::string> && args)53 Result<void> ServiceParser::ParseCapabilities(std::vector<std::string>&& args) {
54     service_->capabilities_ = 0;
55 
56     if (!CapAmbientSupported()) {
57         return Error()
58                << "capabilities requested but the kernel does not support ambient capabilities";
59     }
60 
61     unsigned int last_valid_cap = GetLastValidCap();
62     if (last_valid_cap >= service_->capabilities_->size()) {
63         LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
64     }
65 
66     for (size_t i = 1; i < args.size(); i++) {
67         const std::string& arg = args[i];
68         int res = LookupCap(arg);
69         if (res < 0) {
70             return Errorf("invalid capability '{}'", arg);
71         }
72         unsigned int cap = static_cast<unsigned int>(res);  // |res| is >= 0.
73         if (cap > last_valid_cap) {
74             return Errorf("capability '{}' not supported by the kernel", arg);
75         }
76         (*service_->capabilities_)[cap] = true;
77     }
78     return {};
79 }
80 
ParseClass(std::vector<std::string> && args)81 Result<void> ServiceParser::ParseClass(std::vector<std::string>&& args) {
82     service_->classnames_ = std::set<std::string>(args.begin() + 1, args.end());
83     return {};
84 }
85 
ParseConsole(std::vector<std::string> && args)86 Result<void> ServiceParser::ParseConsole(std::vector<std::string>&& args) {
87     if (service_->proc_attr_.stdio_to_kmsg) {
88         return Error() << "'console' and 'stdio_to_kmsg' are mutually exclusive";
89     }
90     service_->flags_ |= SVC_CONSOLE;
91     service_->proc_attr_.console = args.size() > 1 ? "/dev/" + args[1] : "";
92     return {};
93 }
94 
ParseCritical(std::vector<std::string> && args)95 Result<void> ServiceParser::ParseCritical(std::vector<std::string>&& args) {
96     std::optional<std::string> fatal_reboot_target;
97     std::optional<std::chrono::minutes> fatal_crash_window;
98 
99     for (auto it = args.begin() + 1; it != args.end(); ++it) {
100         auto arg = android::base::Split(*it, "=");
101         if (arg.size() != 2) {
102             return Error() << "critical: Argument '" << *it << "' is not supported";
103         } else if (arg[0] == "target") {
104             fatal_reboot_target = arg[1];
105         } else if (arg[0] == "window") {
106             int minutes;
107             auto window = ExpandProps(arg[1]);
108             if (!window.ok()) {
109                 return Error() << "critical: Could not expand argument ': " << arg[1];
110             }
111             if (*window == "off") {
112                 return {};
113             }
114             if (!ParseInt(*window, &minutes, 0)) {
115                 return Error() << "critical: 'fatal_crash_window' must be an integer > 0";
116             }
117             fatal_crash_window = std::chrono::minutes(minutes);
118         } else {
119             return Error() << "critical: Argument '" << *it << "' is not supported";
120         }
121     }
122 
123     if (fatal_reboot_target) {
124         service_->fatal_reboot_target_ = *fatal_reboot_target;
125     }
126     if (fatal_crash_window) {
127         service_->fatal_crash_window_ = *fatal_crash_window;
128     }
129     service_->flags_ |= SVC_CRITICAL;
130     return {};
131 }
132 
ParseDisabled(std::vector<std::string> && args)133 Result<void> ServiceParser::ParseDisabled(std::vector<std::string>&& args) {
134     service_->flags_ |= SVC_DISABLED;
135     service_->flags_ |= SVC_RC_DISABLED;
136     return {};
137 }
138 
ParseEnterNamespace(std::vector<std::string> && args)139 Result<void> ServiceParser::ParseEnterNamespace(std::vector<std::string>&& args) {
140     if (args[1] != "net") {
141         return Error() << "Init only supports entering network namespaces";
142     }
143     if (!service_->namespaces_.namespaces_to_enter.empty()) {
144         return Error() << "Only one network namespace may be entered";
145     }
146     // Network namespaces require that /sys is remounted, otherwise the old adapters will still be
147     // present. Therefore, they also require mount namespaces.
148     service_->namespaces_.flags |= CLONE_NEWNS;
149     service_->namespaces_.namespaces_to_enter.emplace_back(CLONE_NEWNET, std::move(args[2]));
150     return {};
151 }
152 
ParseGroup(std::vector<std::string> && args)153 Result<void> ServiceParser::ParseGroup(std::vector<std::string>&& args) {
154     auto gid = DecodeUid(args[1]);
155     if (!gid.ok()) {
156         return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
157     }
158     service_->proc_attr_.gid = *gid;
159 
160     for (std::size_t n = 2; n < args.size(); n++) {
161         gid = DecodeUid(args[n]);
162         if (!gid.ok()) {
163             return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
164         }
165         service_->proc_attr_.supp_gids.emplace_back(*gid);
166     }
167     return {};
168 }
169 
ParsePriority(std::vector<std::string> && args)170 Result<void> ServiceParser::ParsePriority(std::vector<std::string>&& args) {
171     service_->proc_attr_.priority = 0;
172     if (!ParseInt(args[1], &service_->proc_attr_.priority,
173                   static_cast<int>(ANDROID_PRIORITY_HIGHEST),  // highest is negative
174                   static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
175         return Errorf("process priority value must be range {} - {}", ANDROID_PRIORITY_HIGHEST,
176                       ANDROID_PRIORITY_LOWEST);
177     }
178     return {};
179 }
180 
ParseInterface(std::vector<std::string> && args)181 Result<void> ServiceParser::ParseInterface(std::vector<std::string>&& args) {
182     const std::string& interface_name = args[1];
183     const std::string& instance_name = args[2];
184 
185     // AIDL services don't use fully qualified names and instead just use "interface aidl <name>"
186     if (interface_name != "aidl") {
187         FQName fq_name;
188         if (!FQName::parse(interface_name, &fq_name)) {
189             return Error() << "Invalid fully-qualified name for interface '" << interface_name
190                            << "'";
191         }
192 
193         if (!fq_name.isFullyQualified()) {
194             return Error() << "Interface name not fully-qualified '" << interface_name << "'";
195         }
196 
197         if (fq_name.isValidValueName()) {
198             return Error() << "Interface name must not be a value name '" << interface_name << "'";
199         }
200     }
201 
202     const std::string fullname = interface_name + "/" + instance_name;
203 
204     for (const auto& svc : *service_list_) {
205         if (svc->interfaces().count(fullname) > 0) {
206             return Error() << "Interface '" << fullname << "' redefined in " << service_->name()
207                            << " but is already defined by " << svc->name();
208         }
209     }
210 
211     service_->interfaces_.insert(fullname);
212 
213     return {};
214 }
215 
ParseIoprio(std::vector<std::string> && args)216 Result<void> ServiceParser::ParseIoprio(std::vector<std::string>&& args) {
217     if (!ParseInt(args[2], &service_->proc_attr_.ioprio_pri, 0, 7)) {
218         return Error() << "priority value must be range 0 - 7";
219     }
220 
221     if (args[1] == "rt") {
222         service_->proc_attr_.ioprio_class = IoSchedClass_RT;
223     } else if (args[1] == "be") {
224         service_->proc_attr_.ioprio_class = IoSchedClass_BE;
225     } else if (args[1] == "idle") {
226         service_->proc_attr_.ioprio_class = IoSchedClass_IDLE;
227     } else {
228         return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
229     }
230 
231     return {};
232 }
233 
ParseKeycodes(std::vector<std::string> && args)234 Result<void> ServiceParser::ParseKeycodes(std::vector<std::string>&& args) {
235     auto it = args.begin() + 1;
236     if (args.size() == 2 && StartsWith(args[1], "$")) {
237         auto expanded = ExpandProps(args[1]);
238         if (!expanded.ok()) {
239             return expanded.error();
240         }
241 
242         // If the property is not set, it defaults to none, in which case there are no keycodes
243         // for this service.
244         if (*expanded == "none") {
245             return {};
246         }
247 
248         args = Split(*expanded, ",");
249         it = args.begin();
250     }
251 
252     for (; it != args.end(); ++it) {
253         int code;
254         if (ParseInt(*it, &code, 0, KEY_MAX)) {
255             for (auto& key : service_->keycodes_) {
256                 if (key == code) return Error() << "duplicate keycode: " << *it;
257             }
258             service_->keycodes_.insert(
259                     std::upper_bound(service_->keycodes_.begin(), service_->keycodes_.end(), code),
260                     code);
261         } else {
262             return Error() << "invalid keycode: " << *it;
263         }
264     }
265     return {};
266 }
267 
ParseOneshot(std::vector<std::string> && args)268 Result<void> ServiceParser::ParseOneshot(std::vector<std::string>&& args) {
269     service_->flags_ |= SVC_ONESHOT;
270     return {};
271 }
272 
ParseOnrestart(std::vector<std::string> && args)273 Result<void> ServiceParser::ParseOnrestart(std::vector<std::string>&& args) {
274     args.erase(args.begin());
275     int line = service_->onrestart_.NumCommands() + 1;
276     if (auto result = service_->onrestart_.AddCommand(std::move(args), line); !result.ok()) {
277         return Error() << "cannot add Onrestart command: " << result.error();
278     }
279     return {};
280 }
281 
ParseNamespace(std::vector<std::string> && args)282 Result<void> ServiceParser::ParseNamespace(std::vector<std::string>&& args) {
283     for (size_t i = 1; i < args.size(); i++) {
284         if (args[i] == "pid") {
285             service_->namespaces_.flags |= CLONE_NEWPID;
286             // PID namespaces require mount namespaces.
287             service_->namespaces_.flags |= CLONE_NEWNS;
288         } else if (args[i] == "mnt") {
289             service_->namespaces_.flags |= CLONE_NEWNS;
290         } else {
291             return Error() << "namespace must be 'pid' or 'mnt'";
292         }
293     }
294     return {};
295 }
296 
ParseOomScoreAdjust(std::vector<std::string> && args)297 Result<void> ServiceParser::ParseOomScoreAdjust(std::vector<std::string>&& args) {
298     if (!ParseInt(args[1], &service_->oom_score_adjust_, MIN_OOM_SCORE_ADJUST,
299                   MAX_OOM_SCORE_ADJUST)) {
300         return Error() << "oom_score_adjust value must be in range " << MIN_OOM_SCORE_ADJUST
301                        << " - +" << MAX_OOM_SCORE_ADJUST;
302     }
303     return {};
304 }
305 
ParseOverride(std::vector<std::string> && args)306 Result<void> ServiceParser::ParseOverride(std::vector<std::string>&& args) {
307     service_->override_ = true;
308     return {};
309 }
310 
ParseMemcgSwappiness(std::vector<std::string> && args)311 Result<void> ServiceParser::ParseMemcgSwappiness(std::vector<std::string>&& args) {
312     if (!ParseInt(args[1], &service_->swappiness_, 0)) {
313         return Error() << "swappiness value must be equal or greater than 0";
314     }
315     return {};
316 }
317 
ParseMemcgLimitInBytes(std::vector<std::string> && args)318 Result<void> ServiceParser::ParseMemcgLimitInBytes(std::vector<std::string>&& args) {
319     if (!ParseInt(args[1], &service_->limit_in_bytes_, 0)) {
320         return Error() << "limit_in_bytes value must be equal or greater than 0";
321     }
322     return {};
323 }
324 
ParseMemcgLimitPercent(std::vector<std::string> && args)325 Result<void> ServiceParser::ParseMemcgLimitPercent(std::vector<std::string>&& args) {
326     if (!ParseInt(args[1], &service_->limit_percent_, 0)) {
327         return Error() << "limit_percent value must be equal or greater than 0";
328     }
329     return {};
330 }
331 
ParseMemcgLimitProperty(std::vector<std::string> && args)332 Result<void> ServiceParser::ParseMemcgLimitProperty(std::vector<std::string>&& args) {
333     service_->limit_property_ = std::move(args[1]);
334     return {};
335 }
336 
ParseMemcgSoftLimitInBytes(std::vector<std::string> && args)337 Result<void> ServiceParser::ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args) {
338     if (!ParseInt(args[1], &service_->soft_limit_in_bytes_, 0)) {
339         return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
340     }
341     return {};
342 }
343 
ParseProcessRlimit(std::vector<std::string> && args)344 Result<void> ServiceParser::ParseProcessRlimit(std::vector<std::string>&& args) {
345     auto rlimit = ParseRlimit(args);
346     if (!rlimit.ok()) return rlimit.error();
347 
348     service_->proc_attr_.rlimits.emplace_back(*rlimit);
349     return {};
350 }
351 
ParseRebootOnFailure(std::vector<std::string> && args)352 Result<void> ServiceParser::ParseRebootOnFailure(std::vector<std::string>&& args) {
353     if (service_->on_failure_reboot_target_) {
354         return Error() << "Only one reboot_on_failure command may be specified";
355     }
356     if (!StartsWith(args[1], "shutdown") && !StartsWith(args[1], "reboot")) {
357         return Error()
358                << "reboot_on_failure commands must begin with either 'shutdown' or 'reboot'";
359     }
360     service_->on_failure_reboot_target_ = std::move(args[1]);
361     return {};
362 }
363 
ParseRestartPeriod(std::vector<std::string> && args)364 Result<void> ServiceParser::ParseRestartPeriod(std::vector<std::string>&& args) {
365     int period;
366     if (!ParseInt(args[1], &period, 5)) {
367         return Error() << "restart_period value must be an integer >= 5";
368     }
369     service_->restart_period_ = std::chrono::seconds(period);
370     return {};
371 }
372 
ParseSeclabel(std::vector<std::string> && args)373 Result<void> ServiceParser::ParseSeclabel(std::vector<std::string>&& args) {
374     service_->seclabel_ = std::move(args[1]);
375     return {};
376 }
377 
ParseSigstop(std::vector<std::string> && args)378 Result<void> ServiceParser::ParseSigstop(std::vector<std::string>&& args) {
379     service_->sigstop_ = true;
380     return {};
381 }
382 
ParseSetenv(std::vector<std::string> && args)383 Result<void> ServiceParser::ParseSetenv(std::vector<std::string>&& args) {
384     service_->environment_vars_.emplace_back(std::move(args[1]), std::move(args[2]));
385     return {};
386 }
387 
ParseShutdown(std::vector<std::string> && args)388 Result<void> ServiceParser::ParseShutdown(std::vector<std::string>&& args) {
389     if (args[1] == "critical") {
390         service_->flags_ |= SVC_SHUTDOWN_CRITICAL;
391         return {};
392     }
393     return Error() << "Invalid shutdown option";
394 }
395 
ParseTaskProfiles(std::vector<std::string> && args)396 Result<void> ServiceParser::ParseTaskProfiles(std::vector<std::string>&& args) {
397     args.erase(args.begin());
398     service_->task_profiles_ = std::move(args);
399     return {};
400 }
401 
ParseTimeoutPeriod(std::vector<std::string> && args)402 Result<void> ServiceParser::ParseTimeoutPeriod(std::vector<std::string>&& args) {
403     int period;
404     if (!ParseInt(args[1], &period, 1)) {
405         return Error() << "timeout_period value must be an integer >= 1";
406     }
407     service_->timeout_period_ = std::chrono::seconds(period);
408     return {};
409 }
410 
411 // name type perm [ uid gid context ]
ParseSocket(std::vector<std::string> && args)412 Result<void> ServiceParser::ParseSocket(std::vector<std::string>&& args) {
413     SocketDescriptor socket;
414     socket.name = std::move(args[1]);
415 
416     auto types = Split(args[2], "+");
417     if (types[0] == "stream") {
418         socket.type = SOCK_STREAM;
419     } else if (types[0] == "dgram") {
420         socket.type = SOCK_DGRAM;
421     } else if (types[0] == "seqpacket") {
422         socket.type = SOCK_SEQPACKET;
423     } else {
424         return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket', got '" << types[0]
425                        << "' instead.";
426     }
427 
428     if (types.size() > 1) {
429         if (types.size() == 2 && types[1] == "passcred") {
430             socket.passcred = true;
431         } else {
432             return Error() << "Only 'passcred' may be used to modify the socket type";
433         }
434     }
435 
436     errno = 0;
437     char* end = nullptr;
438     socket.perm = strtol(args[3].c_str(), &end, 8);
439     if (errno != 0) {
440         return ErrnoError() << "Unable to parse permissions '" << args[3] << "'";
441     }
442     if (end == args[3].c_str() || *end != '\0') {
443         errno = EINVAL;
444         return ErrnoError() << "Unable to parse permissions '" << args[3] << "'";
445     }
446 
447     if (args.size() > 4) {
448         auto uid = DecodeUid(args[4]);
449         if (!uid.ok()) {
450             return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
451         }
452         socket.uid = *uid;
453     }
454 
455     if (args.size() > 5) {
456         auto gid = DecodeUid(args[5]);
457         if (!gid.ok()) {
458             return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
459         }
460         socket.gid = *gid;
461     }
462 
463     socket.context = args.size() > 6 ? args[6] : "";
464 
465     auto old = std::find_if(service_->sockets_.begin(), service_->sockets_.end(),
466                             [&socket](const auto& other) { return socket.name == other.name; });
467 
468     if (old != service_->sockets_.end()) {
469         return Error() << "duplicate socket descriptor '" << socket.name << "'";
470     }
471 
472     service_->sockets_.emplace_back(std::move(socket));
473 
474     return {};
475 }
476 
ParseStdioToKmsg(std::vector<std::string> && args)477 Result<void> ServiceParser::ParseStdioToKmsg(std::vector<std::string>&& args) {
478     if (service_->flags_ & SVC_CONSOLE) {
479         return Error() << "'stdio_to_kmsg' and 'console' are mutually exclusive";
480     }
481     service_->proc_attr_.stdio_to_kmsg = true;
482     return {};
483 }
484 
485 // name type
ParseFile(std::vector<std::string> && args)486 Result<void> ServiceParser::ParseFile(std::vector<std::string>&& args) {
487     if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
488         return Error() << "file type must be 'r', 'w' or 'rw'";
489     }
490 
491     FileDescriptor file;
492     file.type = args[2];
493 
494     auto file_name = ExpandProps(args[1]);
495     if (!file_name.ok()) {
496         return Error() << "Could not expand file path ': " << file_name.error();
497     }
498     file.name = *file_name;
499     if (file.name[0] != '/' || file.name.find("../") != std::string::npos) {
500         return Error() << "file name must not be relative";
501     }
502 
503     auto old = std::find_if(service_->files_.begin(), service_->files_.end(),
504                             [&file](const auto& other) { return other.name == file.name; });
505 
506     if (old != service_->files_.end()) {
507         return Error() << "duplicate file descriptor '" << file.name << "'";
508     }
509 
510     service_->files_.emplace_back(std::move(file));
511 
512     return {};
513 }
514 
ParseUser(std::vector<std::string> && args)515 Result<void> ServiceParser::ParseUser(std::vector<std::string>&& args) {
516     auto uid = DecodeUid(args[1]);
517     if (!uid.ok()) {
518         return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
519     }
520     service_->proc_attr_.uid = *uid;
521     return {};
522 }
523 
ParseWritepid(std::vector<std::string> && args)524 Result<void> ServiceParser::ParseWritepid(std::vector<std::string>&& args) {
525     args.erase(args.begin());
526     service_->writepid_files_ = std::move(args);
527     return {};
528 }
529 
ParseUpdatable(std::vector<std::string> && args)530 Result<void> ServiceParser::ParseUpdatable(std::vector<std::string>&& args) {
531     service_->updatable_ = true;
532     return {};
533 }
534 
GetParserMap() const535 const KeywordMap<ServiceParser::OptionParser>& ServiceParser::GetParserMap() const {
536     constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
537     // clang-format off
538     static const KeywordMap<ServiceParser::OptionParser> parser_map = {
539         {"capabilities",            {0,     kMax, &ServiceParser::ParseCapabilities}},
540         {"class",                   {1,     kMax, &ServiceParser::ParseClass}},
541         {"console",                 {0,     1,    &ServiceParser::ParseConsole}},
542         {"critical",                {0,     2,    &ServiceParser::ParseCritical}},
543         {"disabled",                {0,     0,    &ServiceParser::ParseDisabled}},
544         {"enter_namespace",         {2,     2,    &ServiceParser::ParseEnterNamespace}},
545         {"file",                    {2,     2,    &ServiceParser::ParseFile}},
546         {"group",                   {1,     NR_SVC_SUPP_GIDS + 1, &ServiceParser::ParseGroup}},
547         {"interface",               {2,     2,    &ServiceParser::ParseInterface}},
548         {"ioprio",                  {2,     2,    &ServiceParser::ParseIoprio}},
549         {"keycodes",                {1,     kMax, &ServiceParser::ParseKeycodes}},
550         {"memcg.limit_in_bytes",    {1,     1,    &ServiceParser::ParseMemcgLimitInBytes}},
551         {"memcg.limit_percent",     {1,     1,    &ServiceParser::ParseMemcgLimitPercent}},
552         {"memcg.limit_property",    {1,     1,    &ServiceParser::ParseMemcgLimitProperty}},
553         {"memcg.soft_limit_in_bytes",
554                                     {1,     1,    &ServiceParser::ParseMemcgSoftLimitInBytes}},
555         {"memcg.swappiness",        {1,     1,    &ServiceParser::ParseMemcgSwappiness}},
556         {"namespace",               {1,     2,    &ServiceParser::ParseNamespace}},
557         {"oneshot",                 {0,     0,    &ServiceParser::ParseOneshot}},
558         {"onrestart",               {1,     kMax, &ServiceParser::ParseOnrestart}},
559         {"oom_score_adjust",        {1,     1,    &ServiceParser::ParseOomScoreAdjust}},
560         {"override",                {0,     0,    &ServiceParser::ParseOverride}},
561         {"priority",                {1,     1,    &ServiceParser::ParsePriority}},
562         {"reboot_on_failure",       {1,     1,    &ServiceParser::ParseRebootOnFailure}},
563         {"restart_period",          {1,     1,    &ServiceParser::ParseRestartPeriod}},
564         {"rlimit",                  {3,     3,    &ServiceParser::ParseProcessRlimit}},
565         {"seclabel",                {1,     1,    &ServiceParser::ParseSeclabel}},
566         {"setenv",                  {2,     2,    &ServiceParser::ParseSetenv}},
567         {"shutdown",                {1,     1,    &ServiceParser::ParseShutdown}},
568         {"sigstop",                 {0,     0,    &ServiceParser::ParseSigstop}},
569         {"socket",                  {3,     6,    &ServiceParser::ParseSocket}},
570         {"stdio_to_kmsg",           {0,     0,    &ServiceParser::ParseStdioToKmsg}},
571         {"task_profiles",           {1,     kMax, &ServiceParser::ParseTaskProfiles}},
572         {"timeout_period",          {1,     1,    &ServiceParser::ParseTimeoutPeriod}},
573         {"updatable",               {0,     0,    &ServiceParser::ParseUpdatable}},
574         {"user",                    {1,     1,    &ServiceParser::ParseUser}},
575         {"writepid",                {1,     kMax, &ServiceParser::ParseWritepid}},
576     };
577     // clang-format on
578     return parser_map;
579 }
580 
ParseSection(std::vector<std::string> && args,const std::string & filename,int line)581 Result<void> ServiceParser::ParseSection(std::vector<std::string>&& args,
582                                          const std::string& filename, int line) {
583     if (args.size() < 3) {
584         return Error() << "services must have a name and a program";
585     }
586 
587     const std::string& name = args[1];
588     if (!IsValidName(name)) {
589         return Error() << "invalid service name '" << name << "'";
590     }
591 
592     filename_ = filename;
593 
594     Subcontext* restart_action_subcontext = nullptr;
595     if (subcontext_ && subcontext_->PathMatchesSubcontext(filename)) {
596         restart_action_subcontext = subcontext_;
597     }
598 
599     std::vector<std::string> str_args(args.begin() + 2, args.end());
600 
601     if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_P__) {
602         if (str_args[0] == "/sbin/watchdogd") {
603             str_args[0] = "/system/bin/watchdogd";
604         }
605     }
606     if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
607         if (str_args[0] == "/charger") {
608             str_args[0] = "/system/bin/charger";
609         }
610     }
611 
612     service_ = std::make_unique<Service>(name, restart_action_subcontext, str_args, from_apex_);
613     return {};
614 }
615 
ParseLineSection(std::vector<std::string> && args,int line)616 Result<void> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
617     if (!service_) {
618         return {};
619     }
620 
621     auto parser = GetParserMap().Find(args);
622 
623     if (!parser.ok()) return parser.error();
624 
625     return std::invoke(*parser, this, std::move(args));
626 }
627 
EndSection()628 Result<void> ServiceParser::EndSection() {
629     if (!service_) {
630         return {};
631     }
632 
633     if (interface_inheritance_hierarchy_) {
634         if (const auto& check_hierarchy_result = CheckInterfaceInheritanceHierarchy(
635                     service_->interfaces(), *interface_inheritance_hierarchy_);
636             !check_hierarchy_result.ok()) {
637             return Error() << check_hierarchy_result.error();
638         }
639     }
640 
641     if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__) {
642         if ((service_->flags() & SVC_CRITICAL) != 0 && (service_->flags() & SVC_ONESHOT) != 0) {
643             return Error() << "service '" << service_->name()
644                            << "' can't be both critical and oneshot";
645         }
646     }
647 
648     Service* old_service = service_list_->FindService(service_->name());
649     if (old_service) {
650         if (!service_->is_override()) {
651             return Error() << "ignored duplicate definition of service '" << service_->name()
652                            << "'";
653         }
654 
655         if (StartsWith(filename_, "/apex/") && !old_service->is_updatable()) {
656             return Error() << "cannot update a non-updatable service '" << service_->name()
657                            << "' with a config in APEX";
658         }
659 
660         std::string context = service_->subcontext() ? service_->subcontext()->context() : "";
661         std::string old_context =
662                 old_service->subcontext() ? old_service->subcontext()->context() : "";
663         if (context != old_context) {
664             return Error() << "service '" << service_->name() << "' overrides another service "
665                            << "across the treble boundary.";
666         }
667 
668         service_list_->RemoveService(*old_service);
669         old_service = nullptr;
670     }
671 
672     service_list_->AddService(std::move(service_));
673 
674     return {};
675 }
676 
IsValidName(const std::string & name) const677 bool ServiceParser::IsValidName(const std::string& name) const {
678     // Property names can be any length, but may only contain certain characters.
679     // Property values can contain any characters, but may only be a certain length.
680     // (The latter restriction is needed because `start` and `stop` work by writing
681     // the service name to the "ctl.start" and "ctl.stop" properties.)
682     return IsLegalPropertyName("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
683 }
684 
685 }  // namespace init
686 }  // namespace android
687