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