1 /*
2  * Copyright (C) 2017 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 #pragma once
18 
19 #include <signal.h>
20 
21 #include <string>
22 #include <vector>
23 
24 #include <android-base/unique_fd.h>
25 
26 #include "builtins.h"
27 #include "result.h"
28 #include "system/core/init/subcontext.pb.h"
29 
30 namespace android {
31 namespace init {
32 
33 static constexpr const char kInitContext[] = "u:r:init:s0";
34 static constexpr const char kVendorContext[] = "u:r:vendor_init:s0";
35 static constexpr const char kTestContext[] = "test-test-test";
36 
37 class Subcontext {
38   public:
Subcontext(std::vector<std::string> path_prefixes,std::string context)39     Subcontext(std::vector<std::string> path_prefixes, std::string context)
40         : path_prefixes_(std::move(path_prefixes)), context_(std::move(context)), pid_(0) {
41         Fork();
42     }
43 
44     Result<void> Execute(const std::vector<std::string>& args);
45     Result<std::vector<std::string>> ExpandArgs(const std::vector<std::string>& args);
46     void Restart();
47     bool PathMatchesSubcontext(const std::string& path);
48 
context()49     const std::string& context() const { return context_; }
pid()50     pid_t pid() const { return pid_; }
51 
52   private:
53     void Fork();
54     Result<SubcontextReply> TransmitMessage(const SubcontextCommand& subcontext_command);
55 
56     std::vector<std::string> path_prefixes_;
57     std::string context_;
58     pid_t pid_;
59     android::base::unique_fd socket_;
60 };
61 
62 int SubcontextMain(int argc, char** argv, const BuiltinFunctionMap* function_map);
63 void InitializeSubcontext();
64 Subcontext* GetSubcontext();
65 bool SubcontextChildReap(pid_t pid);
66 void SubcontextTerminate();
67 
68 }  // namespace init
69 }  // namespace android
70