netsniff-ng: Rotate pcap files prematurely on SIGHUP
[netsniff-ng.git] / pkt_buff.h
blob13503885f794349433424c355b5c725d389cf1ca
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;
23 int link_type;
26 static inline struct pkt_buff *pkt_alloc(uint8_t *packet, unsigned int len)
28 struct pkt_buff *pkt = xmalloc(sizeof(*pkt));
30 pkt->head = packet;
31 pkt->data = packet;
32 pkt->tail = packet + len;
33 pkt->size = len;
34 pkt->proto = NULL;
36 return pkt;
39 static inline void pkt_free(struct pkt_buff *pkt)
41 xfree(pkt);
44 static inline unsigned int pkt_len(struct pkt_buff *pkt)
46 bug_on(!pkt || pkt->data > pkt->tail);
48 return pkt->tail - pkt->data;
51 static inline uint8_t *pkt_pull(struct pkt_buff *pkt, unsigned int len)
53 uint8_t *data = NULL;
55 bug_on(!pkt || pkt->head > pkt->data || pkt->data > pkt->tail);
57 if (len <= pkt_len(pkt)) {
58 data = pkt->data;
59 pkt->data += len;
62 bug_on(!pkt || pkt->head > pkt->data || pkt->data > pkt->tail);
64 return data;
67 static inline uint8_t *pkt_peek(struct pkt_buff *pkt)
69 bug_on(!pkt || pkt->head > pkt->data || pkt->data > pkt->tail);
71 return pkt->data;
74 static inline unsigned int pkt_trim(struct pkt_buff *pkt, unsigned int len)
76 unsigned int ret = 0;
78 bug_on(!pkt || pkt->head > pkt->data || pkt->data > pkt->tail);
80 if (len <= pkt_len(pkt))
81 ret = len;
83 pkt->tail -= ret;
84 bug_on(!pkt || pkt->head > pkt->data || pkt->data > pkt->tail);
86 return ret;
89 static inline uint8_t *pkt_pull_tail(struct pkt_buff *pkt, unsigned int len)
91 uint8_t *tail = NULL;
93 bug_on(!pkt || pkt->head > pkt->data || pkt->data > pkt->tail);
95 if (len <= pkt_len(pkt)) {
96 tail = pkt->tail;
97 pkt->tail -= len;
100 return tail;
103 static inline void pkt_set_proto(struct pkt_buff *pkt, struct hash_table *table,
104 unsigned int key)
106 bug_on(!pkt || !table);
108 pkt->proto = lookup_hash(key, table);
109 while (pkt->proto && key != pkt->proto->key)
110 pkt->proto = pkt->proto->next;
113 #endif /* PKT_BUFF_H */