1 /* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef NETMANAGER_BASE_BPF_READER_H 17 #define NETMANAGER_BASE_BPF_READER_H 18 19 #include <cerrno> 20 #include <functional> 21 22 #include "bpf_syscall_wrapper.h" 23 24 namespace OHOS { 25 namespace Bpf { 26 template <class Key, class Value> class NetsysBpfMap { 27 public: 28 NetsysBpfMap<Key, Value>() = default; 29 NetsysBpfMap<Key, Value>(const std::string &pathName, uint32_t flags); 30 NetsysBpfMap<Key, Value>(bpf_map_type mapType, uint32_t maxEntries, uint32_t mapFlags); 31 32 /** 33 * Is has map fd 34 * 35 * @return bool true:has map fd false:not have 36 */ 37 bool IsValid() const; 38 39 /** 40 * Read Value From Map 41 * 42 * @param key the key of map 43 * @return Value value corresponding to key 44 */ 45 Value ReadValueFromMap(const Key key) const; 46 47 /** 48 * WriteValue 49 * 50 * @param key the key want to write 51 * @param value the value want to write 52 * @param flags map flag 53 * @return bool true:write success false:failure 54 */ 55 bool WriteValue(const Key &key, const Value &value, uint64_t flags) const; 56 57 /** 58 * Iterate through each element in the map 59 * 60 * @param counter lambda expression to be executed 61 */ 62 void Iterate(const std::function<void(const Key &key, const NetsysBpfMap<Key, Value> &map)> &counter) const; 63 64 /** 65 * Get the Next Key From Map 66 * 67 * @param curkey current key 68 * @return int next Key 69 */ 70 int GetNextKeyFromMap(Key &curkey) const; 71 72 /** 73 * Get the Next Key From Stats Map 74 * 75 * @param curkey current key 76 * @param nextKey reference of next Key 77 * @return int next Key 78 */ 79 int GetNextKeyFromStatsMap(const Key &curkey, Key &nextKey) const; 80 81 /** 82 * BpfMapFdPin 83 * 84 * @param pathName the path that map needs to pin to 85 * @return bool true:pin success false:failure 86 */ 87 bool BpfMapFdPin(const std::string &pathName) const; 88 89 /** 90 * DeleteEntryFromMap 91 * 92 * @param deleteKey the key need to delete 93 * @return bool true:delete success false:failure 94 */ 95 bool DeleteEntryFromMap(const Key &deleteKey); 96 97 private: 98 int32_t mapFd_ = 0; 99 }; 100 } // namespace Bpf 101 } // namespace OHOS 102 #endif // NETMANAGER_BASE_BPF_READER_H 103