Simplify the code

- We can use the structure not only to read the packet but also to modify it
 - Binary OR/AND are done with single chars, eg. & or | while logical OR/AND are done with 2 chars, eg. && or ||
This commit is contained in:
Quentin 2021-04-25 11:11:03 +02:00
parent 0924655e4b
commit 70aee3087b
Signed by: quentin
GPG Key ID: A98E9B769E4FF428
1 changed files with 12 additions and 24 deletions

View File

@ -31,35 +31,23 @@ int xdp_udp_func(struct xdp_md *ctx)
void *data_end = (void *)(long)ctx->data_end;
void *data = (void *)(long)ctx->data;
unsigned short mask = 0x4000;//0b 0100 0000 0000 0000
int DF_offset = 21;
struct ethhdr *eth = data; //structure ethernet from if_ether.h
int rc = XDP_PASS; // return code
int ipsize;
__u16 header_proto; __u64 length_header_eth;
length_header_eth = sizeof(*eth);//length in bits of header eth
// Check that our packet ethernet headers is big enough, ie. at least the size of Ethernet's fixed headers
if((void*)(eth + 1) > data_end) {
return XDP_PASS;
}
if(data + length_header_eth > data_end)//monitor the bound data
return rc;
header_proto = eth->h_proto;
//Enter only if it's IPV4
if(header_proto == bpf_htons(ETH_P_IP))
{
//We monitor protocol IPV4, we want only UDP packet
struct iphdr *ip = data + length_header_eth;
ipsize = sizeof(struct iphdr);
if(ip + ipsize > data_end) {
return rc;
// Check that the ethernet header declares an IPv4 packet
if(eth->h_proto == bpf_htons(ETH_P_IP)) {
struct iphdr *ip = (struct iphdr*)(eth + 1);
// Check that the IP packet is big enough, ie. at least the size of IP's fixed headers
if((void*)(ip + 1) > data_end) {
return XDP_PASS;
}
if(ip->protocol == IPPROTO_UDP) {
//On souhaite modifier le 21eme byte
// Unsigned short fait 2 bytes
unsigned short *p = data + DF_offset +1 ;
if(p > data_end) return rc;
p[0] = p[0] || mask;
ip->frag_off |= 0x4000; //Set the DF flag to 1 -> 0b 0100 0000 0000 0000
}
}