github.com/cilium/cilium@v1.16.2/bpf/lib/l4.h (about) 1 /* SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) */ 2 /* Copyright Authors of Cilium */ 3 4 #pragma once 5 6 #include <linux/tcp.h> 7 #include <linux/udp.h> 8 #include "common.h" 9 #include "dbg.h" 10 #include "csum.h" 11 12 #define TCP_DPORT_OFF (offsetof(struct tcphdr, dest)) 13 #define TCP_SPORT_OFF (offsetof(struct tcphdr, source)) 14 #define UDP_DPORT_OFF (offsetof(struct udphdr, dest)) 15 #define UDP_SPORT_OFF (offsetof(struct udphdr, source)) 16 17 union tcp_flags { 18 struct { 19 __u8 upper_bits; 20 __u8 lower_bits; 21 __u16 pad; 22 }; 23 __u32 value; 24 }; 25 26 static __always_inline __u8 tcp_flags_to_u8(__be32 value) 27 { 28 return ((union tcp_flags)value).lower_bits; 29 } 30 31 static __always_inline int 32 l4_store_port(struct __ctx_buff *ctx, int l4_off, int port_off, __be16 port) 33 { 34 return ctx_store_bytes(ctx, l4_off + port_off, &port, sizeof(port), 0); 35 } 36 37 /** 38 * Modify L4 port and correct checksum 39 * @arg ctx: packet 40 * @arg l4_off: offset to L4 header 41 * @arg off: offset from L4 header to source or destination port 42 * @arg csum_off: offset from L4 header to 16bit checksum field in L4 header 43 * @arg port: new port value 44 * @arg old_port: old port value (for checksum correction) 45 * 46 * Overwrites a TCP or UDP port with new value and fixes up the checksum 47 * in the L4 header and of ctx->csum. 48 * 49 * NOTE: Calling this function will invalidate any pkt context offset 50 * validation for direct packet access. 51 * 52 * Return 0 on success or a negative DROP_* reason 53 */ 54 static __always_inline int l4_modify_port(struct __ctx_buff *ctx, int l4_off, 55 int off, struct csum_offset *csum_off, 56 __be16 port, __be16 old_port) 57 { 58 if (csum_l4_replace(ctx, l4_off, csum_off, old_port, port, sizeof(port)) < 0) 59 return DROP_CSUM_L4; 60 61 if (ctx_store_bytes(ctx, l4_off + off, &port, sizeof(port), 0) < 0) 62 return DROP_WRITE_ERROR; 63 64 return 0; 65 } 66 67 static __always_inline int l4_load_port(struct __ctx_buff *ctx, int off, 68 __be16 *port) 69 { 70 return ctx_load_bytes(ctx, off, port, sizeof(__be16)); 71 } 72 73 static __always_inline int l4_load_ports(struct __ctx_buff *ctx, int off, 74 __be16 *ports) 75 { 76 return ctx_load_bytes(ctx, off, ports, 2 * sizeof(__be16)); 77 } 78 79 static __always_inline int l4_load_tcp_flags(struct __ctx_buff *ctx, int l4_off, 80 union tcp_flags *flags) 81 { 82 return ctx_load_bytes(ctx, l4_off + 12, flags, 2); 83 }