Ken Chen | ec0f7ac | 2023-09-08 14:14:55 +0800 | [diff] [blame] | 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 | #define LOG_TAG "DnsBpfHelper" |
| 18 | |
| 19 | #include "DnsBpfHelper.h" |
| 20 | |
| 21 | #include <android-base/logging.h> |
| 22 | #include <android-modules-utils/sdk_level.h> |
| 23 | |
| 24 | namespace android { |
| 25 | namespace net { |
| 26 | |
| 27 | base::Result<void> DnsBpfHelper::init() { |
| 28 | if (!android::modules::sdklevel::IsAtLeastT()) { |
| 29 | LOG(ERROR) << __func__ << ": Unsupported before Android T."; |
| 30 | return base::Error(EOPNOTSUPP); |
| 31 | } |
| 32 | |
| 33 | auto result = mConfigurationMap.init(CONFIGURATION_MAP_PATH); |
| 34 | if (!result.ok()) { |
| 35 | LOG(ERROR) << __func__ << ": Failed to init configuration_map: " |
| 36 | << strerror(result.error().code()); |
| 37 | return result; |
| 38 | } |
| 39 | |
| 40 | result = mUidOwnerMap.init(UID_OWNER_MAP_PATH); |
| 41 | if (!result.ok()) { |
| 42 | LOG(ERROR) << __func__ << ": Failed to init uid_owner_map: " |
| 43 | << strerror(result.error().code()); |
| 44 | } |
| 45 | return result; |
| 46 | } |
| 47 | |
| 48 | base::Result<bool> DnsBpfHelper::isUidNetworkingBlocked(uid_t uid, bool) { |
| 49 | if (is_system_uid(uid)) return false; |
| 50 | if (!mConfigurationMap.isValid() || !mUidOwnerMap.isValid()) { |
| 51 | LOG(ERROR) << __func__ |
| 52 | << ": BPF maps are not ready. Forgot to call ADnsHelper_init?"; |
| 53 | return base::Error(EUNATCH); |
| 54 | } |
| 55 | |
| 56 | auto enabledRules = mConfigurationMap.readValue(UID_RULES_CONFIGURATION_KEY); |
| 57 | if (!enabledRules.ok()) { |
| 58 | LOG(ERROR) << __func__ |
| 59 | << ": Failed to read enabled rules from configuration_map: " |
| 60 | << strerror(enabledRules.error().code()); |
| 61 | return enabledRules.error(); |
| 62 | } |
| 63 | |
| 64 | auto value = mUidOwnerMap.readValue(uid); |
| 65 | uint32_t uidRules = value.ok() ? value.value().rule : 0; |
| 66 | |
| 67 | if (isBlockedByUidRules(enabledRules.value(), uidRules)) return true; |
| 68 | |
| 69 | // TODO: Read data saver settings from bpf maps. For metered network, check penalty box, happy box |
| 70 | // and data saver settings. |
| 71 | |
| 72 | return false; |
| 73 | } |
| 74 | |
| 75 | } // namespace net |
| 76 | } // namespace android |