eliminate the data field from an avl_node
[olsrd.git] / lib / nameservice / src / nameservice.c
1 /*
2  * Copyright (c) 2006, Jens Nachtigall <nachtigall@web.de>
3  * Copyright (c) 2005, Bruno Randolf <bruno.randolf@4g-systems.biz>
4  * Copyright (c) 2004, Andreas T√łnnesen(andreto-at-olsr.org)
5  * Copyright (c) 2007, Sven-Ola <sven-ola@gmx.de>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without 
9  * modification, are permitted provided that the following conditions 
10  * are met:
11  *
12  * * Redistributions of source code must retain the above copyright notice, 
13  *   this list of conditions and the following disclaimer.
14  * * Redistributions in binary form must reproduce the above copyright notice, 
15  *   this list of conditions and the following disclaimer in the documentation 
16  *   and/or other materials provided with the distribution.
17  * * Neither the name of the UniK olsr daemon nor the names of its contributors 
18  *   may be used to endorse or promote products derived from this software 
19  *   without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
23  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
24  * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
25  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
28  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
29  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
30  * OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  */
33
34
35 /*
36  * Dynamic linked library for UniK OLSRd
37  */
38
39 #include <stdio.h>
40 #include <string.h>
41 #include <stdlib.h>
42 #include <unistd.h>
43 #include <ctype.h>
44 #include <sys/types.h>
45 #include <regex.h>
46
47 #include "olsr.h"
48 #include "ipcalc.h"
49 #include "net_olsr.h"
50 #include "routing_table.h"
51 #include "mantissa.h"
52 #include "scheduler.h"
53 #include "parser.h"
54 #include "duplicate_set.h"
55 #include "tc_set.h"
56 #include "hna_set.h"
57 #include "mid_set.h"
58 #include "link_set.h"
59
60 #include "plugin_util.h"
61 #include "nameservice.h"
62 #include "mapwrite.h"
63 #include "compat.h"
64
65
66 /* config parameters */
67 static char my_hosts_file[MAX_FILE + 1];
68 static char my_add_hosts[MAX_FILE + 1];
69 static char my_suffix[MAX_SUFFIX];
70 static int my_interval = EMISSION_INTERVAL;
71 static double my_timeout = NAME_VALID_TIME;
72 static char my_resolv_file[MAX_FILE +1];
73 static char my_services_file[MAX_FILE + 1];
74 static char latlon_in_file[MAX_FILE + 1];
75 static char my_latlon_file[MAX_FILE + 1];
76 float my_lat = 0.0, my_lon = 0.0;
77
78 /* the databases (using hashing)
79  * for hostnames, service_lines and dns-servers
80  *
81  * my own hostnames, service_lines and dns-servers
82  * are store in a linked list (without hashing)
83  * */
84 static struct list_node list[HASHSIZE];
85 struct name_entry *my_names = NULL;
86 struct timer_entry *name_table_write = NULL;
87 static olsr_bool name_table_changed = OLSR_TRUE;
88
89 static struct list_node service_list[HASHSIZE];
90 static struct name_entry *my_services = NULL;
91 static olsr_bool service_table_changed = OLSR_TRUE;
92
93 static struct list_node forwarder_list[HASHSIZE];
94 static struct name_entry *my_forwarders = NULL;
95 static olsr_bool forwarder_table_changed = OLSR_TRUE;
96
97 struct list_node latlon_list[HASHSIZE];
98 static olsr_bool latlon_table_changed = OLSR_TRUE;
99
100 /* backoff timer for writing changes into a file */
101 struct timer_entry *write_file_timer = NULL;
102
103 /* periodic message generation */
104 struct timer_entry *msg_gen_timer = NULL;
105
106 /* regular expression to be matched by valid hostnames, compiled in name_init() */
107 static regex_t regex_t_name;
108 static regmatch_t regmatch_t_name;
109
110 /* regular expression to be matched by valid service_lines, compiled in name_init() */
111 static regex_t regex_t_service;
112 static int pmatch_service = 10;
113 static regmatch_t regmatch_t_service[10];
114
115 /**
116  * do initialization
117  */
118 void
119 name_constructor(void) 
120 {
121         int i;
122         
123 #ifdef WIN32
124         int len;
125
126         GetWindowsDirectory(my_hosts_file, MAX_FILE - 12);
127         GetWindowsDirectory(my_services_file, MAX_FILE - 12);
128         GetWindowsDirectory(my_resolv_file, MAX_FILE - 12);
129
130         len = strlen(my_hosts_file);
131         if (my_hosts_file[len - 1] != '\\')
132                 my_hosts_file[len++] = '\\';
133         strcpy(my_hosts_file + len, "hosts_olsr");
134         
135         len = strlen(my_services_file);
136         if (my_services_file[len - 1] != '\\')
137                 my_services_file[len++] = '\\';
138         strcpy(my_services_file + len, "services_olsr");
139
140         len = strlen(my_resolv_file);
141         if (my_resolv_file[len - 1] != '\\')
142                 my_resolv_file[len++] = '\\';
143         strcpy(my_resolv_file + len, "resolvconf_olsr");
144 #else
145         strcpy(my_hosts_file, "/var/run/hosts_olsr");
146         strcpy(my_services_file, "/var/run/services_olsr");
147         strcpy(my_resolv_file, "/var/run/resolvconf_olsr");
148 #endif
149
150         my_suffix[0] = '\0';
151         my_add_hosts[0] = '\0';
152         my_latlon_file[0] = '\0';
153         latlon_in_file[0] = '\0';
154         
155         /* init the lists heads */
156         for(i = 0; i < HASHSIZE; i++) {
157                 list_head_init(&list[i]);
158                 list_head_init(&forwarder_list[i]);
159                 list_head_init(&service_list[i]);
160                 list_head_init(&latlon_list[i]);
161         }
162         
163
164 }
165
166
167 static int set_nameservice_server(const char *value, void *data, set_plugin_parameter_addon addon)
168 {
169         union olsr_ip_addr ip;
170         struct name_entry **v = data;
171         if (0 == strlen(value))
172         {
173                 *v = add_name_to_list(*v, "", addon.ui, NULL);
174                 OLSR_PRINTF(1, "%s got %s (main address)\n", "Got", value);
175                 return 0;
176         }
177         else if (0 < inet_pton(olsr_cnf->ip_version, value, &ip))
178         {
179                 *v = add_name_to_list(*v, "", addon.ui, &ip);
180                 OLSR_PRINTF(1, "%s got %s\n", "Got", value);
181                 return 0;
182         }
183         else
184         {
185                 OLSR_PRINTF(0, "Illegal IP address \"%s\"", value);
186         }
187         return 1;
188 }
189
190 static int set_nameservice_name(const char *value, void *data, set_plugin_parameter_addon addon)
191 {
192         struct name_entry **v = data;
193         if (0 < strlen(value))
194         {
195                 *v = add_name_to_list(*v, value, addon.ui, NULL);
196                 OLSR_PRINTF(1, "%s got %s (main address)\n", "Got", value);
197                 return 0;
198         }
199         else
200         {
201                 OLSR_PRINTF(0, "Illegal name \"%s\"", value);
202         }
203         return 1;
204 }
205
206 static int set_nameservice_host(const char *value, void *data, set_plugin_parameter_addon addon)
207 {
208         union olsr_ip_addr ip;
209         struct name_entry **v = data;
210         if (0 < inet_pton(olsr_cnf->ip_version, addon.pc, &ip))
211         {
212                 // the IP is validated later
213                 *v = add_name_to_list(*v, value, NAME_HOST, &ip);
214                 OLSR_PRINTF(1, "%s: %s got %s\n", "Got", addon.pc, value);
215                 return 0;
216         }
217         else
218         {
219                 OLSR_PRINTF(0, "%s: Illegal IP address \"%s\"", addon.pc, value);
220         }
221         return 1;
222 }
223
224 static int set_nameservice_float(const char *value, void *data, set_plugin_parameter_addon addon __attribute__((unused)))
225 {
226         const float thefloat = atof(value);
227         if (data != NULL)
228         {
229                 float *v = data;
230                 *v = thefloat;
231                 OLSR_PRINTF(1, "%s float %f\n", "Got", thefloat);
232         }
233         else
234         {
235                 OLSR_PRINTF(0, "%s float %f\n", "Ignored", thefloat);
236         }
237         return 0;
238 }
239
240 static const struct olsrd_plugin_parameters plugin_parameters[] = {
241     { .name = "interval",      .set_plugin_parameter = &set_plugin_int,         .data = &my_interval },
242     { .name = "timeout",       .set_plugin_parameter = &set_nameservice_float,  .data = &my_timeout },
243     { .name = "hosts-file",    .set_plugin_parameter = &set_plugin_string,      .data = &my_hosts_file,    .addon = {sizeof(my_hosts_file)} },
244     { .name = "resolv-file",   .set_plugin_parameter = &set_plugin_string,      .data = &my_resolv_file,   .addon = {sizeof(my_resolv_file)} },
245     { .name = "suffix",        .set_plugin_parameter = &set_plugin_string,      .data = &my_suffix,        .addon = {sizeof(my_suffix)} },
246     { .name = "add-hosts",     .set_plugin_parameter = &set_plugin_string,      .data = &my_add_hosts,     .addon = {sizeof(my_add_hosts)} },
247     { .name = "services-file", .set_plugin_parameter = &set_plugin_string,      .data = &my_services_file, .addon = {sizeof(my_services_file)} },
248     { .name = "lat",           .set_plugin_parameter = &set_nameservice_float,  .data = &my_lat },
249     { .name = "lon",           .set_plugin_parameter = &set_nameservice_float,  .data = &my_lon },
250     { .name = "latlon-file",   .set_plugin_parameter = &set_plugin_string,      .data = &my_latlon_file,   .addon = {sizeof(my_latlon_file)} },
251     { .name = "latlon-infile", .set_plugin_parameter = &set_plugin_string,      .data = &latlon_in_file,   .addon = {sizeof(latlon_in_file)} },
252     { .name = "dns-server",    .set_plugin_parameter = &set_nameservice_server, .data = &my_forwarders,    .addon = {NAME_FORWARDER} },
253     { .name = "name",          .set_plugin_parameter = &set_nameservice_name,   .data = &my_names,         .addon = {NAME_HOST} },
254     { .name = "service",       .set_plugin_parameter = &set_nameservice_name,   .data = &my_services,      .addon = {NAME_SERVICE} },
255     { .name = "",              .set_plugin_parameter = &set_nameservice_host,   .data = &my_names },
256 };
257
258 void olsrd_get_plugin_parameters(const struct olsrd_plugin_parameters **params, int *size)
259 {
260         *params = plugin_parameters;
261         *size = sizeof(plugin_parameters)/sizeof(*plugin_parameters);
262 }
263
264
265 /**
266  * queue the name/forwarder/service given in value
267  * to the front of my_list
268  */
269 struct name_entry* 
270 add_name_to_list(struct name_entry *my_list, const char *value, int type, const union olsr_ip_addr *ip) 
271 {
272         struct name_entry *tmp = olsr_malloc(sizeof(struct name_entry), "new name_entry add_name_to_list");
273         tmp->name = strndup( value, MAX_NAME );
274         tmp->len = strlen( tmp->name );
275         tmp->type = type;
276         // all IPs with value 0 will be set to main_addr later
277         if (ip==NULL) 
278                 memset(&tmp->ip, 0, sizeof(tmp->ip));
279         else
280                 tmp->ip = *ip;
281         tmp->next = my_list;
282         return tmp;
283 }
284
285
286 /**
287  * last initialization
288  *
289  * we have to do this here because some things like main_addr 
290  * or the dns suffix (for validation) are not known before
291  *
292  * this is beause of the order in which the plugin is initialized 
293  * by the plugin loader:
294  *   - first the parameters are sent
295  *   - then register_olsr_data() from olsrd_plugin.c is called
296  *     which sets up main_addr and some other variables
297  *   - register_olsr_data() then then finally calls this function
298  */
299 int
300 name_init(void)
301 {
302         struct name_entry *name;
303         union olsr_ip_addr ipz;
304         int ret;
305
306         //regex string for validating the hostnames
307         const char *regex_name = "^[[:alnum:]_.-]+$";
308         //regex string for the service line
309         char *regex_service = olsr_malloc(256*sizeof(char) + strlen(my_suffix), "new *char from name_init for regex_service");
310         memset(&ipz, 0, sizeof(ipz));
311
312         //compile the regex from the string
313         if ((ret = regcomp(&regex_t_name, regex_name , REG_EXTENDED)) != 0)
314         {
315                 /* #2: call regerror() if regcomp failed 
316                  * commented out, because only for debuggin needed
317                  *
318                 int errmsgsz = regerror(ret, &regex_t_name, NULL, 0);
319                 char *errmsg = malloc(errmsgsz);
320                 regerror(ret, &regex_t_name, errmsg, errmsgsz);
321                 fprintf(stderr, "regcomp: %s", errmsg);
322                 free(errmsg);
323                 regfree(&regex_t_name);
324                 * */
325                 OLSR_PRINTF(0, "compilation of regex \"%s\" for hostname failed", regex_name);
326         }
327
328         // a service line is something like prot://hostname.suffix:port|tcp|my little description about this service
329         //                  for example     http://router.olsr:80|tcp|my homepage
330         //                     prot     ://  (hostname.suffix     OR         ip)
331         //regex_service = "^[[:alnum:]]+://(([[:alnum:]_.-]+.olsr)|([[:digit:]]{1,3}\\.[[:digit:]]{1,3}\\.[[:digit:]]{1,3}\\.[[:digit:]]{1,3}))
332         //                 :    port              /path      |(tcp OR udp) |short description
333         //                 :[[:digit:]]+[[:alnum:]/?._=#-]*\\|(tcp|udp)\\|[^|[:cntrl:]]+$";
334     strcpy(regex_service, "^[[:alnum:]]+://(([[:alnum:]_.-]+");
335     strcat(regex_service, my_suffix);
336         strcat(regex_service, ")|([[:digit:]]{1,3}\\.[[:digit:]]{1,3}\\.[[:digit:]]{1,3}\\.[[:digit:]]{1,3})):[[:digit:]]+[[:alnum:]/?._=#-]*\\|(tcp|udp)\\|[^|[:cntrl:]]+$");
337
338         /* #1: call regcomp() to compile the regex */
339         if ((ret = regcomp(&regex_t_service, regex_service , REG_EXTENDED )) != 0)
340         {
341                 /* #2: call regerror() if regcomp failed 
342                  * commented out, because only for debuggin needed
343                  *
344                 int errmsgsz = regerror(ret, &regex_t_service, NULL, 0);
345                 char *errmsg = malloc(errmsgsz);
346                 regerror(ret, &regex_t_service, errmsg, errmsgsz);
347                 fprintf(stderr, "regcomp: %s", errmsg);
348                 free(errmsg);
349                 regfree(&regex_t_service);
350                 * */
351                 OLSR_PRINTF(0, "compilation of regex \"%s\" for hostname failed", regex_name);
352         }
353         free(regex_service);
354         regex_service = NULL;
355
356         //fill in main addr for all entries with ip==0
357         //this does not matter for service, because the ip does not matter
358         //for service
359
360         for (name = my_names; name != NULL; name = name->next) {
361                 if (ipequal(&name->ip, &ipz)) {
362                         OLSR_PRINTF(2, "NAME PLUGIN: insert main addr for name %s \n", name->name);
363                         name->ip = olsr_cnf->main_addr;
364                 }
365         }
366         for (name = my_forwarders; name != NULL; name = name->next) {
367                 if (name->ip.v4.s_addr == 0) {
368                         OLSR_PRINTF(2, "NAME PLUGIN: insert main addr for name %s \n", name->name);
369                         name->ip = olsr_cnf->main_addr;
370                 }
371         }
372
373         //check if entries I want to announce myself are valid and allowed
374         my_names = remove_nonvalid_names_from_list(my_names, NAME_HOST);
375         my_forwarders = remove_nonvalid_names_from_list(my_forwarders, NAME_FORWARDER);
376         my_services = remove_nonvalid_names_from_list(my_services, NAME_SERVICE);
377
378
379         /* register functions with olsrd */
380         olsr_parser_add_function(&olsr_parser, PARSER_TYPE, 1);
381
382         /* periodic message generation */
383         msg_gen_timer = olsr_start_timer(my_interval * MSEC_PER_SEC, EMISSION_JITTER,
384                                                                          OLSR_TIMER_PERIODIC, &olsr_namesvc_gen,
385                                                                          NULL, 0);
386
387         mapwrite_init(my_latlon_file);
388
389         return 1;
390 }
391
392
393 struct name_entry*
394 remove_nonvalid_names_from_list(struct name_entry *my_list, int type) 
395 {
396         struct name_entry *next = my_list;
397         olsr_bool valid = OLSR_FALSE;
398         if (my_list == NULL) {
399                 return NULL;
400         } 
401
402         switch (type) {
403                 case NAME_HOST:
404                         valid = is_name_wellformed(my_list->name) && allowed_ip(&my_list->ip); 
405                         break;
406                 case NAME_FORWARDER:
407                         valid = allowed_ip(&my_list->ip);
408                         break;
409                 case NAME_SERVICE:
410                         valid = allowed_service(my_list->name);
411                         break;
412                 case NAME_LATLON:
413                         valid = is_latlon_wellformed(my_list->name);
414                         break;
415         }
416
417         if ( !valid  ) {
418 #ifndef NODEBUG
419                 struct ipaddr_str strbuf;
420 #endif
421                 OLSR_PRINTF(1, "NAME PLUGIN: invalid or malformed parameter %s (%s), fix your config!\n", my_list->name, olsr_ip_to_string(&strbuf, &my_list->ip));
422                 next = my_list->next;
423                 free(my_list->name);
424                 my_list->name = NULL;
425                 free(my_list);
426                 my_list = NULL;
427                 return remove_nonvalid_names_from_list(next, type);
428         } else {
429 #ifndef NODEBUG
430                 struct ipaddr_str strbuf;
431 #endif
432                 OLSR_PRINTF(2, "NAME PLUGIN: validate parameter %s (%s) -> OK\n", my_list->name, olsr_ip_to_string(&strbuf, &my_list->ip));
433                 my_list->next = remove_nonvalid_names_from_list(my_list->next, type);
434                 return my_list;
435         }
436 }
437
438
439
440 /**
441  * called at unload: free everything
442  *
443  * XXX: should I delete the hosts/services/resolv.conf files on exit?
444  */
445 void
446 name_destructor(void)
447 {
448         OLSR_PRINTF(2, "NAME PLUGIN: exit. cleaning up...\n");
449         
450         free_name_entry_list(&my_names);
451         free_name_entry_list(&my_services);
452         free_name_entry_list(&my_forwarders);
453
454         free_all_list_entries(list);
455         free_all_list_entries(service_list);
456         free_all_list_entries(forwarder_list);
457         free_all_list_entries(latlon_list);
458
459         olsr_stop_timer(write_file_timer);
460         olsr_stop_timer(msg_gen_timer);
461
462         regfree(&regex_t_name);
463         regfree(&regex_t_service);
464         mapwrite_exit();
465 }
466
467 /* free all list entries */
468 void 
469 free_all_list_entries(struct list_node *this_db_list) 
470 {
471         struct db_entry *db;
472         struct list_node *list_head, *list_node, *list_node_next;
473
474         int i;
475         
476         for (i = 0; i < HASHSIZE; i++) {
477
478                 list_head = &this_db_list[i];
479
480                 for (list_node = list_head->next;
481                          list_node != list_head;
482                          list_node = list_node_next) {
483
484                         /* prefetch next node before loosing context */
485                         list_node_next = list_node->next;
486
487                         db = list2db(list_node);
488                         olsr_namesvc_delete_db_entry(db);
489                 }
490         }
491 }
492
493
494 /**
495  * The write file timer has fired.
496  */
497 void
498 olsr_expire_write_file_timer(void *context __attribute__((unused)))
499 {
500         write_file_timer = NULL;
501
502         write_resolv_file();   /* if forwarder_table_changed */
503         write_hosts_file();    /* if name_table_changed */
504         write_services_file(); /* if service_table_changed */
505 #ifdef WIN32
506         write_latlon_file();   /* if latlon_table_changed */
507 #endif
508 }
509
510
511 /*
512  * Kick a timer to write everything into a file.
513  * This also paces things a bit.
514  */
515 static void
516 olsr_start_write_file_timer(void)
517 {
518         if (write_file_timer) {
519                 return;
520         }
521
522         write_file_timer = olsr_start_timer(5 * MSEC_PER_SEC, 5, OLSR_TIMER_ONESHOT,
523                                                                                 olsr_expire_write_file_timer, NULL, 0);
524 }
525
526 /*
527  * Delete and unlink db_entry.
528  */
529 void
530 olsr_namesvc_delete_db_entry(struct db_entry *db)
531 {
532 #ifndef NODEBUG
533         struct ipaddr_str strbuf;
534 #endif
535         OLSR_PRINTF(2, "NAME PLUGIN: %s timed out... deleting\n", 
536                                 olsr_ip_to_string(&strbuf, &db->originator));
537
538         olsr_start_write_file_timer();
539         olsr_stop_timer(db->db_timer); /* stop timer if running */
540         
541         /* Delete */
542         free_name_entry_list(&db->names);
543         list_remove(&db->db_list);
544         free(db);
545 }
546
547 /**
548  * Callback for the db validity timer.
549  */
550 static void
551 olsr_nameservice_expire_db_timer(void *context)
552 {
553   struct db_entry *db;
554
555   db = (struct db_entry *)context;
556   db->db_timer = NULL; /* be pedandic */
557
558   olsr_namesvc_delete_db_entry(db);
559 }
560
561 /**
562  * Scheduled event: generate and send NAME packet
563  */
564 void
565 olsr_namesvc_gen(void *foo __attribute__((unused)))
566 {
567         /* send buffer: huge */
568         char buffer[10240];
569         union olsr_message *message = (union olsr_message *)buffer;
570         struct interface *ifn;
571         int namesize;
572
573         /* fill message */
574         if(olsr_cnf->ip_version == AF_INET)
575         {
576                 /* IPv4 */
577                 message->v4.olsr_msgtype = MESSAGE_TYPE;
578                 message->v4.olsr_vtime = double_to_me(my_timeout);
579                 memcpy(&message->v4.originator, &olsr_cnf->main_addr, olsr_cnf->ipsize);
580                 message->v4.ttl = MAX_TTL;
581                 message->v4.hopcnt = 0;
582                 message->v4.seqno = htons(get_msg_seqno());
583
584                 namesize = encap_namemsg((struct namemsg*)&message->v4.message);
585                 namesize = namesize + sizeof(struct olsrmsg);
586
587                 message->v4.olsr_msgsize = htons(namesize);
588         }
589         else
590         {
591                 /* IPv6 */
592                 message->v6.olsr_msgtype = MESSAGE_TYPE;
593                 message->v6.olsr_vtime = double_to_me(my_timeout);
594                 memcpy(&message->v6.originator, &olsr_cnf->main_addr, olsr_cnf->ipsize);
595                 message->v6.ttl = MAX_TTL;
596                 message->v6.hopcnt = 0;
597                 message->v6.seqno = htons(get_msg_seqno());
598
599                 namesize = encap_namemsg((struct namemsg*)&message->v6.message);
600                 namesize = namesize + sizeof(struct olsrmsg6);
601                 
602                 message->v6.olsr_msgsize = htons(namesize);
603         }
604
605         /* looping trough interfaces */
606         for (ifn = ifnet; ifn ; ifn = ifn->int_next) 
607         {
608                 OLSR_PRINTF(3, "NAME PLUGIN: Generating packet - [%s]\n", ifn->int_name);
609
610                 if(net_outbuffer_push(ifn, message, namesize) != namesize ) {
611                         /* send data and try again */
612                         net_output(ifn);
613                         if(net_outbuffer_push(ifn, message, namesize) != namesize ) {
614                                 OLSR_PRINTF(1, "NAME PLUGIN: could not send on interface: %s\n", ifn->int_name);
615                         }
616                 }
617         }
618 }
619
620
621 /**
622  * Parse name olsr message of NAME type
623  */
624 void
625 olsr_parser(union olsr_message *m,
626                         struct interface *in_if __attribute__((unused)),
627                         union olsr_ip_addr *ipaddr)
628 {
629         struct namemsg *namemessage;
630         union olsr_ip_addr originator;
631         double vtime;
632         int size;
633         olsr_u16_t seqno;
634
635         /* Fetch the originator of the messsage */
636         if(olsr_cnf->ip_version == AF_INET) {
637                 memcpy(&originator, &m->v4.originator, olsr_cnf->ipsize);
638                 seqno = ntohs(m->v4.seqno);
639         } else {
640                 memcpy(&originator, &m->v6.originator, olsr_cnf->ipsize);
641                 seqno = ntohs(m->v6.seqno);
642         }
643                 
644         /* Fetch the message based on IP version */
645         if(olsr_cnf->ip_version == AF_INET) {
646                 vtime = me_to_double(m->v4.olsr_vtime);
647                 size = ntohs(m->v4.olsr_msgsize);
648                 namemessage = (struct namemsg*)&m->v4.message;
649         }
650         else {
651                 vtime = me_to_double(m->v6.olsr_vtime);
652                 size = ntohs(m->v6.olsr_msgsize);
653                 namemessage = (struct namemsg*)&m->v6.message;
654         }
655
656         /* Check if message originated from this node. 
657         If so - back off */
658         if(ipequal(&originator, &olsr_cnf->main_addr))
659                 return;
660
661         /* Check that the neighbor this message was received from is symmetric. 
662         If not - back off*/
663         if(check_neighbor_link(ipaddr) != SYM_LINK) {
664 #ifndef NODEBUG
665                 struct ipaddr_str strbuf;
666 #endif
667                 OLSR_PRINTF(3, "NAME PLUGIN: Received msg from NON SYM neighbor %s\n", olsr_ip_to_string(&strbuf, ipaddr));
668                 return;
669         }
670
671         update_name_entry(&originator, namemessage, size, vtime);
672
673         /* Forward the message if nessecary
674         * default_fwd does all the work for us! */
675         olsr_forward_message(m, ipaddr);
676 }
677
678 /**
679  * Encapsulate a name message into a packet. 
680  *
681  * It assumed that there is enough space in the buffer to do this!
682  *
683  * Returns: the length of the message that was appended
684  */
685 int
686 encap_namemsg(struct namemsg* msg)
687 {
688         struct name_entry *my_name;
689         struct name_entry *my_service;
690
691         // add the hostname, service and forwarder entries after the namemsg header
692         char* pos = (char*)msg + sizeof(struct namemsg);
693         short i=0;
694
695         // names
696         for (my_name = my_names; my_name!=NULL; my_name = my_name->next)
697         {
698                 pos = create_packet( (struct name*) pos, my_name);
699                 i++;
700         }
701         // forwarders
702         for (my_name = my_forwarders; my_name!=NULL; my_name = my_name->next)
703         {
704                 pos = create_packet( (struct name*) pos, my_name);
705                 i++;
706         }
707         // services
708         for (my_service = my_services; my_service!=NULL; my_service = my_service->next)
709         {
710                 pos = create_packet( (struct name*) pos, my_service);
711                 i++;
712         }
713         // latlon
714         if ('\0' != latlon_in_file[0])
715         {
716                 FILE* in = fopen( latlon_in_file, "r" );
717                 if (in != NULL) {
718                         fscanf(in, "%f,%f", &my_lat, &my_lon);
719                         fclose(in);
720                 }
721                 else
722                 {
723                         OLSR_PRINTF(0, "NAME PLUGIN: cant read latlon in file %s\n", latlon_in_file);
724                 }
725         }
726         if (0.0 != my_lat && 0.0 != my_lon)
727         {
728                 char s[64];
729                 struct name_entry e;
730                 memset(&e, 0, sizeof(e));
731                 sprintf(s, "%f,%f,%d", my_lat, my_lon, get_isdefhna_latlon());
732                 e.len = strlen(s);
733                 e.type = NAME_LATLON;
734                 e.name = s;
735                 lookup_defhna_latlon(&e.ip);
736                 pos = create_packet( (struct name*) pos, &e);
737                 i++;
738         }
739
740         // write the namemsg header with the number of announced entries and the protocol version
741         msg->nr_names = htons(i);
742         msg->version = htons(NAME_PROTOCOL_VERSION);
743
744         return pos - (char*)msg; //length
745 }
746
747
748 /**
749  * convert each of my to be announced name_entries into network
750  * compatible format
751  *
752  * return the length of the name packet
753  */
754 char*  
755 create_packet(struct name* to, struct name_entry *from)
756 {
757         char *pos = (char*) to;
758         int k;
759 #ifndef NODEBUG
760         struct ipaddr_str strbuf;
761 #endif
762         OLSR_PRINTF(3, "NAME PLUGIN: Announcing name %s (%s) %d\n", 
763                 from->name, olsr_ip_to_string(&strbuf, &from->ip), from->len);
764         to->type = htons(from->type);
765         to->len = htons(from->len);
766         to->ip = from->ip;
767         pos += sizeof(struct name);
768         strncpy(pos, from->name, from->len);
769         pos += from->len;
770         for (k = from->len; (k & 3) != 0; k++)
771                 *pos++ = '\0';
772         return pos;
773 }
774
775 /**
776  * decapsulate a received name, service or forwarder and update the corresponding hash table if necessary
777  */
778 void
779 decap_namemsg(struct name *from_packet, struct name_entry **to, olsr_bool *this_table_changed )
780 {
781 #ifndef NODEBUG
782         struct ipaddr_str strbuf;
783 #endif
784         struct name_entry *tmp;
785         struct name_entry *already_saved_name_entries;
786         char *name = (char*)from_packet + sizeof(struct name);
787         int type_of_from_packet = ntohs(from_packet->type);
788         unsigned int len_of_name = ntohs(from_packet->len);
789         OLSR_PRINTF(4, "NAME PLUGIN: decap type=%d, len=%d, name=%s\n",
790                 type_of_from_packet, len_of_name, name);
791
792         //XXX: should I check the from_packet->ip here? If so, why not also check the ip from HOST and SERVICE?
793         if( (type_of_from_packet==NAME_HOST && !is_name_wellformed(name)) ||
794                 (type_of_from_packet==NAME_SERVICE && !is_service_wellformed(name)) ||
795                 (type_of_from_packet==NAME_LATLON && !is_latlon_wellformed(name)))
796         {
797                 OLSR_PRINTF(4, "NAME PLUGIN: invalid name [%s] received, skipping.\n", name );
798                 return;
799         }
800
801         //ignore all packets with a too long name
802         //or a spoofed len of its included name string
803         if (len_of_name > MAX_NAME || strlen(name) != len_of_name || NULL != strchr(name, '\\') || NULL != strchr(name, '\'')) {
804                 OLSR_PRINTF(4, "NAME PLUGIN: from_packet->len %d > MAX_NAME %d or from_packet->len %d !0 strlen(name [%s] in packet)\n",
805                         len_of_name, MAX_NAME, len_of_name, name );
806                 return;
807         }
808
809         // don't insert the received entry again, if it has already been inserted in the hash table. 
810         // Instead only the validity time is set in insert_new_name_in_list function, which calls this one
811         for (already_saved_name_entries = (*to); already_saved_name_entries != NULL ; already_saved_name_entries = already_saved_name_entries->next)
812         {
813                 if ( (type_of_from_packet==NAME_HOST || type_of_from_packet==NAME_SERVICE) && strncmp(already_saved_name_entries->name, name, len_of_name) == 0 ) {
814                         OLSR_PRINTF(4, "NAME PLUGIN: received name or service entry %s (%s) already in hash table\n",
815                                 name, olsr_ip_to_string(&strbuf, &already_saved_name_entries->ip));
816                         return;
817                 } else if (type_of_from_packet==NAME_FORWARDER && ipequal(&already_saved_name_entries->ip, &from_packet->ip) ) {
818                         OLSR_PRINTF(4, "NAME PLUGIN: received forwarder entry %s (%s) already in hash table\n",
819                                 name, olsr_ip_to_string(&strbuf, &already_saved_name_entries->ip));
820                         return;
821                 } else if (type_of_from_packet==NAME_LATLON ) {
822                         if (0 != strncmp(already_saved_name_entries->name, name, len_of_name))
823                         {
824                                 OLSR_PRINTF(4, "NAME PLUGIN: updating name %s -> %s (%s)\n",
825                                         already_saved_name_entries->name, name,
826                                         olsr_ip_to_string(&strbuf, &already_saved_name_entries->ip));
827                                 free(already_saved_name_entries->name);
828                                 already_saved_name_entries->name = olsr_malloc(len_of_name + 1, "upd name_entry name");
829                                 strncpy(already_saved_name_entries->name, name, len_of_name);
830
831                                 *this_table_changed = OLSR_TRUE;
832                                 olsr_start_write_file_timer();
833                         }
834                         if (!ipequal(&already_saved_name_entries->ip, &from_packet->ip))
835                         {
836 #ifndef NODEBUG
837                                 struct ipaddr_str strbuf2, strbuf3;
838 #endif
839                                 OLSR_PRINTF(4, "NAME PLUGIN: updating ip %s -> %s (%s)\n",
840                                         olsr_ip_to_string(&strbuf, &already_saved_name_entries->ip),
841                                         olsr_ip_to_string(&strbuf2, &from_packet->ip),
842                                         olsr_ip_to_string(&strbuf3, &already_saved_name_entries->ip));
843                                 already_saved_name_entries->ip = from_packet->ip;
844
845                                 *this_table_changed = OLSR_TRUE;
846                                 olsr_start_write_file_timer();
847                         }
848                         if (!*this_table_changed)
849                         {
850                                 OLSR_PRINTF(4, "NAME PLUGIN: received latlon entry %s (%s) already in hash table\n",
851                                         name, olsr_ip_to_string(&strbuf, &already_saved_name_entries->ip));
852                         }
853                         return;
854                 }
855         }
856
857         //if not yet known entry 
858         tmp = olsr_malloc(sizeof(struct name_entry), "new name_entry");         
859         tmp->type = ntohs(from_packet->type);
860         tmp->len = len_of_name > MAX_NAME ? MAX_NAME : ntohs(from_packet->len);
861         tmp->name = olsr_malloc(tmp->len+1, "new name_entry name");
862         tmp->ip = from_packet->ip;
863         strncpy(tmp->name, name, tmp->len);
864         tmp->name[tmp->len] = '\0';
865
866         OLSR_PRINTF(3, "\nNAME PLUGIN: create new name/service/forwarder entry %s (%s) [len=%d] [type=%d] in linked list\n", 
867                 tmp->name, olsr_ip_to_string(&strbuf, &tmp->ip), tmp->len, tmp->type);
868
869         *this_table_changed = OLSR_TRUE;
870         olsr_start_write_file_timer();
871
872         // queue to front
873         tmp->next = *to;
874         *to = tmp;
875 }
876
877
878 /**
879  * unpack the received message and delegate to the decapsulation function for each
880  * name/service/forwarder entry in the message
881  */
882 void
883 update_name_entry(union olsr_ip_addr *originator, struct namemsg *msg, int msg_size, double vtime)
884 {
885 #ifndef NODEBUG
886         struct ipaddr_str strbuf;
887 #endif
888         char *pos, *end_pos;
889         struct name *from_packet; 
890         int i;
891
892         OLSR_PRINTF(3, "NAME PLUGIN: Received Message from %s\n", 
893                                 olsr_ip_to_string(&strbuf, originator));
894         
895         if (ntohs(msg->version) != NAME_PROTOCOL_VERSION) {
896                 OLSR_PRINTF(3, "NAME PLUGIN: ignoring wrong version %d\n", msg->version);
897                 return;
898         }
899         
900         /* now add the names from the message */
901         pos = (char*)msg + sizeof(struct namemsg);
902         end_pos = pos + msg_size - sizeof(struct name*); // at least one struct name has to be left     
903
904         for (i=ntohs(msg->nr_names); i > 0 && pos<end_pos; i--) 
905         {
906                 from_packet = (struct name*)pos;
907                 
908                 switch (ntohs(from_packet->type)) {
909                         case NAME_HOST: 
910                                 insert_new_name_in_list(originator, list, from_packet,
911                                                                                 &name_table_changed, vtime); 
912                                 break;
913                         case NAME_FORWARDER:
914                                 insert_new_name_in_list(originator, forwarder_list, from_packet,
915                                                                                 &forwarder_table_changed, vtime); 
916                                 break;
917                         case NAME_SERVICE:
918                                 insert_new_name_in_list(originator, service_list, from_packet,
919                                                                                 &service_table_changed, vtime); 
920                                 break;
921                         case NAME_LATLON:
922                                 insert_new_name_in_list(originator, latlon_list, from_packet,
923                                                                                 &latlon_table_changed, vtime);
924                                 break;
925                         default:
926                                 OLSR_PRINTF(3, "NAME PLUGIN: Received Message of unknown type [%d] from (%s)\n",
927                                                         from_packet->type, olsr_ip_to_string(&strbuf, originator));
928                                 break;
929                 }
930
931                 pos += sizeof(struct name);
932                 pos += 1 + (( ntohs(from_packet->len) - 1) | 3);
933         }
934         if (i!=0)
935                 OLSR_PRINTF(4, "NAME PLUGIN: Lost %d entries in received packet due to length inconsistency (%s)\n", i, olsr_ip_to_string(&strbuf, originator));
936 }
937
938
939 /**
940  * insert all the new names,services and forwarders from a received packet into the
941  * corresponding entry for this ip in the corresponding hash table
942  */
943 void
944 insert_new_name_in_list(union olsr_ip_addr *originator,
945                                                 struct list_node *this_list,
946                                                 struct name *from_packet, olsr_bool *this_table_changed,
947                                                 double vtime)
948 {
949         int hash;
950         struct db_entry *entry;
951         struct list_node *list_head, *list_node;
952
953         olsr_bool entry_found = OLSR_FALSE;
954
955         hash = olsr_ip_hashing(originator);
956
957         /* find the entry for originator, if there is already one */
958         list_head = &this_list[hash];
959         for (list_node = list_head->next; list_node != list_head;
960                  list_node = list_node->next) {
961
962                 entry = list2db(list_node);
963
964                 if (ipequal(originator, &entry->originator)) {
965 #ifndef NODEBUG
966                         struct ipaddr_str strbuf;
967 #endif
968                         // found
969                         OLSR_PRINTF(4, "NAME PLUGIN: found entry for (%s) in its hash table\n",
970                                                 olsr_ip_to_string(&strbuf, originator));
971
972                         //delegate to function for parsing the packet and linking it to entry->names
973                         decap_namemsg(from_packet, &entry->names, this_table_changed);
974
975                         olsr_set_timer(&entry->db_timer, vtime * MSEC_PER_SEC,
976                                                    OLSR_NAMESVC_DB_JITTER, OLSR_TIMER_ONESHOT,
977                                                    &olsr_nameservice_expire_db_timer, entry, 0);
978
979                         entry_found = OLSR_TRUE;
980                 }
981         }
982
983         if (! entry_found)
984         {
985 #ifndef NODEBUG
986                 struct ipaddr_str strbuf;
987 #endif
988                 OLSR_PRINTF(3, "NAME PLUGIN: create new db entry for ip (%s) in hash table\n",
989                                         olsr_ip_to_string(&strbuf, originator));
990
991                 /* insert a new entry */
992                 entry = olsr_malloc(sizeof(struct db_entry), "new db_entry");
993                 memset(entry, 0, sizeof(struct db_entry));
994
995                 entry->originator = *originator;
996
997                 olsr_set_timer(&entry->db_timer, vtime * MSEC_PER_SEC,
998                                            OLSR_LINK_LOSS_JITTER, OLSR_TIMER_ONESHOT,
999                                            &olsr_nameservice_expire_db_timer, entry, 0);
1000
1001                 entry->names = NULL;
1002
1003                 /* insert to the list */
1004                 list_add_before(&this_list[hash], &entry->db_list);
1005                 
1006                 //delegate to function for parsing the packet and linking it to entry->names
1007                 decap_namemsg(from_packet, &entry->names, this_table_changed);
1008         }
1009 }
1010
1011 /**
1012  * write names to a file in /etc/hosts compatible format
1013  */
1014 void
1015 write_hosts_file(void)
1016 {
1017         int hash;
1018         struct name_entry *name;
1019         struct db_entry *entry;
1020         struct list_node *list_head, *list_node;
1021         FILE* hosts;
1022         FILE* add_hosts;
1023         int c=0;
1024         time_t currtime;
1025
1026 #ifdef MID_ENTRIES
1027         struct mid_address *alias;
1028 #endif
1029
1030         if (!name_table_changed)
1031                 return;
1032
1033         OLSR_PRINTF(2, "NAME PLUGIN: writing hosts file\n");
1034
1035         hosts = fopen( my_hosts_file, "w" );
1036         if (hosts == NULL) {
1037                 OLSR_PRINTF(2, "NAME PLUGIN: cant write hosts file\n");
1038                 return;
1039         }
1040         
1041         fprintf(hosts, "### this /etc/hosts file is overwritten regularly by olsrd\n");
1042         fprintf(hosts, "### do not edit\n\n");
1043
1044         fprintf(hosts, "127.0.0.1\tlocalhost\n");
1045         fprintf(hosts, "::1\t\tlocalhost\n\n");
1046         
1047         // copy content from additional hosts filename
1048         if (my_add_hosts[0] != '\0') {
1049                 add_hosts = fopen( my_add_hosts, "r" );
1050                 if (add_hosts == NULL) {
1051                         OLSR_PRINTF(2, "NAME PLUGIN: cant open additional hosts file\n");
1052                 }
1053                 else {
1054                         fprintf(hosts, "### contents from '%s' ###\n\n", my_add_hosts);
1055                         while ((c = getc(add_hosts)) != EOF)
1056                                 putc(c, hosts);
1057                 }
1058                 fclose(add_hosts);              
1059                 fprintf(hosts, "\n### olsr names ###\n\n");
1060         }
1061         
1062         // write own names
1063         for (name = my_names; name != NULL; name = name->next) {
1064                 struct ipaddr_str strbuf;
1065                 fprintf(hosts, "%s\t%s%s\t# myself\n", olsr_ip_to_string(&strbuf, &name->ip), name->name, my_suffix );
1066         }
1067         
1068         // write received names
1069         for (hash = 0; hash < HASHSIZE; hash++) {
1070                 list_head = &list[hash];
1071                 for (list_node = list_head->next; list_node != list_head;
1072                          list_node = list_node->next) {
1073
1074                         entry = list2db(list_node);
1075
1076                         for (name = entry->names; name != NULL; name = name->next) {
1077                                 struct ipaddr_str strbuf;
1078                                 OLSR_PRINTF(
1079                                         6, "%s\t%s%s\t#%s\n",
1080                                         olsr_ip_to_string( &strbuf, &name->ip ), name->name, my_suffix,
1081                                         olsr_ip_to_string( &strbuf, &entry->originator )
1082                                         );
1083
1084                                 fprintf(
1085                                         hosts, "%s\t%s%s\t# %s\n",
1086                                         olsr_ip_to_string( &strbuf, &name->ip ), name->name, my_suffix,
1087                                         olsr_ip_to_string( &strbuf, &entry->originator )
1088                                         );
1089
1090 #ifdef MID_ENTRIES
1091                                 // write mid entries
1092                                 if( ( alias = mid_lookup_aliases( &name->ip ) ) != NULL )
1093                                 {
1094                                         unsigned short mid_num = 1;
1095                                         char       mid_prefix[MID_MAXLEN];
1096
1097                                         while( alias != NULL )
1098                                         {
1099                                                 struct ipaddr_str midbuf;
1100
1101                                                 // generate mid prefix
1102                                                 sprintf( mid_prefix, MID_PREFIX, mid_num );
1103
1104                                                 OLSR_PRINTF(
1105                                                         6, "%s\t%s%s%s\t# %s (mid #%i)\n",
1106                                                         olsr_ip_to_string( &midbuf, &alias->alias ),
1107                                                         mid_prefix, name->name, my_suffix,
1108                                                         olsr_ip_to_string( &strbuf, &entry->originator ),
1109                                                         mid_num
1110                                                         );
1111
1112                                                 fprintf(
1113                                                         hosts, "%s\t%s%s%s\t# %s (mid #%i)\n",
1114                                                         olsr_ip_to_string( &midbuf, &alias->alias ),
1115                                                         mid_prefix, name->name, my_suffix,
1116                                                         olsr_ip_to_string( &strbuf, &entry->originator ),
1117                                                         mid_num
1118                                                         );
1119
1120                                                 alias = alias->next_alias;
1121                                                 mid_num++;
1122                                         }
1123                                 }
1124 #endif
1125                         }
1126                 }
1127         }
1128
1129         if (time(&currtime)) {
1130                 fprintf(hosts, "\n### written by olsrd at %s", ctime(&currtime));
1131         }
1132           
1133         fclose(hosts);
1134         name_table_changed = OLSR_FALSE;
1135 }
1136
1137
1138 /**
1139  * write services to a file in the format:
1140  * service  #originator ip
1141  *
1142  * since service has a special format
1143  * each line will look similar to e.g.
1144  * http://me.olsr:80|tcp|my little homepage
1145  */
1146 void
1147 write_services_file(void)
1148 {
1149         int hash;
1150         struct name_entry *name;
1151         struct db_entry *entry;
1152         struct list_node *list_head, *list_node;
1153         FILE* services_file;
1154         time_t currtime;
1155
1156
1157         if (!service_table_changed)
1158                 return;
1159
1160         OLSR_PRINTF(2, "NAME PLUGIN: writing services file\n");
1161
1162         services_file = fopen( my_services_file, "w" );
1163         if (services_file == NULL) {
1164                 OLSR_PRINTF(2, "NAME PLUGIN: cant write services_file file\n");
1165                 return;
1166         }
1167         
1168         fprintf(services_file, "### this file is overwritten regularly by olsrd\n");
1169         fprintf(services_file, "### do not edit\n\n");
1170
1171         
1172         // write own services
1173         for (name = my_services; name != NULL; name = name->next) {
1174                 fprintf(services_file, "%s\t# my own service\n", name->name);
1175         }
1176         
1177         // write received services
1178         for (hash = 0; hash < HASHSIZE; hash++) {
1179                 list_head = &list[hash];
1180                 for (list_node = list_head->next; list_node != list_head;
1181                          list_node = list_node->next) {
1182
1183                         entry = list2db(list_node);
1184
1185                         for (name = entry->names; name != NULL; name = name->next) {
1186                                 struct ipaddr_str strbuf;
1187                                 OLSR_PRINTF(6, "%s\t",  name->name);
1188                                 OLSR_PRINTF(6, "\t#%s\n",
1189                                                         olsr_ip_to_string(&strbuf, &entry->originator));
1190
1191                                 fprintf(services_file, "%s\t", name->name );
1192                                 fprintf(services_file, "\t#%s\n",
1193                                                 olsr_ip_to_string(&strbuf, &entry->originator));
1194                         }
1195                 }
1196         }
1197
1198         if (time(&currtime)) {
1199                 fprintf(services_file, "\n### written by olsrd at %s", ctime(&currtime));
1200         }
1201           
1202         fclose(services_file);
1203         service_table_changed = OLSR_FALSE;
1204 }
1205
1206 /**
1207  * Sort the nameserver pointer array.
1208  *
1209  * fresh entries are at the beginning of the array and
1210  * the best entry is at the end of the array.
1211  */
1212 static void
1213 select_best_nameserver(struct rt_entry **rt)
1214 {
1215         int nameserver_idx;
1216         struct rt_entry *rt1, *rt2;
1217
1218         for (nameserver_idx = 0;
1219                  nameserver_idx < NAMESERVER_COUNT;
1220                  nameserver_idx++) {
1221
1222                 rt1 = rt[nameserver_idx];
1223                 rt2 = rt[nameserver_idx+1];
1224
1225                 /*
1226                  * compare the next two pointers in the array.
1227                  * if the second pointer is NULL then percolate it up.
1228                  */
1229                 if (!rt2 || olsr_cmp_rt(rt1, rt2)) {
1230 #ifndef NODEBUG
1231                         struct ipaddr_str strbuf;
1232                         struct lqtextbuffer lqbuffer;
1233 #endif
1234                         /*
1235                          * first is better, swap the pointers.
1236                          */
1237                         OLSR_PRINTF(6, "NAME PLUGIN: nameserver %s, cost %s\n",
1238                                                 olsr_ip_to_string(&strbuf, &rt1->rt_dst.prefix),
1239                                                 get_linkcost_text(rt1->rt_best->rtp_metric.cost, OLSR_TRUE, &lqbuffer));
1240
1241                         rt[nameserver_idx] = rt2;
1242                         rt[nameserver_idx+1] = rt1;
1243                 }
1244         }
1245 }
1246
1247 /**
1248  * write the 3 best upstream DNS servers to resolv.conf file
1249  * best means the 3 with the best etx value in routing table
1250  */
1251 void
1252 write_resolv_file(void)
1253 {
1254         int hash;
1255         struct name_entry *name;
1256         struct db_entry *entry;
1257         struct list_node *list_head, *list_node;
1258         struct rt_entry *route;
1259         static struct rt_entry *nameserver_routes[NAMESERVER_COUNT+1];
1260         FILE* resolv;
1261         int i=0;
1262         time_t currtime;
1263
1264         if (!forwarder_table_changed || my_forwarders != NULL || my_resolv_file[0] == '\0')
1265                 return;
1266
1267         /* clear the array of 3+1 nameserver routes */
1268         memset(nameserver_routes, 0, sizeof(nameserver_routes));
1269
1270         for (hash = 0; hash < HASHSIZE; hash++) {
1271                 list_head = &list[hash];
1272                 for (list_node = list_head->next; list_node != list_head;
1273                          list_node = list_node->next) {
1274
1275                         entry = list2db(list_node);
1276
1277                         for (name = entry->names; name != NULL; name = name->next) {
1278 #ifndef NODEBUG
1279                                 struct ipaddr_str strbuf;
1280                                 struct lqtextbuffer lqbuffer;
1281 #endif
1282                                 route = olsr_lookup_routing_table(&name->ip);
1283
1284                                 OLSR_PRINTF(6, "NAME PLUGIN: check route for nameserver %s %s",
1285                                                         olsr_ip_to_string(&strbuf, &name->ip),
1286                                                         route ? "suceeded" : "failed");
1287
1288                                 if (route==NULL) // it's possible that route is not present yet
1289                                         continue;
1290
1291                                 /* enqueue it on the head of list */
1292                                 *nameserver_routes = route;
1293                                 OLSR_PRINTF(6, "NAME PLUGIN: found nameserver %s, cost %s",
1294                                                         olsr_ip_to_string(&strbuf, &name->ip),
1295                                                         get_linkcost_text(route->rt_best->rtp_metric.cost, OLSR_TRUE, &lqbuffer));
1296
1297                                 /* find the closet one */
1298                                 select_best_nameserver(nameserver_routes);
1299                         }
1300                 }
1301         }
1302
1303         /* if there is no best route we are done */
1304         if (nameserver_routes[NAMESERVER_COUNT]==NULL)
1305                 return;
1306                  
1307         /* write to file */
1308         OLSR_PRINTF(2, "NAME PLUGIN: try to write to resolv file\n");
1309         resolv = fopen( my_resolv_file, "w" );
1310         if (resolv == NULL) {
1311                 OLSR_PRINTF(2, "NAME PLUGIN: can't write resolv file\n");
1312                 return;
1313         }
1314         fprintf(resolv, "### this file is overwritten regularly by olsrd\n");
1315         fprintf(resolv, "### do not edit\n\n");
1316
1317         for (i = NAMESERVER_COUNT; i >= 0; i--) {
1318                 struct ipaddr_str strbuf;
1319
1320                 route = nameserver_routes[i];
1321
1322                 OLSR_PRINTF(2, "NAME PLUGIN: nameserver_routes #%d %p\n", i, route);
1323
1324                 if (!route) {
1325                         continue;
1326                 }
1327
1328                 OLSR_PRINTF(2, "NAME PLUGIN: nameserver %s\n",
1329                                         olsr_ip_to_string(&strbuf, &route->rt_dst.prefix));
1330                 fprintf(resolv, "nameserver %s\n",
1331                                 olsr_ip_to_string(&strbuf, &route->rt_dst.prefix));
1332         }
1333         if (time(&currtime)) {
1334                 fprintf(resolv, "\n### written by olsrd at %s", ctime(&currtime));
1335         }
1336         fclose(resolv);
1337         forwarder_table_changed = OLSR_FALSE;
1338 }
1339
1340
1341 /**
1342  * completely free a list of name_entries
1343  */
1344 void 
1345 free_name_entry_list(struct name_entry **list) 
1346 {
1347         struct name_entry **tmp = list;
1348         struct name_entry *to_delete;
1349         while (*tmp != NULL) {
1350                 to_delete = *tmp;
1351                 *tmp = (*tmp)->next;
1352
1353                 /* flag changes */
1354                 switch (to_delete->type) {
1355                 case NAME_HOST:
1356                         name_table_changed = OLSR_TRUE;
1357                         break;
1358                 case NAME_FORWARDER:
1359                         forwarder_table_changed = OLSR_TRUE;
1360                         break;
1361                 case NAME_SERVICE:
1362                         service_table_changed = OLSR_TRUE;
1363                         break;
1364                 case NAME_LATLON:
1365                         latlon_table_changed = OLSR_TRUE;
1366                         break;
1367                 default:
1368                         break;
1369                 }
1370
1371                 free( to_delete->name );
1372                 to_delete->name = NULL;
1373                 free( to_delete );
1374                 to_delete = NULL;
1375         }
1376 }
1377
1378
1379 /**
1380  * we only allow names for IP addresses which we are
1381  * responsible for: 
1382  * so the IP must either be from one of the interfaces
1383  * or inside a HNA which we have configured 
1384  */
1385 olsr_bool
1386 allowed_ip(const union olsr_ip_addr *addr)
1387 {
1388         struct ip_prefix_list *hna;
1389         struct interface *iface;
1390         union olsr_ip_addr tmp_ip, tmp_msk;
1391 #ifndef NODEBUG
1392         struct ipaddr_str strbuf;
1393 #endif
1394         
1395         OLSR_PRINTF(6, "checking %s\n", olsr_ip_to_string(&strbuf, addr));
1396         
1397         for(iface = ifnet; iface; iface = iface->int_next)
1398         {
1399                 OLSR_PRINTF(6, "interface %s\n", olsr_ip_to_string(&strbuf, &iface->ip_addr));
1400                 if (ipequal(&iface->ip_addr, addr)) {
1401                         OLSR_PRINTF(6, "MATCHED\n");
1402                         return OLSR_TRUE;
1403                 }
1404         }
1405         
1406         if (olsr_cnf->ip_version == AF_INET) {
1407                 for (hna = olsr_cnf->hna_entries; hna != NULL; hna = hna->next) {
1408                         union olsr_ip_addr netmask;
1409                         OLSR_PRINTF(6, "HNA %s/%d\n", 
1410                                                 olsr_ip_to_string(&strbuf, &hna->net.prefix),
1411                                                 hna->net.prefix_len);
1412                         if (hna->net.prefix_len == 0) {
1413                                 continue;
1414                         }
1415                         olsr_prefix_to_netmask(&netmask, hna->net.prefix_len);
1416                         if ((addr->v4.s_addr & netmask.v4.s_addr) == hna->net.prefix.v4.s_addr) {
1417                                 OLSR_PRINTF(6, "MATCHED\n");
1418                                 return OLSR_TRUE;
1419                         }
1420                 }
1421         } else {
1422                 for (hna = olsr_cnf->hna_entries; hna != NULL; hna = hna->next)
1423                 {
1424                         unsigned int i;
1425                         OLSR_PRINTF(6, "HNA %s/%d\n", 
1426                                 olsr_ip_to_string(&strbuf, &hna->net.prefix),
1427                                 hna->net.prefix_len);
1428                         if ( hna->net.prefix_len == 0 )
1429                                 continue;
1430                         olsr_prefix_to_netmask(&tmp_msk, hna->net.prefix_len);
1431                         for (i = 0; i < sizeof(tmp_ip.v6.s6_addr); i++) {
1432                                 tmp_ip.v6.s6_addr[i] = addr->v6.s6_addr[i] & tmp_msk.v6.s6_addr[i];
1433                         }
1434                         if (ipequal(&tmp_ip, &hna->net.prefix)) {
1435                                 OLSR_PRINTF(6, "MATCHED\n");
1436                                 return OLSR_TRUE;
1437                         }
1438                 }
1439         }
1440         return OLSR_FALSE;
1441 }
1442
1443 /** check if name has the right syntax, i.e. it must adhere to a special regex 
1444  * stored in regex_t_name
1445  * necessary to avaid names like "0.0.0.0 google.de\n etc"
1446  */
1447 olsr_bool
1448 is_name_wellformed(const char *name) {
1449         return regexec(&regex_t_name, name, 1, &regmatch_t_name, 0) == 0 ;
1450 }
1451
1452
1453 /**
1454  * check if the service is in the right syntax and also that the hostname 
1455  * or ip whithin the service is allowed
1456  */
1457 olsr_bool
1458 allowed_service(const char *service_line)
1459 {
1460         /* the call of is_service_wellformed generates the submatches stored in regmatch_t_service
1461          * these are then used by allowed_hostname_or_ip_in_service
1462          * see regexec(3) for more infos */
1463         if (!is_service_wellformed(service_line)) {
1464                 return OLSR_FALSE;
1465         } else if (!allowed_hostname_or_ip_in_service(service_line, &(regmatch_t_service[1]))) {
1466                 return OLSR_FALSE;
1467         } 
1468
1469         return OLSR_TRUE;
1470 }
1471
1472 olsr_bool
1473 allowed_hostname_or_ip_in_service(const char *service_line, const regmatch_t *hostname_or_ip_match) 
1474 {
1475         char *hostname_or_ip;
1476         union olsr_ip_addr olsr_ip;
1477         struct name_entry *name;
1478         if (hostname_or_ip_match->rm_so < 0 || hostname_or_ip_match->rm_eo < 0) {
1479                 return OLSR_FALSE;
1480         } 
1481
1482         hostname_or_ip = strndup(&service_line[hostname_or_ip_match->rm_so], hostname_or_ip_match->rm_eo - hostname_or_ip_match->rm_so);
1483         //hostname is one of the names, that I announce (i.e. one that i am allowed to announce)
1484         for (name = my_names; name != NULL; name = name->next) {
1485                 if (strncmp(name->name, hostname_or_ip, name->len - strlen(my_suffix)) == 0 ) {
1486                         OLSR_PRINTF(4, "NAME PLUGIN: hostname %s in service %s is OK\n", hostname_or_ip, service_line);
1487                         free(hostname_or_ip);
1488                         hostname_or_ip = NULL;
1489                         return OLSR_TRUE;
1490                 }
1491         }
1492
1493         //ip in service-line is allowed 
1494         if (inet_pton(olsr_cnf->ip_version, hostname_or_ip, &olsr_ip) > 0) {
1495                 if (allowed_ip(&olsr_ip)) {
1496 #ifndef NODEBUG
1497                         struct ipaddr_str strbuf;
1498 #endif
1499                         OLSR_PRINTF(2, "NAME PLUGIN: ip %s in service %s is OK\n", olsr_ip_to_string(&strbuf, &olsr_ip), service_line);
1500                         free(hostname_or_ip);
1501                         hostname_or_ip = NULL;
1502                         return OLSR_TRUE;
1503                 }
1504         }
1505
1506         OLSR_PRINTF(1, "NAME PLUGIN: ip or hostname %s in service %s is NOT allowed (does not belong to you)\n", hostname_or_ip, service_line);
1507         free(hostname_or_ip);
1508         hostname_or_ip = NULL;
1509
1510         return OLSR_FALSE;
1511 }
1512
1513 /**
1514  * check if the service matches the syntax 
1515  * of "protocol://host:port/path|tcp_or_udp|a short description", 
1516  * which is given in the regex regex_t_service
1517  */
1518 olsr_bool
1519 is_service_wellformed(const char *service_line)
1520 {
1521         return regexec(&regex_t_service, service_line, pmatch_service, regmatch_t_service, 0) == 0;
1522 }
1523
1524 /**
1525  * check if the latlot matches the syntax 
1526  */
1527 olsr_bool
1528 is_latlon_wellformed(const char *latlon_line)
1529 {
1530         int hna = -1;
1531         float a = 0.0, b = 0.0;
1532         sscanf(latlon_line, "%f,%f,%d", &a, &b, &hna);
1533         return (a != 0.0 && b != 0.0 && -1 != hna);
1534 }
1535
1536 /**
1537  * Returns 1 if this olsrd announces inet
1538  */
1539 olsr_bool get_isdefhna_latlon(void)
1540 {
1541         struct ip_prefix_list *hna;
1542         for (hna = olsr_cnf->hna_entries; hna != NULL; hna = hna->next){
1543                 if (hna->net.prefix_len == 0) {
1544                         return OLSR_TRUE;
1545                 }
1546         }
1547         return OLSR_FALSE;
1548 }
1549
1550 /**
1551  * Grabs the current HNA selected default route
1552  */
1553 void lookup_defhna_latlon(union olsr_ip_addr *ip)
1554 {
1555   struct rt_entry *rt;
1556   struct avl_node *rt_tree_node;
1557   struct olsr_ip_prefix prefix;
1558
1559   memset(ip, 0, sizeof(ip));
1560   memset(&prefix, 0, sizeof(prefix));
1561
1562   if (NULL != (rt_tree_node = avl_find(&routingtree, &prefix))) {
1563         rt = rt_tree2rt(rt_tree_node);
1564     *ip = rt->rt_best->rtp_nexthop.gateway;
1565   }
1566 }
1567
1568 /**
1569  * lookup a nodes name
1570  */
1571 const char*
1572 lookup_name_latlon(union olsr_ip_addr *ip)
1573 {
1574         int hash;
1575         struct db_entry *entry;
1576         struct list_node *list_head, *list_node;
1577         struct name_entry *name;
1578
1579         for (hash = 0; hash < HASHSIZE; hash++) {
1580                 list_head = &list[hash];
1581                 for (list_node = list_head->next; list_node != list_head;
1582                          list_node = list_node->next) {
1583
1584                         entry = list2db(list_node);
1585
1586                         for (name = entry->names; name != NULL; name = name->next) {
1587                                 if (ipequal(&name->ip, ip)) return name->name;
1588                         }
1589                 }
1590         }
1591         return "";
1592 }
1593
1594 #ifdef WIN32
1595 /**
1596  * write latlon positions to a javascript file
1597  */
1598 void
1599 write_latlon_file(void)
1600 {
1601   FILE* fmap;
1602   
1603   if (!my_names || !latlon_table_changed) return;
1604   
1605   OLSR_PRINTF(2, "NAME PLUGIN: writing latlon file\n");
1606
1607   if (NULL == (fmap = fopen(my_latlon_file, "w"))) {
1608     OLSR_PRINTF(0, "NAME PLUGIN: cant write latlon file\n");
1609     return;
1610   }
1611   fprintf(fmap, "/* This file is overwritten regularly by olsrd */\n");
1612   mapwrite_work(fmap);  
1613   fclose(fmap);
1614   latlon_table_changed = OLSR_FALSE;
1615 }
1616 #endif
1617
1618 /*
1619  * Local Variables:
1620  * mode: c
1621  * c-indent-tabs-mode: t
1622  * indent-tabs-mode: t
1623  * c-basic-offset: 4
1624  * tab-width: 4
1625  * End:
1626  */