1 /*
2  * Copyright (C) 2023 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 <libProxyConfig/libProxyConfig.h>
18 
19 #include <json/json.h>
20 
21 #include <fstream>
22 #include <map>
23 #include <mutex>
24 
25 namespace android::automotive::proxyconfig {
26 
27 static std::map<std::string, Service> serviceConfigs;
28 std::once_flag flag;
29 
30 static std::string_view proxyConfig =
31     "/etc/automotive/proxy_config.json";
32 
setProxyConfigFile(std::string_view configFile)33 void setProxyConfigFile(std::string_view configFile) {
34     proxyConfig = configFile;
35 }
36 
readVmService(Json::Value service)37 static Service readVmService(Json::Value service) {
38     Service vmService;
39 
40     vmService.name = service["name"].asString();
41     vmService.port = service["port"].asInt();
42 
43     return vmService;
44 }
45 
getAllVmProxyConfigs()46 std::vector<VmProxyConfig> getAllVmProxyConfigs() {
47     std::ifstream file(std::string(proxyConfig).c_str());
48     Json::Value jsonConfig;
49     file >> jsonConfig;
50     std::vector<VmProxyConfig> vmConfigs;
51 
52     for (const auto& vm: jsonConfig) {
53         VmProxyConfig vmConfig;
54         vmConfig.cid = vm["CID"].asInt();
55         for (const auto& service: vm["Services"]) {
56             vmConfig.services.push_back(readVmService(service));
57         }
58         vmConfigs.push_back(vmConfig);
59     }
60     return vmConfigs;
61 }
62 
lazyLoadConfig()63 static void lazyLoadConfig() {
64     std::call_once(flag, [](){
65         std::vector<VmProxyConfig> vmConfigs = getAllVmProxyConfigs();
66         for (const auto& vmConfig: vmConfigs) {
67             for (const auto& service: vmConfig.services) {
68                 serviceConfigs.insert({service.name, service});
69             }
70         }
71     });
72 }
73 
getServiceConfig(std::string_view name)74 std::optional<Service> getServiceConfig(std::string_view name) {
75     lazyLoadConfig();
76     if (auto entry = serviceConfigs.find(std::string(name)); entry != serviceConfigs.end()) {
77         return entry->second;
78     }
79     return std::nullopt;
80 }
81 
82 }  // namespace android::automotive::proxyconfig
83