Revert "flowtop: Don't init screen until collector is ready"
[netsniff-ng.git] / lookup.c
blob36d03da538464ee15fd99da7620670a473063828
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 <string.h>
10 #include "hash.h"
11 #include "str.h"
12 #include "lookup.h"
13 #include "xmalloc.h"
15 static struct hash_table lookup_port_tables[PORTS_MAX];
16 static const char * const lookup_port_files[] = {
17 [PORTS_UDP] = ETCDIRE_STRING "/udp.conf",
18 [PORTS_TCP] = ETCDIRE_STRING "/tcp.conf",
19 [PORTS_ETHER] = ETCDIRE_STRING "/ether.conf",
22 struct port {
23 unsigned int id;
24 char *port;
25 struct port *next;
28 void lookup_init_ports(enum ports which)
30 FILE *fp;
31 char buff[128], *ptr, *end;
32 const char *file;
33 struct hash_table *table;
34 struct port *p;
35 void **pos;
37 bug_on(which >= PORTS_MAX);
38 table = &lookup_port_tables[which];
39 file = lookup_port_files[which];
41 fp = fopen(file, "r");
42 if (!fp)
43 panic("No %s found!\n", file);
45 memset(buff, 0, sizeof(buff));
47 while (fgets(buff, sizeof(buff), fp) != NULL) {
48 buff[sizeof(buff) - 1] = 0;
49 ptr = buff;
51 p = xmalloc(sizeof(*p));
52 p->id = strtol(ptr, &end, 0);
53 /* not a valid line, skip */
54 if (p->id == 0 && end == ptr) {
55 xfree(p);
56 continue;
59 ptr = strstr(buff, ", ");
60 /* likewise */
61 if (!ptr) {
62 xfree(p);
63 continue;
66 ptr += strlen(", ");
67 ptr = strtrim_right(ptr, '\n');
68 ptr = strtrim_right(ptr, ' ');
70 p->port = xstrdup(ptr);
71 p->next = NULL;
73 pos = insert_hash(p->id, p, table);
74 if (pos) {
75 p->next = *pos;
76 *pos = p;
79 memset(buff, 0, sizeof(buff));
82 fclose(fp);
85 static int __lookup_cleanup_single(void *ptr)
87 struct port *tmp, *p = ptr;
89 if (!ptr)
90 return 0;
92 while ((tmp = p->next)) {
93 xfree(p->port);
94 xfree(p);
95 p = tmp;
98 xfree(p->port);
99 xfree(p);
101 return 0;
104 void lookup_cleanup_ports(enum ports which)
106 struct hash_table *table;
108 bug_on(which >= PORTS_MAX);
109 table = &lookup_port_tables[which];
111 for_each_hash(table, __lookup_cleanup_single);
112 free_hash(table);
115 #define __do_lookup_inline(id, struct_name, hash_ptr, struct_member) \
116 ({ \
117 struct struct_name *entry = lookup_hash(id, hash_ptr); \
119 while (entry && id != entry->id) \
120 entry = entry->next; \
122 (entry && id == entry->id ? entry->struct_member : NULL); \
125 char *lookup_ether_type(unsigned int id)
127 return __do_lookup_inline(id, port, &lookup_port_tables[PORTS_ETHER], port);
130 char *lookup_port_udp(unsigned int id)
132 return __do_lookup_inline(id, port, &lookup_port_tables[PORTS_UDP], port);
135 char *lookup_port_tcp(unsigned int id)
137 return __do_lookup_inline(id, port, &lookup_port_tables[PORTS_TCP], port);