]> git.meshlink.io Git - catta/blob - avahi-dnsconfd/main.c
cca0b68118a1195c7487f513580a8feca944933c
[catta] / avahi-dnsconfd / main.c
1 /* $Id$ */
2
3 /***
4   This file is part of avahi.
5  
6   avahi is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as
8   published by the Free Software Foundation; either version 2.1 of the
9   License, or (at your option) any later version.
10  
11   avahi is distributed in the hope that it will be useful, but WITHOUT
12   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13   or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
14   Public License for more details.
15  
16   You should have received a copy of the GNU Lesser General Public
17   License along with avahi; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <sys/un.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <sys/select.h>
30 #include <sys/socket.h>
31 #include <errno.h>
32 #include <string.h>
33 #include <stdio.h>
34 #include <sys/ioctl.h>
35 #include <net/if.h>
36 #include <signal.h>
37 #include <sys/wait.h>
38 #include <getopt.h>
39 #include <assert.h>
40 #include <inttypes.h>
41 #include <stdlib.h>
42
43 #include <avahi-common/llist.h>
44 #include <avahi-common/malloc.h>
45 #include <avahi-common/address.h>
46
47 #include <libdaemon/dfork.h>
48 #include <libdaemon/dsignal.h>
49 #include <libdaemon/dlog.h>
50 #include <libdaemon/dpid.h>
51 #include <libdaemon/dexec.h>
52
53 #define BROWSE_DNS_SERVERS "BROWSE-DNS-SERVERS\n"
54
55 #define ENV_INTERFACE_DNS_SERVERS  "AVAHI_INTERFACE_DNS_SERVERS"
56 #define ENV_DNS_SERVERS "AVAHI_DNS_SERVERS"
57 #define ENV_INTERFACE "AVAHI_INTERFACE"
58
59 static enum {
60     ACKWAIT,
61     BROWSING
62 } state = ACKWAIT;
63
64 static int quit = 0;
65
66 static enum {
67     DAEMON_RUN,
68     DAEMON_KILL,
69     DAEMON_REFRESH,
70     DAEMON_VERSION,
71     DAEMON_HELP,
72     DAEMON_CHECK
73 } command = DAEMON_RUN;
74
75 static int daemonize = 0;
76
77 typedef struct DNSServerInfo DNSServerInfo;
78
79 struct DNSServerInfo {
80     AvahiIfIndex interface;
81     AvahiProtocol protocol;
82     char *address;
83     AVAHI_LLIST_FIELDS(DNSServerInfo, servers);
84 };
85
86 static AVAHI_LLIST_HEAD(DNSServerInfo, servers);
87
88 static void server_info_free(DNSServerInfo *i) {
89     assert(i);
90
91     avahi_free(i->address);
92     
93     AVAHI_LLIST_REMOVE(DNSServerInfo, servers, servers, i);
94     avahi_free(i);
95 }
96
97 static DNSServerInfo* get_server_info(AvahiIfIndex interface, AvahiProtocol protocol, const char *address) {
98     DNSServerInfo *i;
99     assert(address);
100
101     for (i = servers; i; i = i->servers_next)
102         if (i->interface == interface &&
103             i->protocol == protocol &&
104             strcmp(i->address, address) == 0)
105             return i;
106
107     return NULL;
108 }
109
110 static DNSServerInfo* new_server_info(AvahiIfIndex interface, AvahiProtocol protocol, const char *address) {
111     DNSServerInfo *i;
112     
113     assert(address);
114
115     i = avahi_new(DNSServerInfo, 1);
116     i->interface = interface;
117     i->protocol = protocol;
118     i->address = avahi_strdup(address);
119
120     AVAHI_LLIST_PREPEND(DNSServerInfo, servers, servers, i);
121     
122     return i;
123 }
124
125 static int set_cloexec(int fd) {
126     int n;
127
128     assert(fd >= 0);
129     
130     if ((n = fcntl(fd, F_GETFD)) < 0)
131         return -1;
132
133     if (n & FD_CLOEXEC)
134         return 0;
135
136     return fcntl(fd, F_SETFD, n|FD_CLOEXEC);
137 }
138
139 static int open_socket(void) {
140     int fd = -1;
141     struct sockaddr_un sa;
142
143     if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
144         daemon_log(LOG_ERR, "socket(): %s", strerror(errno));
145         goto fail;
146     }
147
148     if (set_cloexec(fd) < 0) {
149         daemon_log(LOG_ERR, "fcntl(): %s", strerror(errno));
150         goto fail;
151     }
152     
153     memset(&sa, 0, sizeof(sa));
154     sa.sun_family = AF_UNIX;
155     strncpy(sa.sun_path, AVAHI_SOCKET, sizeof(sa.sun_path)-1);
156     sa.sun_path[sizeof(sa.sun_path)-1] = 0;
157
158     if (connect(fd, (struct sockaddr*) &sa, sizeof(sa)) < 0) {
159         daemon_log(LOG_ERR, "connect(): %s", strerror(errno));
160         daemon_log(LOG_INFO, "Failed to connect to the daemon. This probably means that you");
161         daemon_log(LOG_INFO, "didn't start avahi-daemon before avahi-dnsconfd.");
162         goto fail;
163     }
164
165     return fd;
166     
167 fail:
168     if (fd >= 0)
169         close(fd);
170
171     return -1;
172 }
173
174 static ssize_t loop_write(int fd, const void*data, size_t size) {
175
176     ssize_t ret = 0;
177     assert(fd >= 0 && data && size);
178
179     while (size > 0) {
180         ssize_t r;
181
182         if ((r = write(fd, data, size)) < 0)
183             return r;
184
185         if (r == 0)
186             break;
187
188         ret += r;
189         data = (const uint8_t*) data + r;
190         size -= r;
191     }
192
193     return ret;
194 }
195
196 static char *concat_dns_servers(AvahiIfIndex interface) {
197     DNSServerInfo *i;
198     char *r = NULL;
199     
200     for (i = servers; i; i = i->servers_next)
201         if (i->interface == interface || interface <= 0) {
202             char *t;
203
204             if (!r)
205                 t = avahi_strdup(i->address);
206             else
207                 t = avahi_strdup_printf("%s %s", r, i->address);
208
209             avahi_free(r);
210             r = t;
211         }
212
213     return r;
214 }
215
216 static char *getifname(AvahiIfIndex interface, char *name, size_t len) {
217     int fd = -1;
218     char *ret = NULL;
219     struct ifreq ifr;
220
221     assert(interface >= 0);
222     
223     if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
224         daemon_log(LOG_ERR, "socket(): %s", strerror(errno));
225         goto finish;
226     }
227
228     memset(&ifr, 0, sizeof(ifr));
229     ifr.ifr_ifindex = (int) interface;
230     
231     if (ioctl(fd, SIOCGIFNAME, &ifr) < 0) {
232         daemon_log(LOG_ERR, "SIOCGIFNAME: %s\n", strerror(errno));
233         goto finish;
234     }
235
236     strncpy(name, ifr.ifr_name, len-1);
237     name[len-1] = 0;
238     ret = name;
239     
240 finish:
241     if (fd >= 0)
242         close(fd);
243     
244     return ret;
245 }
246
247 static void set_env(const char *name, const char *value) {
248     char **e;
249     size_t l;
250     
251     assert(name);
252     assert(value);
253
254     l = strlen(name);
255
256     for (e = environ; *e; e++) {
257         /* Search for the variable */
258         if (strlen(*e) < l+1)
259             continue;
260         
261         if (strncmp(*e, name, l) != 0 || (*e)[l] != '=')
262             continue;
263
264         /* We simply free the record, sicne we know that we created it previously */
265         avahi_free(*e);
266         *e = avahi_strdup_printf("%s=%s", name, value);
267         return;
268     }
269
270     assert(0);
271 }
272
273 static void run_script(int new, AvahiIfIndex interface, AvahiProtocol protocol, const char *address) {
274     char *p;
275     int ret;
276     char ia[16], pa[16];
277     char name[IFNAMSIZ+1];
278
279     assert(interface > 0);
280
281     if (!getifname(interface, name, sizeof(name))) 
282         return;
283     
284     p = concat_dns_servers(interface);
285     set_env(ENV_INTERFACE_DNS_SERVERS, p ? p : "");
286     avahi_free(p); 
287
288     p = concat_dns_servers(-1);
289     set_env(ENV_DNS_SERVERS, p ? p : "");
290     avahi_free(p); 
291
292     set_env(ENV_INTERFACE, name);
293     
294     snprintf(ia, sizeof(ia), "%i", (int) interface);
295     snprintf(pa, sizeof(pa), "%i", (int) protocol);
296
297     if (daemon_exec("/", &ret, AVAHI_DNSCONF_SCRIPT, AVAHI_DNSCONF_SCRIPT, new ? "+" : "-", address, ia, pa, avahi_proto_to_string(protocol), NULL) < 0)
298         daemon_log(LOG_WARNING, "Failed to run script");
299     else if (ret != 0)
300         daemon_log(LOG_WARNING, "Script returned with non-zero exit code %i", ret);
301 }
302
303 static int new_line(const char *l) {
304     assert(l);
305
306     if (state == ACKWAIT) {
307         if (*l != '+') {
308             daemon_log(LOG_ERR, "Avahi command failed: %s", l);
309             return -1;
310         }
311
312         daemon_log(LOG_INFO, "Successfully connected to Avahi daemon.");
313         state = BROWSING;
314     } else {
315         AvahiIfIndex interface;
316         AvahiProtocol protocol;
317         int i_interface, i_protocol, port;
318         char a[64];
319         
320         assert(state == BROWSING); 
321
322         if (*l != '<' && *l != '>') {
323             daemon_log(LOG_ERR, "Avahi sent us an invalid browsing line: %s", l);
324             return -1;
325         }
326
327         if (sscanf(l+1, "%i %i %64s %i", &i_interface, &i_protocol, a, &port) != 4) {
328             daemon_log(LOG_ERR, "Failed to parse browsing line: %s", l);
329             return -1;
330         }
331
332         interface = (AvahiIfIndex) i_interface;
333         protocol = (AvahiProtocol) i_protocol;
334
335         if (*l == '>') {
336             if (port != 53)
337                 daemon_log(LOG_WARNING, "DNS server with port address != 53 found, ignoring");
338             else {
339                 daemon_log(LOG_INFO, "New DNS Server %s (interface: %i.%s)", a, interface, avahi_proto_to_string(protocol));
340                 new_server_info(interface, protocol, a);
341                 run_script(1, interface, protocol, a);
342             }
343         } else {
344             DNSServerInfo *i;
345
346             if (port == 53) 
347                 if ((i = get_server_info(interface, protocol, a))) {
348                     daemon_log(LOG_INFO, "DNS Server %s removed (interface: %i.%s)", a, interface, avahi_proto_to_string(protocol));
349                     server_info_free(i);
350                     run_script(0, interface, protocol, a);
351                 }
352         }
353
354     }
355     
356     return 0;
357 }
358
359 static int do_connect(void) {
360     int fd = -1;
361     
362     if ((fd = open_socket()) < 0)
363         goto fail;
364
365     if (loop_write(fd, BROWSE_DNS_SERVERS, sizeof(BROWSE_DNS_SERVERS)-1) < 0) {
366         daemon_log(LOG_ERR, "write(): %s", strerror(errno));
367         goto fail;
368     }
369
370     state = ACKWAIT;
371     return fd;
372
373 fail:
374     if (fd >= 0)
375         close(fd);
376     
377     return -1;
378 }
379
380 static void free_dns_server_info_list(void) {
381     while (servers) {
382         AvahiIfIndex interface = servers->interface;
383         AvahiProtocol protocol = servers->protocol;
384         char *address = avahi_strdup(servers->address);
385         server_info_free(servers);
386         
387         run_script(0, interface, protocol, address);
388         avahi_free(address);
389     }
390 }
391
392 static void help(FILE *f, const char *argv0) {
393     fprintf(f,
394             "%s [options]\n"
395             "    -h --help        Show this help\n"
396             "    -D --daemonize   Daemonize after startup\n"
397             "    -k --kill        Kill a running daemon\n"
398             "    -r --refresh     Request a running daemon to refresh DNS server data\n"
399             "    -c --check       Return 0 if a daemon is already running\n"
400             "    -V --version     Show version\n",
401             argv0);
402 }
403
404 static int parse_command_line(int argc, char *argv[]) {
405     int c;
406     
407     static const struct option long_options[] = {
408         { "help",      no_argument,       NULL, 'h' },
409         { "daemonize", no_argument,       NULL, 'D' },
410         { "kill",      no_argument,       NULL, 'k' },
411         { "version",   no_argument,       NULL, 'V' },
412         { "refresh",   no_argument,       NULL, 'r' },
413         { "check",     no_argument,       NULL, 'c' },
414     };
415
416     opterr = 0;
417     while ((c = getopt_long(argc, argv, "hDkVrc", long_options, NULL)) >= 0) {
418
419         switch(c) {
420             case 'h':
421                 command = DAEMON_HELP;
422                 break;
423             case 'D':
424                 daemonize = 1;
425                 break;
426             case 'k':
427                 command = DAEMON_KILL;
428                 break;
429             case 'V':
430                 command = DAEMON_VERSION;
431                 break;
432             case 'r':
433                 command = DAEMON_REFRESH;
434                 break;
435             case 'c':
436                 command = DAEMON_CHECK;
437                 break;
438             default:
439                 fprintf(stderr, "Invalid command line argument: %c\n", c);
440                 return -1;
441         }
442     }
443
444     if (optind < argc) {
445         fprintf(stderr, "Too many arguments\n");
446         return -1;
447     }
448         
449     return 0;
450 }
451
452 static int run_daemon(void) {
453     int fd = -1, ret = -1;
454     char buf[1024];
455     size_t buflen = 0;
456
457     AVAHI_LLIST_HEAD_INIT(DNSServerInfo, servers);
458     
459     daemon_signal_init(SIGINT, SIGTERM, SIGCHLD, SIGHUP, 0);
460
461     /* Allocate some memory for our environment variables */
462     putenv(avahi_strdup(ENV_INTERFACE"="));
463     putenv(avahi_strdup(ENV_DNS_SERVERS"="));
464     putenv(avahi_strdup(ENV_INTERFACE_DNS_SERVERS"="));
465     
466     if ((fd = do_connect()) < 0)
467         goto finish;
468
469     if (daemonize)
470         daemon_retval_send(0);
471
472     ret = 0;
473
474     while (!quit) {
475         fd_set rfds, wfds;
476
477         FD_ZERO(&rfds);
478         FD_ZERO(&wfds);
479
480         FD_SET(fd, &rfds);
481         FD_SET(daemon_signal_fd(), &rfds);
482
483         for (;;) {
484             if (select(fd+1, &rfds, NULL, NULL, NULL) < 0) {
485                 if (errno == EINTR)
486                     continue;
487
488                 daemon_log(LOG_ERR, "select(): %s", strerror(errno));
489                 goto finish;
490             }
491
492             break;
493         }
494
495         if (FD_ISSET(daemon_signal_fd(), &rfds)) {
496
497             int sig;
498
499             if ((sig = daemon_signal_next()) <= 0) {
500                 daemon_log(LOG_ERR, "daemon_signal_next() failed");
501                 goto finish;
502             }
503
504             switch(sig) {
505                 case SIGINT:
506                 case SIGTERM:
507                     daemon_log(LOG_INFO, "Got %s, quitting.", sig == SIGINT ? "SIGINT" : "SIGTERM");
508                     ret = 0;
509                     goto finish;
510
511                 case SIGCHLD:
512                     waitpid(-1, NULL, WNOHANG);
513                     break;
514                     
515                 case SIGHUP:
516                     daemon_log(LOG_INFO, "Refreshing DNS Server list");
517                     
518                     close(fd);
519                     free_dns_server_info_list();
520                     
521                     if ((fd = do_connect()) < 0)
522                         goto finish;
523                     
524                     break;
525             }
526             
527         } else if (FD_ISSET(fd, &rfds)) {
528             ssize_t r;
529             char *n;
530
531             if ((r = read(fd, buf, sizeof(buf) - buflen - 1)) <= 0) {
532                 daemon_log(LOG_ERR, "read(): %s", r < 0 ? strerror(errno) : "EOF");
533                 goto finish;
534             }
535
536             buflen += r;
537             assert(buflen <= sizeof(buf)-1);
538
539             while ((n = memchr(buf, '\n', buflen))) {
540                 *(n++) = 0;
541
542                 if (new_line(buf) < 0)
543                     goto finish;
544
545                 buflen -= (n - buf);
546                 memmove(buf, n, buflen);
547             }
548
549             if (buflen >= sizeof(buf)-1) {
550                 /* The incoming line is horribly long */
551                 buf[sizeof(buf)-1] = 0;
552                 
553                 if (new_line(buf) < 0)
554                     goto finish;
555                 
556                 buflen = 0;
557             }
558         }
559     }
560     
561 finish:
562
563     free_dns_server_info_list();
564
565     if (fd >= 0)
566         close(fd);
567     
568     daemon_signal_done();
569
570     if (ret != 0 && daemonize)
571         daemon_retval_send(1);
572     
573     return ret;
574 }
575
576 static const char* pid_file_proc(void) {
577     return AVAHI_RUNTIME_DIR"/avahi-dnsconfd.pid";
578 }
579
580 int main(int argc, char *argv[]) {
581     char *argv0;
582     int r = 1;
583     int wrote_pid_file = 0;
584
585     if ((argv0 = strrchr(argv[0], '/')))
586         argv0++;
587     else
588         argv0 = argv[0];
589
590     daemon_pid_file_ident = daemon_log_ident = argv0;
591     daemon_pid_file_proc = pid_file_proc;
592     
593     if (parse_command_line(argc, argv) < 0)
594         goto finish;
595
596     if (command == DAEMON_RUN) {
597         pid_t pid;
598
599         if (getuid() != 0) {
600             daemon_log(LOG_ERR, "This program is intended to be run as root.");
601             goto finish;
602         }
603
604         if ((pid = daemon_pid_file_is_running()) >= 0) {
605             daemon_log(LOG_ERR, "Daemon already running on PID %u", pid);
606             goto finish;
607         }
608
609         if (daemonize) {
610             daemon_retval_init();
611             
612             if ((pid = daemon_fork()) < 0)
613                 goto finish;
614             else if (pid != 0) {
615                 int ret;
616                 /** Parent **/
617
618                 if ((ret = daemon_retval_wait(20)) < 0) {
619                     daemon_log(LOG_ERR, "Could not recieve return value from daemon process.");
620                     goto finish;
621                 }
622
623                 r = ret;
624                 goto finish;
625             }
626
627             /* Child */
628         }
629
630         chdir("/");
631
632         if (daemon_pid_file_create() < 0) {
633             daemon_log(LOG_ERR, "Failed to create PID file: %s", strerror(errno));
634
635             if (daemonize)
636                 daemon_retval_send(1);
637             goto finish;
638         } else
639             wrote_pid_file = 1;
640
641         if (run_daemon() < 0)
642             goto finish;
643
644         r = 0;
645     } else if (command == DAEMON_HELP) {
646         help(stdout, argv0);
647         
648         r = 0;
649     } else if (command == DAEMON_VERSION) {
650         printf("%s "PACKAGE_VERSION"\n", argv0);
651         
652         r = 0;
653     } else if (command == DAEMON_KILL) {
654         if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
655             daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
656             goto finish;
657         }
658         
659         r = 0;
660     } else if (command == DAEMON_REFRESH) {
661         if (daemon_pid_file_kill(SIGHUP) < 0) {
662             daemon_log(LOG_WARNING, "Failed to kill daemon: %s", strerror(errno));
663             goto finish;
664         }
665
666         r = 0;
667     } else if (command == DAEMON_CHECK)
668         r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
669
670
671 finish:
672
673     if (daemonize)
674         daemon_retval_done();
675     
676     if (wrote_pid_file)
677         daemon_pid_file_remove();
678
679     return r;
680 }