blob: 2a2ef8cd68f50702cbf6b6d3c7766cb76e029c91 [file] [log] [blame]
Chenbo Feng36575d02018-02-05 15:19:15 -08001/*
2 * Copyright (C) 2018 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 <linux/bpf.h>
18#include <stdint.h>
Chenbo Feng5ed17992018-03-13 21:30:49 -070019#include "bpf_shared.h"
Chenbo Feng36575d02018-02-05 15:19:15 -080020
21#define ELF_SEC(NAME) __attribute__((section(NAME), used))
22
23struct uid_tag {
24 uint32_t uid;
25 uint32_t tag;
26};
27
28struct stats_key {
29 uint32_t uid;
30 uint32_t tag;
31 uint32_t counterSet;
32 uint32_t ifaceIndex;
33};
34
35struct stats_value {
36 uint64_t rxPackets;
37 uint64_t rxBytes;
38 uint64_t txPackets;
39 uint64_t txBytes;
40};
41
42/* helper functions called from eBPF programs written in C */
43static void* (*find_map_entry)(uint64_t map, void* key) = (void*)BPF_FUNC_map_lookup_elem;
44static int (*write_to_map_entry)(uint64_t map, void* key, void* value,
45 uint64_t flags) = (void*)BPF_FUNC_map_update_elem;
46static int (*delete_map_entry)(uint64_t map, void* key) = (void*)BPF_FUNC_map_delete_elem;
47static uint64_t (*get_socket_cookie)(struct __sk_buff* skb) = (void*)BPF_FUNC_get_socket_cookie;
48static uint32_t (*get_socket_uid)(struct __sk_buff* skb) = (void*)BPF_FUNC_get_socket_uid;
49static int (*bpf_skb_load_bytes)(struct __sk_buff* skb, int off, void* to,
50 int len) = (void*)BPF_FUNC_skb_load_bytes;
51
52#define BPF_PASS 1
53#define BPF_DROP 0
Chenbo Feng5ed17992018-03-13 21:30:49 -070054#define BPF_EGRESS 0
55#define BPF_INGRESS 1
56
57static __always_inline int xt_bpf_count(struct __sk_buff* skb, int type) {
58 uint32_t key = skb->ifindex;
59 struct stats_value* value;
60
61 value = find_map_entry(IFACE_STATS_MAP, &key);
62 if (!value) {
63 struct stats_value newValue = {};
64 write_to_map_entry(IFACE_STATS_MAP, &key, &newValue, BPF_NOEXIST);
65 value = find_map_entry(IFACE_STATS_MAP, &key);
66 }
67 if (value) {
68 if (type == BPF_EGRESS) {
69 __sync_fetch_and_add(&value->txPackets, 1);
70 __sync_fetch_and_add(&value->txBytes, skb->len);
71 } else if (type == BPF_INGRESS) {
72 __sync_fetch_and_add(&value->rxPackets, 1);
73 __sync_fetch_and_add(&value->rxBytes, skb->len);
74 }
75 }
76 return BPF_PASS;
77}