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