Merge tag 'mvebu-dt-5.8-1' of git://git.infradead.org/linux-mvebu into arm/dt
[linux-2.6-microblaze.git] / tools / testing / selftests / bpf / progs / connect4_prog.c
1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2018 Facebook
3
4 #include <string.h>
5
6 #include <linux/stddef.h>
7 #include <linux/bpf.h>
8 #include <linux/in.h>
9 #include <linux/in6.h>
10 #include <sys/socket.h>
11
12 #include <bpf/bpf_helpers.h>
13 #include <bpf/bpf_endian.h>
14
15 #define SRC_REWRITE_IP4         0x7f000004U
16 #define DST_REWRITE_IP4         0x7f000001U
17 #define DST_REWRITE_PORT4       4444
18
19 int _version SEC("version") = 1;
20
21 __attribute__ ((noinline))
22 int do_bind(struct bpf_sock_addr *ctx)
23 {
24         struct sockaddr_in sa = {};
25
26         sa.sin_family = AF_INET;
27         sa.sin_port = bpf_htons(0);
28         sa.sin_addr.s_addr = bpf_htonl(SRC_REWRITE_IP4);
29
30         if (bpf_bind(ctx, (struct sockaddr *)&sa, sizeof(sa)) != 0)
31                 return 0;
32
33         return 1;
34 }
35
36 SEC("cgroup/connect4")
37 int connect_v4_prog(struct bpf_sock_addr *ctx)
38 {
39         struct bpf_sock_tuple tuple = {};
40         struct bpf_sock *sk;
41
42         /* Verify that new destination is available. */
43         memset(&tuple.ipv4.saddr, 0, sizeof(tuple.ipv4.saddr));
44         memset(&tuple.ipv4.sport, 0, sizeof(tuple.ipv4.sport));
45
46         tuple.ipv4.daddr = bpf_htonl(DST_REWRITE_IP4);
47         tuple.ipv4.dport = bpf_htons(DST_REWRITE_PORT4);
48
49         if (ctx->type != SOCK_STREAM && ctx->type != SOCK_DGRAM)
50                 return 0;
51         else if (ctx->type == SOCK_STREAM)
52                 sk = bpf_sk_lookup_tcp(ctx, &tuple, sizeof(tuple.ipv4),
53                                        BPF_F_CURRENT_NETNS, 0);
54         else
55                 sk = bpf_sk_lookup_udp(ctx, &tuple, sizeof(tuple.ipv4),
56                                        BPF_F_CURRENT_NETNS, 0);
57
58         if (!sk)
59                 return 0;
60
61         if (sk->src_ip4 != tuple.ipv4.daddr ||
62             sk->src_port != DST_REWRITE_PORT4) {
63                 bpf_sk_release(sk);
64                 return 0;
65         }
66
67         bpf_sk_release(sk);
68
69         /* Rewrite destination. */
70         ctx->user_ip4 = bpf_htonl(DST_REWRITE_IP4);
71         ctx->user_port = bpf_htons(DST_REWRITE_PORT4);
72
73         return do_bind(ctx) ? 1 : 0;
74 }
75
76 char _license[] SEC("license") = "GPL";