dissector: we're in default case anyways
[netsniff-ng.git] / trie.c
blob85277a89a74ec68cacc548d9e7613484375dbca3
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 /* Always happens on the dst address */
42 rwlock_rd_lock(&tree_lock);
43 (*fd) = ptree_search_data_exact(data, dlen, addr, alen, tree);
44 rwlock_unlock(&tree_lock);
47 int trie_addr_maybe_update(char *buff, size_t len, int ipv4, int fd,
48 struct sockaddr_storage *addr, size_t alen)
50 int ret;
51 void *data;
52 size_t dlen;
53 struct ipv4hdr *hdr4 = (void *) buff;
54 struct ipv6hdr *hdr6 = (void *) buff;
56 data = ipv4 ? (void *) &hdr4->h_saddr : (void *) &hdr6->saddr;
57 dlen = ipv4 ? sizeof(hdr4->h_saddr) : sizeof(hdr6->saddr);
59 if (unlikely((ipv4 && ((struct ipv4hdr *) buff)->h_version != 4) ||
60 (!ipv4 && ((struct ipv6hdr *) buff)->version != 6)))
61 return -1;
63 /* Always happens on the src address */
64 rwlock_wr_lock(&tree_lock);
65 ret = ptree_maybe_add_entry(data, dlen, fd, addr, alen, &tree);
66 rwlock_unlock(&tree_lock);
68 return ret;
71 void trie_addr_remove(int fd)
73 int found = 1;
74 struct patricia_node *n = NULL;
76 rwlock_wr_lock(&tree_lock);
78 while (found) {
79 ptree_get_key(fd, tree, &n);
80 if (n) {
81 ptree_del_entry(n->key, n->klen, &tree);
82 n = NULL;
83 } else
84 found = 0;
87 rwlock_unlock(&tree_lock);
90 void trie_addr_remove_addr(struct sockaddr_storage *addr, size_t alen)
92 int found = 1;
93 struct patricia_node *n = NULL;
95 rwlock_wr_lock(&tree_lock);
97 while (found) {
98 ptree_get_key_addr(addr, alen, tree, &n);
99 if (n) {
100 ptree_del_entry(n->key, n->klen, &tree);
101 n = NULL;
102 } else
103 found = 0;
106 rwlock_unlock(&tree_lock);
109 void trie_init(void)
111 rwlock_init(&tree_lock);
114 void trie_cleanup(void)
116 rwlock_wr_lock(&tree_lock);
117 ptree_free(tree);
118 rwlock_unlock(&tree_lock);
120 rwlock_destroy(&tree_lock);