blob: 0a5c5b8a5c28d3448cf87c7f5d3b93ef9a1b955d [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 <linux/if_ether.h>
19#include <linux/if_packet.h>
20#include <linux/ip.h>
21#include "bpf_kern.h"
22#include "bpf_shared.h"
23
24ELF_SEC(BPF_PROG_SEC_NAME)
25int bpf_cgroup_ingress(struct __sk_buff* skb) {
26 uint64_t cookie = get_socket_cookie(skb);
27 struct uid_tag* utag = find_map_entry(COOKIE_TAG_MAP, &cookie);
28 uint32_t uid, tag;
29 if (utag) {
30 uid = utag->uid;
31 tag = utag->tag;
32 } else {
33 uid = get_socket_uid(skb);
34 tag = 0;
35 }
36
37 struct stats_key key = {.uid = uid, .tag = tag, .counterSet = 0, .ifaceIndex = skb->ifindex};
38
39 uint32_t* counterSet;
40 counterSet = find_map_entry(UID_COUNTERSET_MAP, &uid);
41 if (counterSet) key.counterSet = *counterSet;
42
43 int ret;
44 if (tag) {
45 struct stats_value* tagValue;
46 tagValue = find_map_entry(TAG_STATS_MAP, &key);
47 if (!tagValue) {
48 struct stats_value newValue = {};
49 write_to_map_entry(TAG_STATS_MAP, &key, &newValue, BPF_NOEXIST);
50 tagValue = find_map_entry(TAG_STATS_MAP, &key);
51 }
52 if (tagValue) {
53 __sync_fetch_and_add(&tagValue->rxPackets, 1);
54 __sync_fetch_and_add(&tagValue->rxBytes, skb->len);
55 }
56 }
57
58 key.tag = 0;
59 struct stats_value* value;
60 value = find_map_entry(UID_STATS_MAP, &key);
61 if (!value) {
62 struct stats_value newValue = {};
63 write_to_map_entry(UID_STATS_MAP, &key, &newValue, BPF_NOEXIST);
64 value = find_map_entry(UID_STATS_MAP, &key);
65 }
66 if (value) {
67 __sync_fetch_and_add(&value->rxPackets, 1);
68 __sync_fetch_and_add(&value->rxBytes, skb->len);
69 }
70 return BPF_PASS;
71}