lookup: Make lookup type and function names more generic
[netsniff-ng.git] / lookup.c
blobf903fe67402eac260d9384fbfbb0a42e317ac572
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2009, 2010 Daniel Borkmann.
4 * Copyright 2014, 2015 Tobias Klauser
5 * Subject to the GPL, version 2.
6 */
8 #include <errno.h>
9 #include <stdbool.h>
10 #include <stdio.h>
11 #include <string.h>
13 #include "hash.h"
14 #include "str.h"
15 #include "lookup.h"
16 #include "xmalloc.h"
18 static struct hash_table lookup_port_tables[LT_MAX];
19 static const char * const lookup_port_files[] = {
20 [LT_PORTS_UDP] = ETCDIRE_STRING "/udp.conf",
21 [LT_PORTS_TCP] = ETCDIRE_STRING "/tcp.conf",
22 [LT_ETHERTYPES] = ETCDIRE_STRING "/ether.conf",
25 struct lookup_entry {
26 unsigned int id;
27 char *str;
28 struct lookup_entry *next;
31 void lookup_init(enum lookup_type which)
33 FILE *fp;
34 char buff[128], *ptr, *end;
35 const char *file;
36 struct hash_table *table;
37 struct lookup_entry *p;
38 void **pos;
40 bug_on(which >= LT_MAX);
41 table = &lookup_port_tables[which];
42 file = lookup_port_files[which];
44 fp = fopen(file, "r");
45 if (!fp) {
46 fprintf(stderr, "Cannot open %s: %s."
47 "Port name resolution won't be available.\n",
48 file, strerror(errno));
49 return;
52 memset(buff, 0, sizeof(buff));
54 while (fgets(buff, sizeof(buff), fp) != NULL) {
55 buff[sizeof(buff) - 1] = 0;
56 ptr = buff;
58 p = xmalloc(sizeof(*p));
59 p->id = strtol(ptr, &end, 0);
60 /* not a valid line, skip */
61 if (p->id == 0 && end == ptr) {
62 xfree(p);
63 continue;
66 ptr = strstr(buff, ", ");
67 /* likewise */
68 if (!ptr) {
69 xfree(p);
70 continue;
73 ptr += strlen(", ");
74 ptr = strtrim_right(ptr, '\n');
75 ptr = strtrim_right(ptr, ' ');
77 p->str = xstrdup(ptr);
78 p->next = NULL;
80 pos = insert_hash(p->id, p, table);
81 if (pos) {
82 p->next = *pos;
83 *pos = p;
86 memset(buff, 0, sizeof(buff));
89 fclose(fp);
92 static int __lookup_cleanup_single(void *ptr)
94 struct lookup_entry *tmp, *p = ptr;
96 if (!ptr)
97 return 0;
99 while ((tmp = p->next)) {
100 xfree(p->str);
101 xfree(p);
102 p = tmp;
105 xfree(p->str);
106 xfree(p);
108 return 0;
111 void lookup_cleanup(enum lookup_type which)
113 struct hash_table *table;
115 bug_on(which >= LT_MAX);
116 table = &lookup_port_tables[which];
118 for_each_hash(table, __lookup_cleanup_single);
119 free_hash(table);
122 #define __do_lookup_inline(id, hash_ptr) \
123 ({ \
124 struct lookup_entry *entry = lookup_hash(id, hash_ptr); \
126 while (entry && id != entry->id) \
127 entry = entry->next; \
129 (entry && id == entry->id ? entry->str : NULL); \
132 char *lookup_ether_type(unsigned int id)
134 return __do_lookup_inline(id, &lookup_port_tables[LT_ETHERTYPES]);
137 char *lookup_port_udp(unsigned int id)
139 return __do_lookup_inline(id, &lookup_port_tables[LT_PORTS_UDP]);
142 char *lookup_port_tcp(unsigned int id)
144 return __do_lookup_inline(id, &lookup_port_tables[LT_PORTS_TCP]);