blob: daeb83261972ecc5172b7988b7fab9cc6cd3788a [file] [log] [blame]
Vic Yang92c236e2019-05-28 15:58:35 -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 "selabel.h"
18
19#include <selinux/android.h>
20
21namespace android {
22namespace init {
23
24namespace {
25
26selabel_handle* sehandle = nullptr;
27}
28
29// selinux_android_file_context_handle() takes on the order of 10+ms to run, so we want to cache
30// its value. selinux_android_restorecon() also needs an sehandle for file context look up. It
31// will create and store its own copy, but selinux_android_set_sehandle() can be used to provide
32// one, thus eliminating an extra call to selinux_android_file_context_handle().
33void SelabelInitialize() {
34 sehandle = selinux_android_file_context_handle();
35 selinux_android_set_sehandle(sehandle);
36}
37
38// A C++ wrapper around selabel_lookup() using the cached sehandle.
39// If sehandle is null, this returns success with an empty context.
40bool SelabelLookupFileContext(const std::string& key, int type, std::string* result) {
41 result->clear();
42
43 if (!sehandle) return true;
44
45 char* context;
46 if (selabel_lookup(sehandle, &context, key.c_str(), type) != 0) {
47 return false;
48 }
49 *result = context;
50 free(context);
51 return true;
52}
53
54// A C++ wrapper around selabel_lookup_best_match() using the cached sehandle.
55// If sehandle is null, this returns success with an empty context.
56bool SelabelLookupFileContextBestMatch(const std::string& key,
57 const std::vector<std::string>& aliases, int type,
58 std::string* result) {
59 result->clear();
60
61 if (!sehandle) return true;
62
63 std::vector<const char*> c_aliases;
64 for (const auto& alias : aliases) {
65 c_aliases.emplace_back(alias.c_str());
66 }
67 c_aliases.emplace_back(nullptr);
68
69 char* context;
70 if (selabel_lookup_best_match(sehandle, &context, key.c_str(), &c_aliases[0], type) != 0) {
71 return false;
72 }
73 *result = context;
74 free(context);
75 return true;
76}
77
78} // namespace init
79} // namespace android