trafgen: proto: Fix bad field masking
[netsniff-ng.git] / trafgen_l3.c
blob0e923e0c5521c2b858d08ad2d7ccae2345a6dc9e
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Subject to the GPL, version 2.
4 */
6 #include <linux/if_ether.h>
8 #include "die.h"
9 #include "csum.h"
10 #include "built_in.h"
11 #include "trafgen_l2.h"
12 #include "trafgen_l3.h"
13 #include "trafgen_proto.h"
14 #include "trafgen_conf.h"
16 static struct proto_field ipv4_fields[] = {
17 { .id = IP4_VER, .len = 1, .offset = 0, .shift = 4, .mask = 0xf0 },
18 { .id = IP4_IHL, .len = 1, .offset = 0, .shift = 0, .mask = 0x0f },
19 { .id = IP4_DSCP, .len = 1, .offset = 1, .shift = 2, .mask = 0xfc },
20 { .id = IP4_ECN, .len = 1, .offset = 1, .shift = 0, .mask = 0x03 },
21 { .id = IP4_TOS, .len = 1, .offset = 1 },
22 { .id = IP4_LEN, .len = 2, .offset = 2 },
23 { .id = IP4_ID, .len = 2, .offset = 4 },
24 { .id = IP4_FLAGS, .len = 2, .offset = 6, .shift = 13, .mask = 0xe000 },
25 { .id = IP4_MF, .len = 2, .offset = 6, .shift = 13, .mask = 0x2000 },
26 { .id = IP4_DF, .len = 2, .offset = 6, .shift = 14, .mask = 0x4000 },
27 { .id = IP4_FRAG_OFFS, .len = 2, .offset = 6, .shift = 0, .mask = 0x1fff },
28 { .id = IP4_TTL, .len = 1, .offset = 8 },
29 { .id = IP4_PROTO, .len = 1, .offset = 9 },
30 { .id = IP4_CSUM, .len = 2, .offset = 10 },
31 { .id = IP4_SADDR, .len = 4, .offset = 12 },
32 { .id = IP4_DADDR, .len = 4, .offset = 16 },
35 static void ipv4_header_init(struct proto_hdr *hdr)
37 proto_lower_default_add(hdr, PROTO_ETH);
39 proto_header_fields_add(hdr, ipv4_fields, array_size(ipv4_fields));
41 proto_field_set_default_u8(hdr, IP4_VER, 4);
42 proto_field_set_default_u8(hdr, IP4_IHL, 5);
43 proto_field_set_default_dev_ipv4(hdr, IP4_SADDR);
46 static void ipv4_packet_finish(struct proto_hdr *hdr)
48 struct packet *pkt = current_packet();
49 uint16_t total_len;
51 total_len = pkt->len - hdr->pkt_offset;
52 proto_field_set_default_be16(hdr, IP4_LEN, total_len);
54 if (!proto_field_is_set(hdr, IP4_CSUM)) {
55 uint16_t csum;
56 uint8_t ihl;
58 ihl = proto_field_get_u8(hdr, IP4_IHL);
59 csum = htons(calc_csum(&pkt->payload[hdr->pkt_offset], ihl * 4));
60 proto_field_set_u16(hdr, IP4_CSUM, bswap_16(csum));
64 static void ipv4_set_next_proto(struct proto_hdr *hdr, enum proto_id pid)
66 uint8_t ip_proto;
68 switch(pid) {
69 case PROTO_IP4:
70 ip_proto = IPPROTO_IPIP;
71 break;
72 case PROTO_UDP:
73 ip_proto = IPPROTO_UDP;
74 break;
75 case PROTO_TCP:
76 ip_proto = IPPROTO_TCP;
77 break;
78 default:
79 panic("ipv4: Not supported protocol id %u\n", pid);
82 proto_field_set_default_u8(hdr, IP4_PROTO, ip_proto);
85 static struct proto_hdr ipv4_hdr = {
86 .id = PROTO_IP4,
87 .layer = PROTO_L3,
88 .header_init = ipv4_header_init,
89 .packet_finish = ipv4_packet_finish,
90 .set_next_proto = ipv4_set_next_proto,
93 void protos_l3_init(void)
95 proto_header_register(&ipv4_hdr);