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