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:
39     Subcontext(std::vector<std::string> path_prefixes, std::string context, bool host = false)
path_prefixes_(std::move (path_prefixes))40         : path_prefixes_(std::move(path_prefixes)), context_(std::move(context)), pid_(0) {
41         if (!host) {
42             Fork();
43         }
44     }
45 
46     Result<void> Execute(const std::vector<std::string>& args);
47     Result<std::vector<std::string>> ExpandArgs(const std::vector<std::string>& args);
48     void Restart();
49     bool PathMatchesSubcontext(const std::string& path);
50 
context()51     const std::string& context() const { return context_; }
pid()52     pid_t pid() const { return pid_; }
53 
54   private:
55     void Fork();
56     Result<SubcontextReply> TransmitMessage(const SubcontextCommand& subcontext_command);
57 
58     std::vector<std::string> path_prefixes_;
59     std::string context_;
60     pid_t pid_;
61     android::base::unique_fd socket_;
62 };
63 
64 int SubcontextMain(int argc, char** argv, const BuiltinFunctionMap* function_map);
65 void InitializeSubcontext();
66 void InitializeHostSubcontext(std::vector<std::string> vendor_prefixes);
67 Subcontext* GetSubcontext();
68 bool SubcontextChildReap(pid_t pid);
69 void SubcontextTerminate();
70 
71 }  // namespace init
72 }  // namespace android
73