• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024 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 BPF_RING_BUFFER_H
17 #define BPF_RING_BUFFER_H
18 #include <iostream>
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <errno.h>
22 #include <unistd.h>
23 #include <linux/bpf.h>
24 #include <sys/mman.h>
25 #include <sys/epoll.h>
26 #include <time.h>
27 #include <linux/if_ether.h>
28 #include <linux/unistd.h>
29 #include <string>
30 #include <functional>
31 #include <memory>
32 #include <mutex>
33 #include <vector>
34 
35 #include "bpf_path.h"
36 #include "bpf_def.h"
37 #include "bpf_stats.h"
38 #include "bpf_mapper.h"
39 #include "securec.h"
40 
41 #include "i_netsys_traffic_callback.h"
42 
43 namespace OHOS::NetManagerStandard {
44 
45 enum RingBufferError {
46     RING_BUFFER_ERR_NONE = 0,
47     RING_BUFFER_ERR_INTERNAL,
48 };
49 
50 class NetsysBpfRingBuffer {
51 public:
52     NetsysBpfRingBuffer() = default;
53     ~NetsysBpfRingBuffer() = default;
54 
55     static uint64_t BpfMapPathNameToU64(const std::string &pathName);
56     static int32_t BpfSyscall(int32_t cmd, const bpf_attr &attr);
57     static int GetRingbufFd(const std::string &path, uint32_t fileFlags);
58 
59     static int HandleNetworkPolicyEventCallback(void *ctx, void *data, size_t data_sz);
60     static int HandleNetStatsEventCallback(void *ctx, void *data, size_t dataSz);
61     static void ListenRingBufferThread(void);
62     static void ListenNetworkAccessPolicyEvent();
63     static void ListenNetStatsRingBufferThread();
64     static void ExistRingBufferPoll(void);
65     static void ListenNetworkStatsEvent(void);
66     static void ExistNetstatsRingBufferPoll();
67     static int RegisterNetsysTrafficCallback(const sptr<NetsysNative::INetsysTrafficCallback> &callback);
68     static int UnRegisterNetsysTrafficCallback(const sptr<NetsysNative::INetsysTrafficCallback> &callback);
69 
70 private:
71     static bool existThread_;
72     static std::atomic_bool existNetStatsThread_;
73     static std::vector<sptr<NetsysNative::INetsysTrafficCallback>> callbacks_;
74     static std::mutex callbackMutex_;
75 };
76 } // namespace OHOS::NetManagerStandard
77 #endif // BPF_RING_BUFFER_H
78