str: Add converting cmdline args vector to str module
[netsniff-ng.git] / lookup.c
blob874a9b1d84ba2f98d9298064a435d7d0e352dbba
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2009, 2010 Daniel Borkmann.
4 * Copyright 2014 Tobias Klauser
5 * Subject to the GPL, version 2.
6 */
8 #include <errno.h>
9 #include <string.h>
11 #include "hash.h"
12 #include "str.h"
13 #include "lookup.h"
14 #include "xmalloc.h"
16 static struct hash_table lookup_port_tables[PORTS_MAX];
17 static const char * const lookup_port_files[] = {
18 [PORTS_UDP] = ETCDIRE_STRING "/udp.conf",
19 [PORTS_TCP] = ETCDIRE_STRING "/tcp.conf",
20 [PORTS_ETHER] = ETCDIRE_STRING "/ether.conf",
23 struct port {
24 unsigned int id;
25 char *port;
26 struct port *next;
29 void lookup_init_ports(enum ports which)
31 FILE *fp;
32 char buff[128], *ptr, *end;
33 const char *file;
34 struct hash_table *table;
35 struct port *p;
36 void **pos;
38 bug_on(which >= PORTS_MAX);
39 table = &lookup_port_tables[which];
40 file = lookup_port_files[which];
42 fp = fopen(file, "r");
43 if (!fp) {
44 fprintf(stderr, "Cannot open %s: %s."
45 "Port name resolution won't be available.\n",
46 file, strerror(errno));
47 return;
50 memset(buff, 0, sizeof(buff));
52 while (fgets(buff, sizeof(buff), fp) != NULL) {
53 buff[sizeof(buff) - 1] = 0;
54 ptr = buff;
56 p = xmalloc(sizeof(*p));
57 p->id = strtol(ptr, &end, 0);
58 /* not a valid line, skip */
59 if (p->id == 0 && end == ptr) {
60 xfree(p);
61 continue;
64 ptr = strstr(buff, ", ");
65 /* likewise */
66 if (!ptr) {
67 xfree(p);
68 continue;
71 ptr += strlen(", ");
72 ptr = strtrim_right(ptr, '\n');
73 ptr = strtrim_right(ptr, ' ');
75 p->port = xstrdup(ptr);
76 p->next = NULL;
78 pos = insert_hash(p->id, p, table);
79 if (pos) {
80 p->next = *pos;
81 *pos = p;
84 memset(buff, 0, sizeof(buff));
87 fclose(fp);
90 static int __lookup_cleanup_single(void *ptr)
92 struct port *tmp, *p = ptr;
94 if (!ptr)
95 return 0;
97 while ((tmp = p->next)) {
98 xfree(p->port);
99 xfree(p);
100 p = tmp;
103 xfree(p->port);
104 xfree(p);
106 return 0;
109 void lookup_cleanup_ports(enum ports which)
111 struct hash_table *table;
113 bug_on(which >= PORTS_MAX);
114 table = &lookup_port_tables[which];
116 for_each_hash(table, __lookup_cleanup_single);
117 free_hash(table);
120 #define __do_lookup_inline(id, struct_name, hash_ptr, struct_member) \
121 ({ \
122 struct struct_name *entry = lookup_hash(id, hash_ptr); \
124 while (entry && id != entry->id) \
125 entry = entry->next; \
127 (entry && id == entry->id ? entry->struct_member : NULL); \
130 char *lookup_ether_type(unsigned int id)
132 return __do_lookup_inline(id, port, &lookup_port_tables[PORTS_ETHER], port);
135 char *lookup_port_udp(unsigned int id)
137 return __do_lookup_inline(id, port, &lookup_port_tables[PORTS_UDP], port);
140 char *lookup_port_tcp(unsigned int id)
142 return __do_lookup_inline(id, port, &lookup_port_tables[PORTS_TCP], port);