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