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