1 /*
2 * Copyright (C) 2020 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 #define LOG_TAG "libapexutil"
17
18 #include "apexutil.h"
19
20 #include <dirent.h>
21 #include <string.h>
22
23 #include <memory>
24
25 #include <android-base/file.h>
26 #include <android-base/logging.h>
27 #include <android-base/result.h>
28 #include <apex_manifest.pb.h>
29
30 using ::android::base::Error;
31 using ::android::base::ReadFileToString;
32 using ::android::base::Result;
33 using ::apex::proto::ApexManifest;
34
35 namespace {
36
ParseApexManifest(const std::string & manifest_path)37 Result<ApexManifest> ParseApexManifest(const std::string &manifest_path) {
38 std::string content;
39 if (!ReadFileToString(manifest_path, &content)) {
40 return Error() << "Failed to read manifest file: " << manifest_path;
41 }
42 ApexManifest manifest;
43 if (!manifest.ParseFromString(content)) {
44 return Error() << "Can't parse APEX manifest: " << manifest_path;
45 }
46 return manifest;
47 }
48
49 } // namespace
50
51 namespace android {
52 namespace apex {
53
54 std::map<std::string, ApexManifest>
GetActivePackages(const std::string & apex_root)55 GetActivePackages(const std::string &apex_root) {
56 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(apex_root.c_str()),
57 closedir);
58 if (!dir) {
59 return {};
60 }
61
62 std::map<std::string, ApexManifest> apexes;
63 dirent *entry;
64 while ((entry = readdir(dir.get())) != nullptr) {
65 if (entry->d_name[0] == '.')
66 continue;
67 if (entry->d_type != DT_DIR)
68 continue;
69 if (strchr(entry->d_name, '@') != nullptr)
70 continue;
71 if (strcmp(entry->d_name, "sharedlibs") == 0)
72 continue;
73 std::string apex_path = apex_root + "/" + entry->d_name;
74 auto manifest = ParseApexManifest(apex_path + "/apex_manifest.pb");
75 if (manifest.ok()) {
76 apexes.emplace(std::move(apex_path), std::move(*manifest));
77 } else {
78 LOG(WARNING) << manifest.error();
79 }
80 }
81 return apexes;
82 }
83
84 } // namespace apex
85 } // namespace android
86