netsniff-ng: add option to dump bpf assembly
[netsniff-ng.git] / pkt_buff.h
blobf86c01175a0ab3a2d3eac8730a87fa3e9909e9c4
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright (C) 2012 Christoph Jaeger <christoph@netsniff-ng.org>
4 * Subject to the GPL, version 2.
5 */
7 #ifndef PKT_BUFF_H
8 #define PKT_BUFF_H
10 #include "hash.h"
11 #include "built_in.h"
12 #include "proto.h"
13 #include "xmalloc.h"
15 struct pkt_buff {
16 /* invariant: head <= data <= tail */
17 uint8_t *head;
18 uint8_t *data;
19 uint8_t *tail;
20 unsigned int size;
22 struct protocol *proto;
25 static inline struct pkt_buff *pkt_alloc(uint8_t *packet, unsigned int len)
27 struct pkt_buff *pkt = xmalloc(sizeof(*pkt));
29 pkt->head = packet;
30 pkt->data = packet;
31 pkt->tail = packet + len;
32 pkt->size = len;
33 pkt->proto = NULL;
35 return pkt;
38 static inline void pkt_free(struct pkt_buff *pkt)
40 xfree(pkt);
43 static inline unsigned int pkt_len(struct pkt_buff *pkt)
45 bug_on(!pkt || pkt->data > pkt->tail);
47 return pkt->tail - pkt->data;
50 static inline uint8_t *pkt_pull(struct pkt_buff *pkt, unsigned int len)
52 uint8_t *data = NULL;
54 bug_on(!pkt || pkt->head > pkt->data || pkt->data > pkt->tail);
56 if (len <= pkt_len(pkt)) {
57 data = pkt->data;
58 pkt->data += len;
61 bug_on(!pkt || pkt->head > pkt->data || pkt->data > pkt->tail);
63 return data;
66 static inline uint8_t *pkt_peek(struct pkt_buff *pkt)
68 bug_on(!pkt || pkt->head > pkt->data || pkt->data > pkt->tail);
70 return pkt->data;
73 static inline unsigned int pkt_trim(struct pkt_buff *pkt, unsigned int len)
75 unsigned int ret = 0;
77 bug_on(!pkt || pkt->head > pkt->data || pkt->data > pkt->tail);
79 if (len <= pkt_len(pkt))
80 ret = len;
82 pkt->tail -= ret;
83 bug_on(!pkt || pkt->head > pkt->data || pkt->data > pkt->tail);
85 return ret;
88 static inline uint8_t *pkt_pull_tail(struct pkt_buff *pkt, unsigned int len)
90 uint8_t *tail = NULL;
92 bug_on(!pkt || pkt->head > pkt->data || pkt->data > pkt->tail);
94 if (len <= pkt_len(pkt)) {
95 tail = pkt->tail;
96 pkt->tail -= len;
99 return tail;
102 static inline void pkt_set_proto(struct pkt_buff *pkt, struct hash_table *table,
103 unsigned int key)
105 bug_on(!pkt || !table);
107 pkt->proto = (struct protocol *) lookup_hash(key, table);
108 while (pkt->proto && key != pkt->proto->key)
109 pkt->proto = pkt->proto->next;
112 #endif /* PKT_BUFF_H */