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