cf2511c33905751bb6ed866bf6bba9b1fb8330f3
[cascardo/linux.git] / samples / bpf / parse_simple.c
1 /* Copyright (c) 2016 Facebook
2  *
3  * This program is free software; you can redistribute it and/or
4  * modify it under the terms of version 2 of the GNU General Public
5  * License as published by the Free Software Foundation.
6  */
7 #include <linux/ip.h>
8 #include <linux/ipv6.h>
9 #include <linux/in.h>
10 #include <linux/tcp.h>
11 #include <linux/udp.h>
12 #include <uapi/linux/bpf.h>
13 #include <net/ip.h>
14 #include "bpf_helpers.h"
15
16 #define DEFAULT_PKTGEN_UDP_PORT 9
17
18 /* copy of 'struct ethhdr' without __packed */
19 struct eth_hdr {
20         unsigned char   h_dest[ETH_ALEN];
21         unsigned char   h_source[ETH_ALEN];
22         unsigned short  h_proto;
23 };
24
25 SEC("simple")
26 int handle_ingress(struct __sk_buff *skb)
27 {
28         void *data = (void *)(long)skb->data;
29         struct eth_hdr *eth = data;
30         struct iphdr *iph = data + sizeof(*eth);
31         struct udphdr *udp = data + sizeof(*eth) + sizeof(*iph);
32         void *data_end = (void *)(long)skb->data_end;
33
34         /* single length check */
35         if (data + sizeof(*eth) + sizeof(*iph) + sizeof(*udp) > data_end)
36                 return 0;
37
38         if (eth->h_proto != htons(ETH_P_IP))
39                 return 0;
40         if (iph->protocol != IPPROTO_UDP || iph->ihl != 5)
41                 return 0;
42         if (ip_is_fragment(iph))
43                 return 0;
44         if (udp->dest == htons(DEFAULT_PKTGEN_UDP_PORT))
45                 return TC_ACT_SHOT;
46         return 0;
47 }
48 char _license[] SEC("license") = "GPL";