curvetun, astraceroute: don't show header as in netsniff-ng
[netsniff-ng.git] / trie.c
bloba74d710a430091c7ea2af92ff4ad3ba41cb252ae
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * By Daniel Borkmann <daniel@netsniff-ng.org>
4 * Copyright 2011 Daniel Borkmann.
5 * Subject to the GPL, version 2.
6 */
8 #include <stdint.h>
9 #include <string.h>
10 #include <netinet/in.h>
12 #include "patricia.h"
13 #include "locking.h"
14 #include "trie.h"
15 #include "ipv4.h"
16 #include "ipv6.h"
18 static struct patricia_node *tree = NULL;
20 static struct rwlock tree_lock;
22 void trie_addr_lookup(char *buff, size_t len, int ipv4, int *fd,
23 struct sockaddr_storage *addr, size_t *alen)
25 void *data;
26 size_t dlen;
27 struct ipv4hdr *hdr4 = (void *) buff;
28 struct ipv6hdr *hdr6 = (void *) buff;
30 data = ipv4 ? (void *) &hdr4->h_daddr : (void *) &hdr6->daddr;
31 dlen = ipv4 ? sizeof(hdr4->h_daddr) : sizeof(hdr6->daddr);
33 if (unlikely((ipv4 && ((struct ipv4hdr *) buff)->h_version != 4) ||
34 (!ipv4 && ((struct ipv6hdr *) buff)->version != 6))) {
35 memset(addr, 0, sizeof(*addr));
36 (*alen) = 0;
37 (*fd) = -1;
38 return;
41 rwlock_rd_lock(&tree_lock);
42 (*fd) = ptree_search_data_exact(data, dlen, addr, alen, tree);
43 rwlock_unlock(&tree_lock);
46 int trie_addr_maybe_update(char *buff, size_t len, int ipv4, int fd,
47 struct sockaddr_storage *addr, size_t alen)
49 int ret;
50 void *data;
51 size_t dlen;
52 struct ipv4hdr *hdr4 = (void *) buff;
53 struct ipv6hdr *hdr6 = (void *) buff;
55 data = ipv4 ? (void *) &hdr4->h_saddr : (void *) &hdr6->saddr;
56 dlen = ipv4 ? sizeof(hdr4->h_saddr) : sizeof(hdr6->saddr);
58 if (unlikely((ipv4 && ((struct ipv4hdr *) buff)->h_version != 4) ||
59 (!ipv4 && ((struct ipv6hdr *) buff)->version != 6)))
60 return -1;
62 rwlock_wr_lock(&tree_lock);
63 ret = ptree_add_entry(data, dlen, fd, addr, alen, &tree);
64 rwlock_unlock(&tree_lock);
66 return ret;
69 void trie_addr_remove(int fd)
71 int found = 1;
72 struct patricia_node *n = NULL;
74 rwlock_wr_lock(&tree_lock);
76 while (found) {
77 ptree_get_key(fd, tree, &n);
78 if (n) {
79 ptree_del_entry(n->key, n->klen, &tree);
80 n = NULL;
81 } else
82 found = 0;
85 rwlock_unlock(&tree_lock);
88 void trie_addr_remove_addr(struct sockaddr_storage *addr, size_t alen)
90 int found = 1;
91 struct patricia_node *n = NULL;
93 rwlock_wr_lock(&tree_lock);
95 while (found) {
96 ptree_get_key_addr(addr, alen, tree, &n);
97 if (n) {
98 ptree_del_entry(n->key, n->klen, &tree);
99 n = NULL;
100 } else
101 found = 0;
104 rwlock_unlock(&tree_lock);
107 void trie_init(void)
109 rwlock_init(&tree_lock);
112 void trie_cleanup(void)
114 rwlock_wr_lock(&tree_lock);
115 ptree_free(tree);
116 rwlock_unlock(&tree_lock);
117 rwlock_destroy(&tree_lock);