Add inotify support for /ect/avahi/services and /etc/avahi/hosts. Based on a patch...
[platform/upstream/avahi.git] / avahi-daemon / 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 <assert.h>
27 #include <getopt.h>
28 #include <string.h>
29 #include <signal.h>
30 #include <errno.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <grp.h>
34 #include <pwd.h>
35 #include <sys/stat.h>
36 #include <sys/ioctl.h>
37 #include <stdio.h>
38 #include <fcntl.h>
39 #include <time.h>
40 #include <stdlib.h>
41 #include <sys/time.h>
42 #include <sys/resource.h>
43 #include <sys/socket.h>
44
45 #ifdef HAVE_SYS_INOTIFY_H
46 #include <sys/inotify.h>
47 #else
48 #include "inotify-nosys.h"
49 #endif
50
51 #include <libdaemon/dfork.h>
52 #include <libdaemon/dsignal.h>
53 #include <libdaemon/dlog.h>
54 #include <libdaemon/dpid.h>
55
56 #include <avahi-common/malloc.h>
57 #include <avahi-common/simple-watch.h>
58 #include <avahi-common/error.h>
59 #include <avahi-common/alternative.h>
60 #include <avahi-common/domain.h>
61
62 #include <avahi-core/core.h>
63 #include <avahi-core/publish.h>
64 #include <avahi-core/dns-srv-rr.h>
65 #include <avahi-core/log.h>
66
67 #ifdef ENABLE_CHROOT
68 #include "chroot.h"
69 #include "caps.h"
70 #endif
71
72 #include "setproctitle.h"
73 #include "main.h"
74 #include "simple-protocol.h"
75 #include "static-services.h"
76 #include "static-hosts.h"
77 #include "ini-file-parser.h"
78
79 #ifdef HAVE_DBUS
80 #include "dbus-protocol.h"
81 #endif
82
83 AvahiServer *avahi_server = NULL;
84 AvahiSimplePoll *simple_poll_api = NULL;
85 static char *argv0 = NULL;
86 int nss_support = 0;
87
88 typedef enum {
89     DAEMON_RUN,
90     DAEMON_KILL,
91     DAEMON_VERSION,
92     DAEMON_HELP,
93     DAEMON_RELOAD,
94     DAEMON_CHECK
95 } DaemonCommand;
96
97 typedef struct {
98     AvahiServerConfig server_config;
99     DaemonCommand command;
100     int daemonize;
101     int use_syslog;
102     char *config_file;
103 #ifdef HAVE_DBUS
104     int enable_dbus;
105     int fail_on_missing_dbus;
106 #endif
107     int drop_root;
108     int set_rlimits;
109 #ifdef ENABLE_CHROOT
110     int use_chroot;
111 #endif
112     int modify_proc_title;
113
114     int disable_user_service_publishing;
115     int publish_resolv_conf;
116     char ** publish_dns_servers;
117     int debug;
118
119     int rlimit_as_set, rlimit_core_set, rlimit_data_set, rlimit_fsize_set, rlimit_nofile_set, rlimit_stack_set;
120     rlim_t rlimit_as, rlimit_core, rlimit_data, rlimit_fsize, rlimit_nofile, rlimit_stack;
121
122 #ifdef RLIMIT_NPROC
123     int rlimit_nproc_set;
124     rlim_t rlimit_nproc;
125 #endif
126 } DaemonConfig;
127
128 #define RESOLV_CONF "/etc/resolv.conf"
129
130 static AvahiSEntryGroup *dns_servers_entry_group = NULL;
131 static AvahiSEntryGroup *resolv_conf_entry_group = NULL;
132
133 static char **resolv_conf = NULL;
134
135 static DaemonConfig config;
136
137 static int has_prefix(const char *s, const char *prefix) {
138     size_t l;
139
140     l = strlen(prefix);
141     
142     return strlen(s) >= l && strncmp(s, prefix, l) == 0;
143 }
144
145 static int load_resolv_conf(void) {
146     int ret = -1;
147     FILE *f;
148     int i = 0;
149     
150     avahi_strfreev(resolv_conf);
151     resolv_conf = NULL;
152
153 #ifdef ENABLE_CHROOT
154     f = avahi_chroot_helper_get_file(RESOLV_CONF);
155 #else
156     f = fopen(RESOLV_CONF, "r");
157 #endif
158     
159     if (!f) {
160         avahi_log_warn("Failed to open "RESOLV_CONF": %s", strerror(errno));
161         goto finish;
162     }
163
164     resolv_conf = avahi_new0(char*, AVAHI_WIDE_AREA_SERVERS_MAX+1);
165
166     while (!feof(f) && i < AVAHI_WIDE_AREA_SERVERS_MAX) {
167         char ln[128];
168         char *p;
169
170         if (!(fgets(ln, sizeof(ln), f)))
171             break;
172
173         ln[strcspn(ln, "\r\n#")] = 0;
174         p = ln + strspn(ln, "\t ");
175
176         if (has_prefix(p, "nameserver")) {
177             p += 10;
178             p += strspn(p, "\t ");
179             p[strcspn(p, "\t ")] = 0;
180             resolv_conf[i++] = avahi_strdup(p);
181         }
182     }
183
184     ret = 0;
185
186 finish:
187
188     if (ret != 0) {
189         avahi_strfreev(resolv_conf);
190         resolv_conf = NULL;
191     }
192         
193     if (f)
194         fclose(f);
195
196     return ret;
197 }
198
199 static AvahiSEntryGroup* add_dns_servers(AvahiServer *s, AvahiSEntryGroup* g, char **l) {
200     char **p;
201
202     assert(s);
203     assert(l);
204
205     if (!g) 
206         g = avahi_s_entry_group_new(s, NULL, NULL);
207
208     assert(avahi_s_entry_group_is_empty(g));
209
210     for (p = l; *p; p++) {
211         AvahiAddress a;
212         
213         if (!avahi_address_parse(*p, AVAHI_PROTO_UNSPEC, &a))
214             avahi_log_warn("Failed to parse address '%s', ignoring.", *p);
215         else
216             if (avahi_server_add_dns_server_address(s, g, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, 0, NULL, AVAHI_DNS_SERVER_RESOLVE, &a, 53) < 0) {
217                 avahi_s_entry_group_free(g);
218                 avahi_log_error("Failed to add DNS server address: %s", avahi_strerror(avahi_server_errno(s)));
219                 return NULL;
220             }
221     }
222
223     avahi_s_entry_group_commit(g);
224
225     return g;
226 }
227
228 static void remove_dns_server_entry_groups(void) {
229
230     if (resolv_conf_entry_group)
231         avahi_s_entry_group_reset(resolv_conf_entry_group);
232     
233     if (dns_servers_entry_group) 
234         avahi_s_entry_group_reset(dns_servers_entry_group);
235 }
236
237 static void update_wide_area_servers(void) {
238     AvahiAddress a[AVAHI_WIDE_AREA_SERVERS_MAX];
239     unsigned n = 0;
240     char **p;
241
242     if (!resolv_conf) {
243         avahi_server_set_wide_area_servers(avahi_server, NULL, 0);
244         return;
245     }
246
247     for (p = resolv_conf; *p && n < AVAHI_WIDE_AREA_SERVERS_MAX; p++) {
248         if (!avahi_address_parse(*p, AVAHI_PROTO_UNSPEC, &a[n]))
249             avahi_log_warn("Failed to parse address '%s', ignoring.", *p);
250         else
251             n++;
252     }
253
254     avahi_server_set_wide_area_servers(avahi_server, a, n);
255 }
256
257 static void server_callback(AvahiServer *s, AvahiServerState state, void *userdata) {
258     DaemonConfig *c = userdata;
259     
260     assert(s);
261     assert(c);
262
263     /* This function is possibly called before the global variable
264      * avahi_server has been set, therefore we do it explicitly */
265
266     avahi_server = s;
267     
268 #ifdef HAVE_DBUS
269     if (c->enable_dbus && state != AVAHI_SERVER_INVALID && state != AVAHI_SERVER_FAILURE)
270         dbus_protocol_server_state_changed(state);
271 #endif
272
273     switch (state) {
274         case AVAHI_SERVER_RUNNING:
275             avahi_log_info("Server startup complete. Host name is %s. Local service cookie is %u.", avahi_server_get_host_name_fqdn(s), avahi_server_get_local_service_cookie(s));
276             
277             avahi_set_proc_title(argv0, "%s: running [%s]", argv0, avahi_server_get_host_name_fqdn(s));
278             
279             static_service_add_to_server();
280             static_hosts_add_to_server();
281             
282             remove_dns_server_entry_groups();
283             
284             if (c->publish_resolv_conf && resolv_conf && resolv_conf[0])
285                 resolv_conf_entry_group = add_dns_servers(s, resolv_conf_entry_group, resolv_conf);
286             
287             if (c->publish_dns_servers && c->publish_dns_servers[0])
288                 dns_servers_entry_group = add_dns_servers(s, dns_servers_entry_group, c->publish_dns_servers);
289             
290             simple_protocol_restart_queries();
291             break;
292             
293         case AVAHI_SERVER_COLLISION: {
294             char *n;
295             
296             avahi_set_proc_title(argv0, "%s: collision", argv0);
297             
298             static_service_remove_from_server();
299             static_hosts_remove_from_server();
300             remove_dns_server_entry_groups();
301
302             n = avahi_alternative_host_name(avahi_server_get_host_name(s));
303             avahi_log_warn("Host name conflict, retrying with <%s>", n);
304             avahi_server_set_host_name(s, n);
305             avahi_free(n);
306
307             break;
308         }
309
310         case AVAHI_SERVER_FAILURE:
311
312             avahi_log_error("Server error: %s", avahi_strerror(avahi_server_errno(s)));
313             avahi_simple_poll_quit(simple_poll_api);
314             break;
315
316         case AVAHI_SERVER_REGISTERING:
317
318             avahi_set_proc_title(argv0, "%s: registering [%s]", argv0, avahi_server_get_host_name_fqdn(s));
319             
320             static_service_remove_from_server();
321             static_hosts_remove_from_server();
322             remove_dns_server_entry_groups();
323             
324             break;
325
326         case AVAHI_SERVER_INVALID:
327             break;
328             
329     }
330 }
331
332 static void help(FILE *f) {
333     fprintf(f,
334             "%s [options]\n"
335             "    -h --help          Show this help\n"
336             "    -D --daemonize     Daemonize after startup (implies -s)\n"
337             "    -s --syslog        Write log messages to syslog(3) instead of STDERR\n"
338             "    -k --kill          Kill a running daemon\n"
339             "    -r --reload        Request a running daemon to reload static services\n"
340             "    -c --check         Return 0 if a daemon is already running\n"
341             "    -V --version       Show version\n"
342             "    -f --file=FILE     Load the specified configuration file instead of\n"
343             "                       "AVAHI_CONFIG_FILE"\n"
344             "       --no-rlimits    Don't enforce resource limits\n"
345             "       --no-drop-root  Don't drop privileges\n"
346 #ifdef ENABLE_CHROOT            
347             "       --no-chroot     Don't chroot()\n"
348 #endif            
349             "       --no-proc-title Don't modify process title\n"
350             "       --debug         Increase verbosity\n",
351             argv0);
352 }
353
354
355 static int parse_command_line(DaemonConfig *c, int argc, char *argv[]) {
356     int o;
357
358     enum {
359         OPTION_NO_RLIMITS = 256,
360         OPTION_NO_DROP_ROOT,
361 #ifdef ENABLE_CHROOT        
362         OPTION_NO_CHROOT,
363 #endif
364         OPTION_NO_PROC_TITLE,
365         OPTION_DEBUG
366     };
367     
368     static const struct option long_options[] = {
369         { "help",           no_argument,       NULL, 'h' },
370         { "daemonize",      no_argument,       NULL, 'D' },
371         { "kill",           no_argument,       NULL, 'k' },
372         { "version",        no_argument,       NULL, 'V' },
373         { "file",           required_argument, NULL, 'f' },
374         { "reload",         no_argument,       NULL, 'r' },
375         { "check",          no_argument,       NULL, 'c' },
376         { "syslog",         no_argument,       NULL, 's' },
377         { "no-rlimits",     no_argument,       NULL, OPTION_NO_RLIMITS },
378         { "no-drop-root",   no_argument,       NULL, OPTION_NO_DROP_ROOT },
379 #ifdef ENABLE_CHROOT
380         { "no-chroot",      no_argument,       NULL, OPTION_NO_CHROOT },
381 #endif
382         { "no-proc-title",  no_argument,       NULL, OPTION_NO_PROC_TITLE },
383         { "debug",          no_argument,       NULL, OPTION_DEBUG },
384         { NULL, 0, NULL, 0 }
385     };
386
387     assert(c);
388
389     while ((o = getopt_long(argc, argv, "hDkVf:rcs", long_options, NULL)) >= 0) {
390
391         switch(o) {
392             case 's':
393                 c->use_syslog = 1;
394                 break;
395             case 'h':
396                 c->command = DAEMON_HELP;
397                 break;
398             case 'D':
399                 c->daemonize = 1;
400                 break;
401             case 'k':
402                 c->command = DAEMON_KILL;
403                 break;
404             case 'V':
405                 c->command = DAEMON_VERSION;
406                 break;
407             case 'f':
408                 avahi_free(c->config_file);
409                 c->config_file = avahi_strdup(optarg);
410                 break;
411             case 'r':
412                 c->command = DAEMON_RELOAD;
413                 break;
414             case 'c':
415                 c->command = DAEMON_CHECK;
416                 break;
417             case OPTION_NO_RLIMITS:
418                 c->set_rlimits = 0;
419                 break;
420             case OPTION_NO_DROP_ROOT:
421                 c->drop_root = 0;
422                 break;
423 #ifdef ENABLE_CHROOT
424             case OPTION_NO_CHROOT:
425                 c->use_chroot = 0;
426                 break;
427 #endif
428             case OPTION_NO_PROC_TITLE:
429                 c->modify_proc_title = 0;
430                 break;
431             case OPTION_DEBUG:
432                 c->debug = 1;
433                 break;
434             default:
435                 return -1;
436         }
437     }
438
439     if (optind < argc) {
440         fprintf(stderr, "Too many arguments\n");
441         return -1;
442     }
443         
444     return 0;
445 }
446
447 static int is_yes(const char *s) {
448     assert(s);
449     
450     return *s == 'y' || *s == 'Y' || *s == '1' || *s == 't' || *s == 'T';
451 }
452
453 static int load_config_file(DaemonConfig *c) {
454     int r = -1;
455     AvahiIniFile *f;
456     AvahiIniFileGroup *g;
457
458     assert(c);
459
460     if (!(f = avahi_ini_file_load(c->config_file ? c->config_file : AVAHI_CONFIG_FILE)))
461         goto finish;
462     
463     for (g = f->groups; g; g = g->groups_next) {
464         
465         if (strcasecmp(g->name, "server") == 0) {
466             AvahiIniFilePair *p;
467
468             for (p = g->pairs; p; p = p->pairs_next) {
469
470                 if (strcasecmp(p->key, "host-name") == 0) {
471                     avahi_free(c->server_config.host_name);
472                     c->server_config.host_name = avahi_strdup(p->value);
473                 } else if (strcasecmp(p->key, "domain-name") == 0) {
474                     avahi_free(c->server_config.domain_name);
475                     c->server_config.domain_name = avahi_strdup(p->value);
476                 } else if (strcasecmp(p->key, "browse-domains") == 0) {
477                     char **e, **t;
478
479                     e = avahi_split_csv(p->value);
480                     
481                     for (t = e; *t; t++) {
482                         char cleaned[AVAHI_DOMAIN_NAME_MAX];
483
484                         if (!avahi_normalize_name(*t, cleaned, sizeof(cleaned))) {
485                             avahi_log_error("Invalid domain name \"%s\" for key \"%s\" in group \"%s\"\n", *t, p->key, g->name);
486                             avahi_strfreev(e);
487                             goto finish;
488                         }
489
490                         c->server_config.browse_domains = avahi_string_list_add(c->server_config.browse_domains, cleaned);
491                     }
492                     
493                     avahi_strfreev(e);
494                 } else if (strcasecmp(p->key, "use-ipv4") == 0)
495                     c->server_config.use_ipv4 = is_yes(p->value);
496                 else if (strcasecmp(p->key, "use-ipv6") == 0)
497                     c->server_config.use_ipv6 = is_yes(p->value);
498                 else if (strcasecmp(p->key, "check-response-ttl") == 0)
499                     c->server_config.check_response_ttl = is_yes(p->value);
500                 else if (strcasecmp(p->key, "allow-point-to-point") == 0)
501                     c->server_config.allow_point_to_point = is_yes(p->value);
502                 else if (strcasecmp(p->key, "use-iff-running") == 0)
503                     c->server_config.use_iff_running = is_yes(p->value);
504                 else if (strcasecmp(p->key, "disallow-other-stacks") == 0)
505                     c->server_config.disallow_other_stacks = is_yes(p->value);
506 #ifdef HAVE_DBUS
507                 else if (strcasecmp(p->key, "enable-dbus") == 0) {
508
509                     if (*(p->value) == 'w' || *(p->value) == 'W') {
510                         c->fail_on_missing_dbus = 0;
511                         c->enable_dbus = 1;
512                     } else if (*(p->value) == 'y' || *(p->value) == 'Y') {
513                         c->fail_on_missing_dbus = 1;
514                         c->enable_dbus = 1;
515                     } else {
516                         c->enable_dbus = 0;
517                     }
518                 }
519 #endif
520                 else {
521                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
522                     goto finish;
523                 }
524             }
525             
526         } else if (strcasecmp(g->name, "publish") == 0) {
527             AvahiIniFilePair *p;
528
529             for (p = g->pairs; p; p = p->pairs_next) {
530                 
531                 if (strcasecmp(p->key, "publish-addresses") == 0)
532                     c->server_config.publish_addresses = is_yes(p->value);
533                 else if (strcasecmp(p->key, "publish-hinfo") == 0)
534                     c->server_config.publish_hinfo = is_yes(p->value);
535                 else if (strcasecmp(p->key, "publish-workstation") == 0)
536                     c->server_config.publish_workstation = is_yes(p->value);
537                 else if (strcasecmp(p->key, "publish-domain") == 0)
538                     c->server_config.publish_domain = is_yes(p->value);
539                 else if (strcasecmp(p->key, "publish-resolv-conf-dns-servers") == 0)
540                     c->publish_resolv_conf = is_yes(p->value);
541                 else if (strcasecmp(p->key, "disable-publishing") == 0)
542                     c->server_config.disable_publishing = is_yes(p->value);
543                 else if (strcasecmp(p->key, "disable-user-service-publishing") == 0)
544                     c->disable_user_service_publishing = is_yes(p->value);
545                 else if (strcasecmp(p->key, "add-service-cookie") == 0)
546                     c->server_config.add_service_cookie = is_yes(p->value);
547                 else if (strcasecmp(p->key, "publish-dns-servers") == 0) {
548                     avahi_strfreev(c->publish_dns_servers);
549                     c->publish_dns_servers = avahi_split_csv(p->value);
550                 } else if (strcasecmp(p->key, "publish-a-on-ipv6") == 0)
551                     c->server_config.publish_a_on_ipv6 = is_yes(p->value);
552                 else if (strcasecmp(p->key, "publish-aaaa-on-ipv4") == 0)
553                     c->server_config.publish_aaaa_on_ipv4 = is_yes(p->value);
554                 else {
555                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
556                     goto finish;
557                 }
558             }
559
560         } else if (strcasecmp(g->name, "wide-area") == 0) {
561             AvahiIniFilePair *p;
562
563             for (p = g->pairs; p; p = p->pairs_next) {
564                 
565                 if (strcasecmp(p->key, "enable-wide-area") == 0)
566                     c->server_config.enable_wide_area = is_yes(p->value);
567                 else {
568                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
569                     goto finish;
570                 }
571             }
572             
573         } else if (strcasecmp(g->name, "reflector") == 0) {
574             AvahiIniFilePair *p;
575
576             for (p = g->pairs; p; p = p->pairs_next) {
577                 
578                 if (strcasecmp(p->key, "enable-reflector") == 0)
579                     c->server_config.enable_reflector = is_yes(p->value);
580                 else if (strcasecmp(p->key, "reflect-ipv") == 0)
581                     c->server_config.reflect_ipv = is_yes(p->value);
582                 else {
583                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
584                     goto finish;
585                 }
586             }
587             
588         } else if (strcasecmp(g->name, "rlimits") == 0) {
589             AvahiIniFilePair *p;
590
591             for (p = g->pairs; p; p = p->pairs_next) {
592                 
593                 if (strcasecmp(p->key, "rlimit-as") == 0) {
594                     c->rlimit_as_set = 1;
595                     c->rlimit_as = atoi(p->value);
596                 } else if (strcasecmp(p->key, "rlimit-core") == 0) {
597                     c->rlimit_core_set = 1;
598                     c->rlimit_core = atoi(p->value);
599                 } else if (strcasecmp(p->key, "rlimit-data") == 0) {
600                     c->rlimit_data_set = 1;
601                     c->rlimit_data = atoi(p->value);
602                 } else if (strcasecmp(p->key, "rlimit-fsize") == 0) {
603                     c->rlimit_fsize_set = 1;
604                     c->rlimit_fsize = atoi(p->value);
605                 } else if (strcasecmp(p->key, "rlimit-nofile") == 0) {
606                     c->rlimit_nofile_set = 1;
607                     c->rlimit_nofile = atoi(p->value);
608                 } else if (strcasecmp(p->key, "rlimit-stack") == 0) {
609                     c->rlimit_stack_set = 1;
610                     c->rlimit_stack = atoi(p->value);
611                 } else if (strcasecmp(p->key, "rlimit-nproc") == 0) {
612 #ifdef RLIMIT_NPROC
613                     c->rlimit_nproc_set = 1;
614                     c->rlimit_nproc = atoi(p->value);
615 #else
616                     avahi_log_error("Ignoring configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
617 #endif
618                 } else {
619                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
620                     goto finish;
621                 }
622
623             }
624             
625         } else {
626             avahi_log_error("Invalid configuration file group \"%s\".\n", g->name);
627             goto finish;
628         }
629     }
630
631     r = 0;
632
633 finish:
634
635     if (f)
636         avahi_ini_file_free(f);
637     
638     return r;
639 }
640
641 static void log_function(AvahiLogLevel level, const char *txt) {
642
643     static const int log_level_map[] = {
644         LOG_ERR,
645         LOG_WARNING,
646         LOG_NOTICE,
647         LOG_INFO,
648         LOG_DEBUG
649     };
650     
651     assert(level < AVAHI_LOG_LEVEL_MAX);
652     assert(txt);
653
654     if (!config.debug && level == AVAHI_LOG_DEBUG)
655         return;
656
657     daemon_log(log_level_map[level], "%s", txt);
658 }
659
660 static void dump(const char *text, AVAHI_GCC_UNUSED void* userdata) {
661     avahi_log_info("%s", text);
662 }
663
664 #ifdef HAVE_INOTIFY
665
666 static int inotify_fd = -1;
667
668 static void add_inotify_watches(void) {
669     int c = 0;
670     /* We ignore the return values, because one or more of these files
671      * might not exist and we're OK with that. In addition we never
672      * want to remove these watches, hence we keep their ids? */
673
674 #ifdef ENABLE_CHROOT
675     c = config.use_chroot;
676 #endif
677     
678     inotify_add_watch(inotify_fd, c ? "/services" : AVAHI_SERVICE_DIR, IN_CLOSE_WRITE|IN_DELETE|IN_DELETE_SELF|IN_MOVED_FROM|IN_MOVED_TO|IN_MOVE_SELF|IN_ONLYDIR);
679     inotify_add_watch(inotify_fd, c ? "/" : AVAHI_CONFIG_DIR, IN_CLOSE_WRITE|IN_DELETE|IN_DELETE_SELF|IN_MOVED_FROM|IN_MOVED_TO|IN_MOVE_SELF|IN_ONLYDIR);
680 }
681
682 #endif
683
684 static void reload_config(void) {
685
686 #ifdef HAVE_INOTIFY
687     /* Refresh in case the config dirs have been removed */
688     add_inotify_watches();
689 #endif
690
691 #ifdef ENABLE_CHROOT
692     static_service_load(config.use_chroot);
693     static_hosts_load(config.use_chroot);
694 #else
695     static_service_load(0);
696     static_hosts_load(0);
697 #endif            
698     static_service_add_to_server();
699     static_hosts_add_to_server();
700     
701     if (resolv_conf_entry_group)
702         avahi_s_entry_group_reset(resolv_conf_entry_group);
703     
704     load_resolv_conf();
705     
706     update_wide_area_servers();
707     
708     if (config.publish_resolv_conf && resolv_conf && resolv_conf[0])
709         resolv_conf_entry_group = add_dns_servers(avahi_server, resolv_conf_entry_group, resolv_conf);
710 }
711
712 #ifdef HAVE_INOTIFY
713
714 static void inotify_callback(AvahiWatch *watch, int fd, AVAHI_GCC_UNUSED AvahiWatchEvent event, AVAHI_GCC_UNUSED void *userdata) {
715     char* buffer;
716     int n = 0;
717
718     assert(fd == inotify_fd);
719     assert(watch);
720
721     ioctl(inotify_fd, FIONREAD, &n);
722     if (n <= 0)
723         n = 128;
724
725     buffer = avahi_malloc(n);
726     if (read(inotify_fd, buffer, n) < 0 ) {
727         avahi_free(buffer);
728         avahi_log_error("Failed to read inotify event: %s", avahi_strerror(errno));
729         return;
730     }
731     avahi_free(buffer);
732
733     avahi_log_info("Files changed, reloading.");
734     reload_config();
735 }
736
737 #endif
738
739 static void signal_callback(AvahiWatch *watch, AVAHI_GCC_UNUSED int fd, AVAHI_GCC_UNUSED AvahiWatchEvent event, AVAHI_GCC_UNUSED void *userdata) {
740     int sig;
741     const AvahiPoll *poll_api;
742     
743     assert(watch);
744     assert(simple_poll_api);
745
746     poll_api = avahi_simple_poll_get(simple_poll_api);
747
748     if ((sig = daemon_signal_next()) <= 0) {
749         avahi_log_error("daemon_signal_next() failed");
750         poll_api->watch_free(watch);
751         return;
752     }
753
754     switch (sig) {
755         case SIGINT:
756         case SIGQUIT:
757         case SIGTERM:
758             avahi_log_info(
759                 "Got %s, quitting.",
760                 sig == SIGINT ? "SIGINT" :
761                 (sig == SIGQUIT ? "SIGQUIT" : "SIGTERM"));
762             avahi_simple_poll_quit(simple_poll_api);
763             break;
764
765         case SIGHUP:
766             avahi_log_info("Got SIGHUP, reloading.");
767
768             reload_config();
769             break;
770
771         case SIGUSR1:
772             avahi_log_info("Got SIGUSR1, dumping record data.");
773             avahi_server_dump(avahi_server, dump, NULL);
774             break;
775
776         default:
777             avahi_log_warn("Got spurious signal, ignoring.");
778             break;
779     }
780 }
781
782 /* Imported from ../avahi-client/nss-check.c */
783 int avahi_nss_support(void);
784
785 static int run_server(DaemonConfig *c) {
786     int r = -1;
787     int error;
788     const AvahiPoll *poll_api = NULL;
789     AvahiWatch *sig_watch = NULL;
790     int retval_is_sent = 0;
791 #ifdef HAVE_INOTIFY
792     AvahiWatch *inotify_watch = NULL;
793 #endif
794
795     assert(c);
796
797     if (!(nss_support = avahi_nss_support()))
798         avahi_log_warn("WARNING: No NSS support for mDNS detected, consider installing nss-mdns!");
799
800     if (!(simple_poll_api = avahi_simple_poll_new())) {
801         avahi_log_error("Failed to create main loop object.");
802         goto finish;
803     }
804
805     poll_api = avahi_simple_poll_get(simple_poll_api);
806
807     if (daemon_signal_init(SIGINT, SIGQUIT, SIGHUP, SIGTERM, SIGUSR1, 0) < 0) {
808         avahi_log_error("Could not register signal handlers (%s).", strerror(errno));
809         goto finish;
810     }
811
812     if (!(sig_watch = poll_api->watch_new(poll_api, daemon_signal_fd(), AVAHI_WATCH_IN, signal_callback, simple_poll_api))) {
813         avahi_log_error( "Failed to create signal watcher");
814         goto finish;
815     }
816
817     if (simple_protocol_setup(poll_api) < 0)
818         goto finish;
819
820 #ifdef HAVE_DBUS
821     if (c->enable_dbus) {
822         if (dbus_protocol_setup(poll_api, config.disable_user_service_publishing, !c->fail_on_missing_dbus
823 #ifdef ENABLE_CHROOT
824                                 && !config.use_chroot
825 #endif
826             ) < 0) {
827
828             avahi_log_warn("WARNING: Failed to contact D-Bus daemon.");
829
830             if (c->fail_on_missing_dbus)
831                 goto finish;
832         }
833     }
834 #endif
835
836 #ifdef ENABLE_CHROOT
837
838     if (config.drop_root && config.use_chroot) {
839         if (chroot(AVAHI_CONFIG_DIR) < 0) {
840             avahi_log_error("Failed to chroot(): %s", strerror(errno));
841             goto finish;
842         }
843         
844         avahi_log_info("Successfully called chroot().");
845         chdir("/");
846         
847         if (avahi_caps_drop_all() < 0) {
848             avahi_log_error("Failed to drop capabilities.");
849             goto finish;
850         }
851         avahi_log_info("Successfully dropped remaining capabilities.");
852     }
853     
854 #endif
855
856 #ifdef HAVE_INOTIFY
857     if ((inotify_fd = inotify_init()) < 0)
858         avahi_log_warn( "Failed to initialize inotify: %s", strerror(errno));
859     else {
860         add_inotify_watches();
861         
862         if (!(inotify_watch = poll_api->watch_new(poll_api, inotify_fd, AVAHI_WATCH_IN, inotify_callback, NULL))) {
863             avahi_log_error( "Failed to create inotify watcher");
864             goto finish;
865         }
866     }
867 #endif
868
869     load_resolv_conf();
870 #ifdef ENABLE_CHROOT
871     static_service_load(config.use_chroot);
872     static_hosts_load(config.use_chroot);
873 #else
874     static_service_load(0);
875     static_hosts_load(0);
876 #endif
877
878     if (!(avahi_server = avahi_server_new(poll_api, &c->server_config, server_callback, c, &error))) {
879         avahi_log_error("Failed to create server: %s", avahi_strerror(error));
880         goto finish;
881     }
882
883     update_wide_area_servers();
884
885     if (c->daemonize) {
886         daemon_retval_send(0);
887         retval_is_sent = 1;
888     }
889
890     for (;;) {
891         if ((r = avahi_simple_poll_iterate(simple_poll_api, -1)) < 0) {
892
893             /* We handle signals through an FD, so let's continue */
894             if (errno == EINTR)
895                 continue;
896             
897             avahi_log_error("poll(): %s", strerror(errno));
898             goto finish;
899         } else if (r > 0)
900             /* Quit */
901             break;
902     }
903     
904
905 finish:
906     
907     static_service_remove_from_server();
908     static_service_free_all();
909
910     static_hosts_remove_from_server();
911     static_hosts_free_all();
912
913     remove_dns_server_entry_groups();
914     
915     simple_protocol_shutdown();
916
917 #ifdef HAVE_DBUS
918     if (c->enable_dbus)
919         dbus_protocol_shutdown();
920 #endif
921
922     if (avahi_server) {
923         avahi_server_free(avahi_server);
924         avahi_server = NULL;
925     }
926
927     daemon_signal_done();
928
929     if (sig_watch)
930         poll_api->watch_free(sig_watch);
931
932 #ifdef HAVE_INOTIFY
933     if (inotify_watch)
934         poll_api->watch_free(inotify_watch);
935     if (inotify_fd >= 0)
936         close(inotify_fd);
937 #endif
938     
939     if (simple_poll_api) {
940         avahi_simple_poll_free(simple_poll_api);
941         simple_poll_api = NULL;
942     }
943
944     if (!retval_is_sent && c->daemonize)
945         daemon_retval_send(1);
946     
947     return r;
948 }
949
950 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
951
952 static int drop_root(void) {
953     struct passwd *pw;
954     struct group * gr;
955     int r;
956     
957     if (!(pw = getpwnam(AVAHI_USER))) {
958         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
959         return -1;
960     }
961
962     if (!(gr = getgrnam(AVAHI_GROUP))) {
963         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
964         return -1;
965     }
966
967     avahi_log_info("Found user '"AVAHI_USER"' (UID %lu) and group '"AVAHI_GROUP"' (GID %lu).", (unsigned long) pw->pw_uid, (unsigned long) gr->gr_gid);
968
969     if (initgroups(AVAHI_USER, gr->gr_gid) != 0) {
970         avahi_log_error("Failed to change group list: %s", strerror(errno));
971         return -1;
972     }
973
974 #if defined(HAVE_SETRESGID)
975     r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
976 #elif defined(HAVE_SETEGID)
977     if ((r = setgid(gr->gr_gid)) >= 0)
978         r = setegid(gr->gr_gid);
979 #elif defined(HAVE_SETREGID)
980     r = setregid(gr->gr_gid, gr->gr_gid);
981 #else
982 #error "No API to drop priviliges"
983 #endif
984
985     if (r < 0) {
986         avahi_log_error("Failed to change GID: %s", strerror(errno));
987         return -1;
988     }
989
990 #if defined(HAVE_SETRESUID)
991     r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
992 #elif defined(HAVE_SETEUID)
993     if ((r = setuid(pw->pw_uid)) >= 0)
994         r = seteuid(pw->pw_uid);
995 #elif defined(HAVE_SETREUID)
996     r = setreuid(pw->pw_uid, pw->pw_uid);
997 #else
998 #error "No API to drop priviliges"
999 #endif
1000
1001     if (r < 0) {
1002         avahi_log_error("Failed to change UID: %s", strerror(errno));
1003         return -1;
1004     }
1005
1006     set_env("USER", pw->pw_name);
1007     set_env("LOGNAME", pw->pw_name);
1008     set_env("HOME", pw->pw_dir);
1009
1010     avahi_log_info("Successfully dropped root privileges.");
1011
1012     return 0;
1013 }
1014
1015 static const char* pid_file_proc(void) {
1016     return AVAHI_DAEMON_RUNTIME_DIR"/pid";
1017 }
1018
1019 static int make_runtime_dir(void) {
1020     int r = -1;
1021     mode_t u;
1022     int reset_umask = 0;
1023     struct passwd *pw;
1024     struct group * gr;
1025     struct stat st;
1026
1027     if (!(pw = getpwnam(AVAHI_USER))) {
1028         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
1029         goto fail;
1030     }
1031
1032     if (!(gr = getgrnam(AVAHI_GROUP))) {
1033         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
1034         goto fail;
1035     }
1036
1037     u = umask(0000);
1038     reset_umask = 1;
1039     
1040     if (mkdir(AVAHI_DAEMON_RUNTIME_DIR, 0755) < 0 && errno != EEXIST) {
1041         avahi_log_error("mkdir(\""AVAHI_DAEMON_RUNTIME_DIR"\"): %s", strerror(errno));
1042         goto fail;
1043     }
1044     
1045     chown(AVAHI_DAEMON_RUNTIME_DIR, pw->pw_uid, gr->gr_gid);
1046
1047     if (stat(AVAHI_DAEMON_RUNTIME_DIR, &st) < 0) {
1048         avahi_log_error("stat(): %s\n", strerror(errno));
1049         goto fail;
1050     }
1051
1052     if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
1053         avahi_log_error("Failed to create runtime directory "AVAHI_DAEMON_RUNTIME_DIR".");
1054         goto fail;
1055     }
1056
1057     r = 0;
1058
1059 fail:
1060     if (reset_umask)
1061         umask(u);
1062     return r;
1063 }
1064
1065 static void set_one_rlimit(int resource, rlim_t limit, const char *name) {
1066     struct rlimit rl;
1067     rl.rlim_cur = rl.rlim_max = limit;
1068
1069     if (setrlimit(resource, &rl) < 0)
1070         avahi_log_warn("setrlimit(%s, {%u, %u}) failed: %s", name, (unsigned) limit, (unsigned) limit, strerror(errno));
1071 }
1072
1073 static void enforce_rlimits(void) {
1074 #ifdef RLIMIT_AS
1075     if (config.rlimit_as_set)
1076         set_one_rlimit(RLIMIT_AS, config.rlimit_as, "RLIMIT_AS");
1077 #endif
1078     if (config.rlimit_core_set)
1079         set_one_rlimit(RLIMIT_CORE, config.rlimit_core, "RLIMIT_CORE");
1080     if (config.rlimit_data_set)
1081         set_one_rlimit(RLIMIT_DATA, config.rlimit_data, "RLIMIT_DATA");
1082     if (config.rlimit_fsize_set)
1083         set_one_rlimit(RLIMIT_FSIZE, config.rlimit_fsize, "RLIMIT_FSIZE");
1084     if (config.rlimit_nofile_set)
1085         set_one_rlimit(RLIMIT_NOFILE, config.rlimit_nofile, "RLIMIT_NOFILE");
1086     if (config.rlimit_stack_set)
1087         set_one_rlimit(RLIMIT_STACK, config.rlimit_stack, "RLIMIT_STACK");
1088 #ifdef RLIMIT_NPROC
1089     if (config.rlimit_nproc_set)
1090         set_one_rlimit(RLIMIT_NPROC, config.rlimit_nproc, "RLIMIT_NPROC");
1091 #endif
1092
1093     /* the sysctl() call from iface-pfroute.c needs locked memory on FreeBSD */
1094 #if defined(RLIMIT_MEMLOCK) && !defined(__FreeBSD__)
1095     /* We don't need locked memory */
1096     set_one_rlimit(RLIMIT_MEMLOCK, 0, "RLIMIT_MEMLOCK");
1097 #endif
1098 }
1099
1100 #define RANDOM_DEVICE "/dev/urandom"
1101
1102 static void init_rand_seed(void) {
1103     int fd;
1104     unsigned seed = 0;
1105
1106     /* Try to initialize seed from /dev/urandom, to make it a little
1107      * less predictable, and to make sure that multiple machines
1108      * booted at the same time choose different random seeds.  */
1109     if ((fd = open(RANDOM_DEVICE, O_RDONLY)) >= 0) {
1110         read(fd, &seed, sizeof(seed));
1111         close(fd);
1112     }
1113
1114     /* If the initialization failed by some reason, we add the time to the seed*/
1115     seed ^= (unsigned) time(NULL);
1116
1117     srand(seed);
1118 }
1119
1120 int main(int argc, char *argv[]) {
1121     int r = 255;
1122     int wrote_pid_file = 0;
1123
1124     avahi_set_log_function(log_function);
1125
1126     init_rand_seed();
1127     
1128     avahi_server_config_init(&config.server_config);
1129     config.command = DAEMON_RUN;
1130     config.daemonize = 0;
1131     config.config_file = NULL;
1132 #ifdef HAVE_DBUS
1133     config.enable_dbus = 1;
1134     config.fail_on_missing_dbus = 1;
1135 #endif
1136     
1137     config.drop_root = 1;
1138     config.set_rlimits = 1;
1139 #ifdef ENABLE_CHROOT
1140     config.use_chroot = 1;
1141 #endif
1142     config.modify_proc_title = 1;
1143
1144     config.disable_user_service_publishing = 0;
1145     config.publish_dns_servers = NULL;
1146     config.publish_resolv_conf = 0;
1147     config.use_syslog = 0;
1148     config.debug = 0;
1149     config.rlimit_as_set = 0;
1150     config.rlimit_core_set = 0;
1151     config.rlimit_data_set = 0;
1152     config.rlimit_fsize_set = 0;
1153     config.rlimit_nofile_set = 0;
1154     config.rlimit_stack_set = 0;
1155 #ifdef RLIMIT_NPROC
1156     config.rlimit_nproc_set = 0;
1157 #endif
1158     
1159     if ((argv0 = strrchr(argv[0], '/')))
1160         argv0 = avahi_strdup(argv0 + 1);
1161     else
1162         argv0 = avahi_strdup(argv[0]);
1163
1164     daemon_pid_file_ident = (const char *) argv0;
1165     daemon_log_ident = (char*) argv0;
1166     daemon_pid_file_proc = pid_file_proc;
1167     
1168     if (parse_command_line(&config, argc, argv) < 0)
1169         goto finish;
1170
1171     if (config.modify_proc_title)
1172         avahi_init_proc_title(argc, argv);
1173
1174 #ifdef ENABLE_CHROOT
1175     config.use_chroot = config.use_chroot && config.drop_root;
1176 #endif
1177     
1178     if (config.command == DAEMON_HELP) {
1179         help(stdout);
1180         r = 0;
1181     } else if (config.command == DAEMON_VERSION) {
1182         printf("%s "PACKAGE_VERSION"\n", argv0);
1183         r = 0;
1184     } else if (config.command == DAEMON_KILL) {
1185         if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
1186             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
1187             goto finish;
1188         }
1189
1190         r = 0;
1191
1192     } else if (config.command == DAEMON_RELOAD) {
1193         if (daemon_pid_file_kill(SIGHUP) < 0) {
1194             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
1195             goto finish;
1196         }
1197
1198         r = 0;
1199         
1200     } else if (config.command == DAEMON_CHECK)
1201         r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
1202     else if (config.command == DAEMON_RUN) {
1203         pid_t pid;
1204
1205         if (getuid() != 0 && config.drop_root) {
1206             avahi_log_error("This program is intended to be run as root.");
1207             goto finish;
1208         }
1209         
1210         if ((pid = daemon_pid_file_is_running()) >= 0) {
1211             avahi_log_error("Daemon already running on PID %u", pid);
1212             goto finish;
1213         }
1214
1215         if (load_config_file(&config) < 0)
1216             goto finish;
1217         
1218         if (config.daemonize) {
1219             daemon_retval_init();
1220             
1221             if ((pid = daemon_fork()) < 0)
1222                 goto finish;
1223             else if (pid != 0) {
1224                 int ret;
1225                 /** Parent **/
1226
1227                 if ((ret = daemon_retval_wait(20)) < 0) {
1228                     avahi_log_error("Could not receive return value from daemon process.");
1229                     goto finish;
1230                 }
1231
1232                 r = ret;
1233                 goto finish;
1234             }
1235
1236             /* Child */
1237         }
1238
1239         if (config.use_syslog || config.daemonize)
1240             daemon_log_use = DAEMON_LOG_SYSLOG;
1241
1242         if (make_runtime_dir() < 0)
1243             goto finish;
1244
1245         if (config.drop_root) {
1246 #ifdef ENABLE_CHROOT
1247             if (config.use_chroot)
1248                 if (avahi_caps_reduce() < 0)
1249                     goto finish;
1250 #endif
1251             
1252             if (drop_root() < 0)
1253                 goto finish;
1254
1255 #ifdef ENABLE_CHROOT
1256             if (config.use_chroot)
1257                 if (avahi_caps_reduce2() < 0)
1258                     goto finish;
1259 #endif
1260         }
1261
1262         if (daemon_pid_file_create() < 0) {
1263             avahi_log_error("Failed to create PID file: %s", strerror(errno));
1264
1265             if (config.daemonize)
1266                 daemon_retval_send(1);
1267             goto finish;
1268         } else
1269             wrote_pid_file = 1;
1270
1271         if (config.set_rlimits)
1272             enforce_rlimits();
1273
1274         chdir("/");
1275
1276 #ifdef ENABLE_CHROOT
1277         if (config.drop_root && config.use_chroot)
1278             if (avahi_chroot_helper_start(argv0) < 0) {
1279                 avahi_log_error("failed to start chroot() helper daemon.");
1280                 goto finish;
1281             }
1282 #endif
1283         avahi_log_info("%s "PACKAGE_VERSION" starting up.", argv0);
1284
1285         avahi_set_proc_title(argv0, "%s: starting up", argv0);
1286         
1287         if (run_server(&config) == 0)
1288             r = 0;
1289     }
1290         
1291 finish:
1292
1293     if (config.daemonize)
1294         daemon_retval_done();
1295
1296     avahi_server_config_free(&config.server_config);
1297     avahi_free(config.config_file);
1298     avahi_strfreev(config.publish_dns_servers);
1299     avahi_strfreev(resolv_conf);
1300
1301     if (wrote_pid_file) {
1302 #ifdef ENABLE_CHROOT
1303         avahi_chroot_helper_unlink(pid_file_proc());
1304 #else
1305         daemon_pid_file_remove();
1306 #endif
1307     }
1308
1309 #ifdef ENABLE_CHROOT
1310     avahi_chroot_helper_shutdown();
1311 #endif
1312
1313     avahi_free(argv0);
1314     
1315     return r;
1316 }