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