1 /* Copyright (c) 2017 Covalent IO, Inc. http://covalent.io
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.
7 * This program is distributed in the hope that it will be useful, but
8 * WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 * General Public License for more details.
12 #include <uapi/linux/bpf.h>
13 #include <uapi/linux/if_ether.h>
14 #include <uapi/linux/if_packet.h>
15 #include <uapi/linux/ip.h>
16 #include "../../tools/testing/selftests/bpf/bpf_helpers.h"
17 #include "../../tools/testing/selftests/bpf/bpf_endian.h"
19 /* Sockmap sample program connects a client and a backend together
22 * client:X <---> frontend:80 client:X <---> backend:80
24 * For simplicity we hard code values here and bind 1:1. The hard
25 * coded values are part of the setup in sockmap.sh script that
26 * is associated with this BPF program.
28 * The bpf_printk is verbose and prints information as connections
29 * are established and verdicts are decided.
32 #define bpf_printk(fmt, ...) \
34 char ____fmt[] = fmt; \
35 bpf_trace_printk(____fmt, sizeof(____fmt), \
39 struct bpf_map_def SEC("maps") sock_map = {
40 .type = BPF_MAP_TYPE_SOCKMAP,
41 .key_size = sizeof(int),
42 .value_size = sizeof(int),
47 int bpf_prog1(struct __sk_buff *skb)
53 int bpf_prog2(struct __sk_buff *skb)
55 __u32 lport = skb->local_port;
56 __u32 rport = skb->remote_port;
64 bpf_printk("sockmap: %d -> %d @ %d\n", lport, bpf_ntohl(rport), ret);
65 return bpf_sk_redirect_map(&sock_map, ret, 0);
69 int bpf_sockmap(struct bpf_sock_ops *skops)
72 int op, err = 0, index, key, ret;
78 case BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB:
79 lport = skops->local_port;
80 rport = skops->remote_port;
84 err = bpf_sock_map_update(skops, &sock_map, &ret,
86 bpf_printk("passive(%i -> %i) map ctx update err: %d\n",
87 lport, bpf_ntohl(rport), err);
90 case BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB:
91 lport = skops->local_port;
92 rport = skops->remote_port;
94 if (bpf_ntohl(rport) == 10001) {
96 err = bpf_sock_map_update(skops, &sock_map, &ret,
98 bpf_printk("active(%i -> %i) map ctx update err: %d\n",
99 lport, bpf_ntohl(rport), err);
108 char _license[] SEC("license") = "GPL";