1 /*
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 "vsockinfo.h"
18 
19 #include <sstream>
20 
21 #ifdef __BIONIC__
22 #include <android-base/logging.h>
23 #include <cutils/properties.h>
24 #endif  // __BIONIC__
25 
26 namespace android::hardware::automotive::utils {
27 
28 #ifdef __BIONIC__
29 
30 namespace {
getNumberFromProperty(const char * key)31 std::optional<unsigned> getNumberFromProperty(const char* key) {
32     auto value = property_get_int64(key, -1);
33     if ((value <= 0) || (value > UINT_MAX)) {
34         LOG(WARNING) << key << " is missing or out of bounds";
35         return std::nullopt;
36     }
37 
38     return static_cast<unsigned int>(value);
39 }
40 
getNumberFromProperties(const PropertyList & arr)41 std::optional<unsigned> getNumberFromProperties(const PropertyList& arr) {
42     for (const auto& key : arr) {
43         auto val = getNumberFromProperty(key.c_str());
44         if (val) return val;
45     }
46 
47     return std::nullopt;
48 }
49 }  // namespace
50 
fromRoPropertyStore(const PropertyList & cid_props,const PropertyList & port_props)51 std::optional<VsockConnectionInfo> VsockConnectionInfo::fromRoPropertyStore(
52         const PropertyList& cid_props, const PropertyList& port_props) {
53     const auto cid = getNumberFromProperties(cid_props);
54     const auto port = getNumberFromProperties(port_props);
55 
56     if (cid && port) {
57         return {{*cid, *port}};
58     } else {
59         return {};
60     }
61 }
62 
63 #endif  // __BIONIC__
64 
str() const65 std::string VsockConnectionInfo::str() const {
66     std::stringstream ss;
67 
68     ss << "vsock:" << cid << ":" << port;
69     return ss.str();
70 }
71 
72 }  // namespace android::hardware::automotive::utils
73