]> git.meshlink.io Git - catta/blob - avahi-daemon/main.c
get rid of a lot of old svn cruft
[catta] / avahi-daemon / main.c
1 /***
2   This file is part of avahi.
3
4   avahi is free software; you can redistribute it and/or modify it
5   under the terms of the GNU Lesser General Public License as
6   published by the Free Software Foundation; either version 2.1 of the
7   License, or (at your option) any later version.
8
9   avahi is distributed in the hope that it will be useful, but WITHOUT
10   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11   or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
12   Public License for more details.
13
14   You should have received a copy of the GNU Lesser General Public
15   License along with avahi; if not, write to the Free Software
16   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
17   USA.
18 ***/
19
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
23
24 #include <assert.h>
25 #include <getopt.h>
26 #include <string.h>
27 #include <signal.h>
28 #include <errno.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <grp.h>
32 #include <pwd.h>
33 #include <sys/stat.h>
34 #include <sys/ioctl.h>
35 #include <stdio.h>
36 #include <fcntl.h>
37 #include <time.h>
38 #include <stdlib.h>
39 #include <sys/time.h>
40 #include <sys/resource.h>
41 #include <sys/socket.h>
42
43 #ifdef HAVE_INOTIFY
44 #include <sys/inotify.h>
45 #endif
46
47 #ifdef HAVE_KQUEUE
48 #include <sys/types.h>
49 #include <sys/event.h>
50 #include <unistd.h>
51 #endif
52
53 #include <libdaemon/dfork.h>
54 #include <libdaemon/dsignal.h>
55 #include <libdaemon/dlog.h>
56 #include <libdaemon/dpid.h>
57
58 #include <avahi-common/malloc.h>
59 #include <avahi-common/simple-watch.h>
60 #include <avahi-common/error.h>
61 #include <avahi-common/alternative.h>
62 #include <avahi-common/domain.h>
63
64 #include <avahi-core/core.h>
65 #include <avahi-core/publish.h>
66 #include <avahi-core/dns-srv-rr.h>
67 #include <avahi-core/log.h>
68
69 #ifdef ENABLE_CHROOT
70 #include "chroot.h"
71 #include "caps.h"
72 #endif
73
74 #include "setproctitle.h"
75 #include "main.h"
76 #include "simple-protocol.h"
77 #include "static-services.h"
78 #include "static-hosts.h"
79 #include "ini-file-parser.h"
80 #include "sd-daemon.h"
81
82 #ifdef HAVE_DBUS
83 #include "dbus-protocol.h"
84 #endif
85
86 AvahiServer *avahi_server = NULL;
87 AvahiSimplePoll *simple_poll_api = NULL;
88 static char *argv0 = NULL;
89 int nss_support = 0;
90
91 typedef enum {
92     DAEMON_RUN,
93     DAEMON_KILL,
94     DAEMON_VERSION,
95     DAEMON_HELP,
96     DAEMON_RELOAD,
97     DAEMON_CHECK
98 } DaemonCommand;
99
100 typedef struct {
101     AvahiServerConfig server_config;
102     DaemonCommand command;
103     int daemonize;
104     int use_syslog;
105     char *config_file;
106 #ifdef HAVE_DBUS
107     int enable_dbus;
108     int fail_on_missing_dbus;
109 #endif
110     int drop_root;
111     int set_rlimits;
112 #ifdef ENABLE_CHROOT
113     int use_chroot;
114 #endif
115     int modify_proc_title;
116
117     int disable_user_service_publishing;
118     int publish_resolv_conf;
119     char ** publish_dns_servers;
120     int debug;
121
122     int rlimit_as_set, rlimit_core_set, rlimit_data_set, rlimit_fsize_set, rlimit_nofile_set, rlimit_stack_set;
123     rlim_t rlimit_as, rlimit_core, rlimit_data, rlimit_fsize, rlimit_nofile, rlimit_stack;
124
125 #ifdef RLIMIT_NPROC
126     int rlimit_nproc_set;
127     rlim_t rlimit_nproc;
128 #endif
129 } DaemonConfig;
130
131 #define RESOLV_CONF "/etc/resolv.conf"
132 #define BROWSE_DOMAINS_MAX 16
133
134 static AvahiSEntryGroup *dns_servers_entry_group = NULL;
135 static AvahiSEntryGroup *resolv_conf_entry_group = NULL;
136
137 static char **resolv_conf_name_servers = NULL;
138 static char **resolv_conf_search_domains = NULL;
139
140 static DaemonConfig config;
141
142 static int has_prefix(const char *s, const char *prefix) {
143     size_t l;
144
145     l = strlen(prefix);
146
147     return strlen(s) >= l && strncmp(s, prefix, l) == 0;
148 }
149
150 static int load_resolv_conf(void) {
151     int ret = -1;
152     FILE *f;
153     int i = 0, j = 0;
154
155     avahi_strfreev(resolv_conf_name_servers);
156     resolv_conf_name_servers = NULL;
157
158     avahi_strfreev(resolv_conf_search_domains);
159     resolv_conf_search_domains = NULL;
160
161 #ifdef ENABLE_CHROOT
162     f = avahi_chroot_helper_get_file(RESOLV_CONF);
163 #else
164     f = fopen(RESOLV_CONF, "r");
165 #endif
166
167     if (!f) {
168         avahi_log_warn("Failed to open "RESOLV_CONF": %s", strerror(errno));
169         goto finish;
170     }
171
172     resolv_conf_name_servers = avahi_new0(char*, AVAHI_WIDE_AREA_SERVERS_MAX+1);
173     resolv_conf_search_domains = avahi_new0(char*, BROWSE_DOMAINS_MAX+1);
174
175     while (!feof(f)) {
176         char ln[128];
177         char *p;
178
179         if (!(fgets(ln, sizeof(ln), f)))
180             break;
181
182         ln[strcspn(ln, "\r\n#")] = 0;
183         p = ln + strspn(ln, "\t ");
184
185         if ((has_prefix(p, "nameserver ") || has_prefix(p, "nameserver\t")) && i < AVAHI_WIDE_AREA_SERVERS_MAX) {
186             p += 10;
187             p += strspn(p, "\t ");
188             p[strcspn(p, "\t ")] = 0;
189             resolv_conf_name_servers[i++] = avahi_strdup(p);
190         }
191
192         if ((has_prefix(p, "search ") || has_prefix(p, "search\t") ||
193              has_prefix(p, "domain ") || has_prefix(p, "domain\t"))) {
194
195             p += 6;
196
197             while (j < BROWSE_DOMAINS_MAX) {
198                 size_t k;
199
200                 p += strspn(p, "\t ");
201                 k = strcspn(p, "\t ");
202
203                 if (k > 0) {
204                     resolv_conf_search_domains[j++] = avahi_strndup(p, k);
205                     p += k;
206                 }
207
208                 if (!*p)
209                     break;
210             }
211         }
212     }
213
214     ret = 0;
215
216 finish:
217
218     if (ret != 0) {
219         avahi_strfreev(resolv_conf_name_servers);
220         resolv_conf_name_servers = NULL;
221
222         avahi_strfreev(resolv_conf_search_domains);
223         resolv_conf_search_domains = NULL;
224     }
225
226     if (f)
227         fclose(f);
228
229     return ret;
230 }
231
232 static AvahiSEntryGroup* add_dns_servers(AvahiServer *s, AvahiSEntryGroup* g, char **l) {
233     char **p;
234
235     assert(s);
236     assert(l);
237
238     if (!g)
239         g = avahi_s_entry_group_new(s, NULL, NULL);
240
241     assert(avahi_s_entry_group_is_empty(g));
242
243     for (p = l; *p; p++) {
244         AvahiAddress a;
245
246         if (!avahi_address_parse(*p, AVAHI_PROTO_UNSPEC, &a))
247             avahi_log_warn("Failed to parse address '%s', ignoring.", *p);
248         else
249             if (avahi_server_add_dns_server_address(s, g, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, 0, NULL, AVAHI_DNS_SERVER_RESOLVE, &a, 53) < 0) {
250                 avahi_s_entry_group_free(g);
251                 avahi_log_error("Failed to add DNS server address: %s", avahi_strerror(avahi_server_errno(s)));
252                 return NULL;
253             }
254     }
255
256     avahi_s_entry_group_commit(g);
257
258     return g;
259 }
260
261 static void remove_dns_server_entry_groups(void) {
262
263     if (resolv_conf_entry_group)
264         avahi_s_entry_group_reset(resolv_conf_entry_group);
265
266     if (dns_servers_entry_group)
267         avahi_s_entry_group_reset(dns_servers_entry_group);
268 }
269
270 static void update_wide_area_servers(void) {
271     AvahiAddress a[AVAHI_WIDE_AREA_SERVERS_MAX];
272     unsigned n = 0;
273     char **p;
274
275     if (!resolv_conf_name_servers) {
276         avahi_server_set_wide_area_servers(avahi_server, NULL, 0);
277         return;
278     }
279
280     for (p = resolv_conf_name_servers; *p && n < AVAHI_WIDE_AREA_SERVERS_MAX; p++) {
281         if (!avahi_address_parse(*p, AVAHI_PROTO_UNSPEC, &a[n]))
282             avahi_log_warn("Failed to parse address '%s', ignoring.", *p);
283         else
284             n++;
285     }
286
287     avahi_server_set_wide_area_servers(avahi_server, a, n);
288 }
289
290 static AvahiStringList *filter_duplicate_domains(AvahiStringList *l) {
291     AvahiStringList *e, *n, *p;
292
293     if (!l)
294         return l;
295
296     for (p = l, e = l->next; e; e = n) {
297         n = e->next;
298
299         if (avahi_domain_equal((char*) e->text, (char*) l->text)) {
300             p->next = e->next;
301             avahi_free(e);
302         } else
303             p = e;
304     }
305
306     l->next = filter_duplicate_domains(l->next);
307     return l;
308 }
309
310 static void update_browse_domains(void) {
311     AvahiStringList *l;
312     int n;
313     char **p;
314
315     if (!resolv_conf_search_domains) {
316         avahi_server_set_browse_domains(avahi_server, NULL);
317         return;
318     }
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 if (strcasecmp(p->key, "allow-interfaces") == 0) {
600                     char **e, **t;
601
602                     avahi_string_list_free(c->server_config.allow_interfaces);
603                     c->server_config.allow_interfaces = NULL;
604                     e = avahi_split_csv(p->value);
605
606                     for (t = e; *t; t++)
607                         c->server_config.allow_interfaces = avahi_string_list_add(c->server_config.allow_interfaces, *t);
608
609                     avahi_strfreev(e);
610                 } else if (strcasecmp(p->key, "deny-interfaces") == 0) {
611                     char **e, **t;
612
613                     avahi_string_list_free(c->server_config.deny_interfaces);
614                     c->server_config.deny_interfaces = NULL;
615                     e = avahi_split_csv(p->value);
616
617                     for (t = e; *t; t++)
618                         c->server_config.deny_interfaces = avahi_string_list_add(c->server_config.deny_interfaces, *t);
619
620                     avahi_strfreev(e);
621                 } else {
622                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
623                     goto finish;
624                 }
625             }
626
627         } else if (strcasecmp(g->name, "publish") == 0) {
628             AvahiIniFilePair *p;
629
630             for (p = g->pairs; p; p = p->pairs_next) {
631
632                 if (strcasecmp(p->key, "publish-addresses") == 0)
633                     c->server_config.publish_addresses = is_yes(p->value);
634                 else if (strcasecmp(p->key, "publish-hinfo") == 0)
635                     c->server_config.publish_hinfo = is_yes(p->value);
636                 else if (strcasecmp(p->key, "publish-workstation") == 0)
637                     c->server_config.publish_workstation = is_yes(p->value);
638                 else if (strcasecmp(p->key, "publish-domain") == 0)
639                     c->server_config.publish_domain = is_yes(p->value);
640                 else if (strcasecmp(p->key, "publish-resolv-conf-dns-servers") == 0)
641                     c->publish_resolv_conf = is_yes(p->value);
642                 else if (strcasecmp(p->key, "disable-publishing") == 0)
643                     c->server_config.disable_publishing = is_yes(p->value);
644                 else if (strcasecmp(p->key, "disable-user-service-publishing") == 0)
645                     c->disable_user_service_publishing = is_yes(p->value);
646                 else if (strcasecmp(p->key, "add-service-cookie") == 0)
647                     c->server_config.add_service_cookie = is_yes(p->value);
648                 else if (strcasecmp(p->key, "publish-dns-servers") == 0) {
649                     avahi_strfreev(c->publish_dns_servers);
650                     c->publish_dns_servers = avahi_split_csv(p->value);
651                 } else if (strcasecmp(p->key, "publish-a-on-ipv6") == 0)
652                     c->server_config.publish_a_on_ipv6 = is_yes(p->value);
653                 else if (strcasecmp(p->key, "publish-aaaa-on-ipv4") == 0)
654                     c->server_config.publish_aaaa_on_ipv4 = is_yes(p->value);
655                 else {
656                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
657                     goto finish;
658                 }
659             }
660
661         } else if (strcasecmp(g->name, "wide-area") == 0) {
662             AvahiIniFilePair *p;
663
664             for (p = g->pairs; p; p = p->pairs_next) {
665
666                 if (strcasecmp(p->key, "enable-wide-area") == 0)
667                     c->server_config.enable_wide_area = is_yes(p->value);
668                 else {
669                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
670                     goto finish;
671                 }
672             }
673
674         } else if (strcasecmp(g->name, "reflector") == 0) {
675             AvahiIniFilePair *p;
676
677             for (p = g->pairs; p; p = p->pairs_next) {
678
679                 if (strcasecmp(p->key, "enable-reflector") == 0)
680                     c->server_config.enable_reflector = is_yes(p->value);
681                 else if (strcasecmp(p->key, "reflect-ipv") == 0)
682                     c->server_config.reflect_ipv = is_yes(p->value);
683                 else {
684                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
685                     goto finish;
686                 }
687             }
688
689         } else if (strcasecmp(g->name, "rlimits") == 0) {
690             AvahiIniFilePair *p;
691
692             for (p = g->pairs; p; p = p->pairs_next) {
693
694                 if (strcasecmp(p->key, "rlimit-as") == 0) {
695                     c->rlimit_as_set = 1;
696                     c->rlimit_as = atoi(p->value);
697                 } else if (strcasecmp(p->key, "rlimit-core") == 0) {
698                     c->rlimit_core_set = 1;
699                     c->rlimit_core = atoi(p->value);
700                 } else if (strcasecmp(p->key, "rlimit-data") == 0) {
701                     c->rlimit_data_set = 1;
702                     c->rlimit_data = atoi(p->value);
703                 } else if (strcasecmp(p->key, "rlimit-fsize") == 0) {
704                     c->rlimit_fsize_set = 1;
705                     c->rlimit_fsize = atoi(p->value);
706                 } else if (strcasecmp(p->key, "rlimit-nofile") == 0) {
707                     c->rlimit_nofile_set = 1;
708                     c->rlimit_nofile = atoi(p->value);
709                 } else if (strcasecmp(p->key, "rlimit-stack") == 0) {
710                     c->rlimit_stack_set = 1;
711                     c->rlimit_stack = atoi(p->value);
712                 } else if (strcasecmp(p->key, "rlimit-nproc") == 0) {
713 #ifdef RLIMIT_NPROC
714                     c->rlimit_nproc_set = 1;
715                     c->rlimit_nproc = atoi(p->value);
716 #else
717                     avahi_log_error("Ignoring configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
718 #endif
719                 } else {
720                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
721                     goto finish;
722                 }
723
724             }
725
726         } else {
727             avahi_log_error("Invalid configuration file group \"%s\".\n", g->name);
728             goto finish;
729         }
730     }
731
732     r = 0;
733
734 finish:
735
736     if (f)
737         avahi_ini_file_free(f);
738
739     return r;
740 }
741
742 static void log_function(AvahiLogLevel level, const char *txt) {
743
744     static const int log_level_map[] = {
745         LOG_ERR,
746         LOG_WARNING,
747         LOG_NOTICE,
748         LOG_INFO,
749         LOG_DEBUG
750     };
751
752     assert(level < AVAHI_LOG_LEVEL_MAX);
753     assert(txt);
754
755     if (!config.debug && level == AVAHI_LOG_DEBUG)
756         return;
757
758     daemon_log(log_level_map[level], "%s", txt);
759 }
760
761 static void dump(const char *text, AVAHI_GCC_UNUSED void* userdata) {
762     avahi_log_info("%s", text);
763 }
764
765 #ifdef HAVE_INOTIFY
766
767 static int inotify_fd = -1;
768
769 static void add_inotify_watches(void) {
770     int c = 0;
771     /* We ignore the return values, because one or more of these files
772      * might not exist and we're OK with that. In addition we never
773      * want to remove these watches, hence we keep their ids? */
774
775 #ifdef ENABLE_CHROOT
776     c = config.use_chroot;
777 #endif
778
779     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
780 #ifdef IN_ONLYDIR
781                       |IN_ONLYDIR
782 #endif
783     );
784     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
785 #ifdef IN_ONLYDIR
786                       |IN_ONLYDIR
787 #endif
788     );
789 }
790
791 #endif
792
793 #ifdef HAVE_KQUEUE
794
795 #define NUM_WATCHES 2
796
797 static int kq = -1;
798 static int kfds[NUM_WATCHES];
799 static int num_kfds = 0;
800
801 static void add_kqueue_watch(const char *dir);
802
803 static void add_kqueue_watches(void) {
804     int c = 0;
805
806 #ifdef ENABLE_CHROOT
807     c = config.use_chroot;
808 #endif
809
810     add_kqueue_watch(c ? "/" : AVAHI_CONFIG_DIR);
811     add_kqueue_watch(c ? "/services" : AVAHI_SERVICE_DIR);
812 }
813
814 static void add_kqueue_watch(const char *dir) {
815     int fd;
816     struct kevent ev;
817
818     if (kq < 0)
819         return;
820
821     if (num_kfds >= NUM_WATCHES)
822         return;
823
824     fd = open(dir, O_RDONLY);
825     if (fd < 0)
826         return;
827     EV_SET(&ev, fd, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_CLEAR,
828            NOTE_DELETE | NOTE_EXTEND | NOTE_WRITE | NOTE_RENAME,
829            0, 0);
830     if (kevent(kq, &ev, 1, NULL, 0, NULL) == -1) {
831         close(fd);
832         return;
833     }
834
835     kfds[num_kfds++] = fd;
836 }
837
838 #endif
839
840 static void reload_config(void) {
841
842 #ifdef HAVE_INOTIFY
843     /* Refresh in case the config dirs have been removed */
844     add_inotify_watches();
845 #endif
846
847 #ifdef HAVE_KQUEUE
848     add_kqueue_watches();
849 #endif
850
851 #ifdef ENABLE_CHROOT
852     static_service_load(config.use_chroot);
853     static_hosts_load(config.use_chroot);
854 #else
855     static_service_load(0);
856     static_hosts_load(0);
857 #endif
858     static_service_add_to_server();
859     static_hosts_add_to_server();
860
861     if (resolv_conf_entry_group)
862         avahi_s_entry_group_reset(resolv_conf_entry_group);
863
864     load_resolv_conf();
865
866     update_wide_area_servers();
867     update_browse_domains();
868
869     if (config.publish_resolv_conf && resolv_conf_name_servers && resolv_conf_name_servers[0])
870         resolv_conf_entry_group = add_dns_servers(avahi_server, resolv_conf_entry_group, resolv_conf_name_servers);
871 }
872
873 #ifdef HAVE_INOTIFY
874
875 static void inotify_callback(AvahiWatch *watch, int fd, AVAHI_GCC_UNUSED AvahiWatchEvent event, AVAHI_GCC_UNUSED void *userdata) {
876     char* buffer;
877     int n = 0;
878
879     assert(fd == inotify_fd);
880     assert(watch);
881
882     ioctl(inotify_fd, FIONREAD, &n);
883     if (n <= 0)
884         n = 128;
885
886     buffer = avahi_malloc(n);
887     if (read(inotify_fd, buffer, n) < 0 ) {
888         avahi_free(buffer);
889         avahi_log_error("Failed to read inotify event: %s", avahi_strerror(errno));
890         return;
891     }
892     avahi_free(buffer);
893
894     avahi_log_info("Files changed, reloading.");
895     reload_config();
896 }
897
898 #endif
899
900 #ifdef HAVE_KQUEUE
901
902 static void kqueue_callback(AvahiWatch *watch, int fd, AVAHI_GCC_UNUSED AvahiWatchEvent event, AVAHI_GCC_UNUSED void *userdata) {
903     struct kevent ev;
904     struct timespec nullts = { 0, 0 };
905     int res;
906
907     assert(fd == kq);
908     assert(watch);
909
910     res = kevent(kq, NULL, 0, &ev, 1, &nullts);
911
912     if (res > 0) {
913         /* Sleep for a half-second to avoid potential races
914          * during install/uninstall. */
915         usleep(500000);
916         avahi_log_info("Files changed, reloading.");
917         reload_config();
918     } else {
919         avahi_log_error("Failed to read kqueue event: %s", avahi_strerror(errno));
920     }
921 }
922
923 #endif
924
925 static void signal_callback(AvahiWatch *watch, AVAHI_GCC_UNUSED int fd, AVAHI_GCC_UNUSED AvahiWatchEvent event, AVAHI_GCC_UNUSED void *userdata) {
926     int sig;
927     const AvahiPoll *poll_api;
928
929     assert(watch);
930     assert(simple_poll_api);
931
932     poll_api = avahi_simple_poll_get(simple_poll_api);
933
934     if ((sig = daemon_signal_next()) <= 0) {
935         avahi_log_error("daemon_signal_next() failed");
936         poll_api->watch_free(watch);
937         return;
938     }
939
940     switch (sig) {
941         case SIGINT:
942         case SIGQUIT:
943         case SIGTERM:
944             avahi_log_info(
945                     "Got %s, quitting.",
946                     sig == SIGINT ? "SIGINT" :
947                     (sig == SIGQUIT ? "SIGQUIT" : "SIGTERM"));
948             avahi_simple_poll_quit(simple_poll_api);
949             break;
950
951         case SIGHUP:
952             avahi_log_info("Got SIGHUP, reloading.");
953
954             reload_config();
955             break;
956
957         case SIGUSR1:
958             avahi_log_info("Got SIGUSR1, dumping record data.");
959             avahi_server_dump(avahi_server, dump, NULL);
960             break;
961
962         default:
963             avahi_log_warn("Got spurious signal, ignoring.");
964             break;
965     }
966 }
967
968 /* Imported from ../avahi-client/nss-check.c */
969 int avahi_nss_support(void);
970
971 static int run_server(DaemonConfig *c) {
972     int r = -1;
973     int error;
974     const AvahiPoll *poll_api = NULL;
975     AvahiWatch *sig_watch = NULL;
976     int retval_is_sent = 0;
977 #ifdef HAVE_INOTIFY
978     AvahiWatch *inotify_watch = NULL;
979 #endif
980 #ifdef HAVE_KQUEUE
981     int i;
982     AvahiWatch *kqueue_watch = NULL;
983 #endif
984
985     assert(c);
986
987     if (!(nss_support = avahi_nss_support()))
988         avahi_log_warn("WARNING: No NSS support for mDNS detected, consider installing nss-mdns!");
989
990     if (!(simple_poll_api = avahi_simple_poll_new())) {
991         avahi_log_error("Failed to create main loop object.");
992         goto finish;
993     }
994
995     poll_api = avahi_simple_poll_get(simple_poll_api);
996
997     if (daemon_signal_init(SIGINT, SIGQUIT, SIGHUP, SIGTERM, SIGUSR1, 0) < 0) {
998         avahi_log_error("Could not register signal handlers (%s).", strerror(errno));
999         goto finish;
1000     }
1001
1002     if (!(sig_watch = poll_api->watch_new(poll_api, daemon_signal_fd(), AVAHI_WATCH_IN, signal_callback, simple_poll_api))) {
1003         avahi_log_error( "Failed to create signal watcher");
1004         goto finish;
1005     }
1006
1007     if (simple_protocol_setup(poll_api) < 0)
1008         goto finish;
1009
1010 #ifdef HAVE_DBUS
1011     if (c->enable_dbus) {
1012         if (dbus_protocol_setup(poll_api, config.disable_user_service_publishing, !c->fail_on_missing_dbus
1013 #ifdef ENABLE_CHROOT
1014                                 && !config.use_chroot
1015 #endif
1016             ) < 0) {
1017
1018             avahi_log_warn("WARNING: Failed to contact D-Bus daemon.");
1019
1020             if (c->fail_on_missing_dbus)
1021                 goto finish;
1022         }
1023     }
1024 #endif
1025
1026 #ifdef ENABLE_CHROOT
1027
1028     if (config.drop_root && config.use_chroot) {
1029         if (chroot(AVAHI_CONFIG_DIR) < 0) {
1030             avahi_log_error("Failed to chroot(): %s", strerror(errno));
1031             goto finish;
1032         }
1033
1034         avahi_log_info("Successfully called chroot().");
1035         chdir("/");
1036
1037         if (avahi_caps_drop_all() < 0) {
1038             avahi_log_error("Failed to drop capabilities.");
1039             goto finish;
1040         }
1041         avahi_log_info("Successfully dropped remaining capabilities.");
1042     }
1043
1044 #endif
1045
1046 #ifdef HAVE_INOTIFY
1047     if ((inotify_fd = inotify_init()) < 0)
1048         avahi_log_warn( "Failed to initialize inotify: %s", strerror(errno));
1049     else {
1050         add_inotify_watches();
1051
1052         if (!(inotify_watch = poll_api->watch_new(poll_api, inotify_fd, AVAHI_WATCH_IN, inotify_callback, NULL))) {
1053             avahi_log_error( "Failed to create inotify watcher");
1054             goto finish;
1055         }
1056     }
1057 #endif
1058
1059 #ifdef HAVE_KQUEUE
1060     if ((kq = kqueue()) < 0)
1061         avahi_log_warn( "Failed to initialize kqueue: %s", strerror(errno));
1062     else {
1063         add_kqueue_watches();
1064
1065         if (!(kqueue_watch = poll_api->watch_new(poll_api, kq, AVAHI_WATCH_IN, kqueue_callback, NULL))) {
1066             avahi_log_error( "Failed to create kqueue watcher");
1067             goto finish;
1068         }
1069     }
1070 #endif
1071
1072     load_resolv_conf();
1073 #ifdef ENABLE_CHROOT
1074     static_service_load(config.use_chroot);
1075     static_hosts_load(config.use_chroot);
1076 #else
1077     static_service_load(0);
1078     static_hosts_load(0);
1079 #endif
1080
1081     if (!(avahi_server = avahi_server_new(poll_api, &c->server_config, server_callback, c, &error))) {
1082         avahi_log_error("Failed to create server: %s", avahi_strerror(error));
1083         goto finish;
1084     }
1085
1086     update_wide_area_servers();
1087     update_browse_domains();
1088
1089     if (c->daemonize) {
1090         daemon_retval_send(0);
1091         retval_is_sent = 1;
1092     }
1093
1094     for (;;) {
1095         if ((r = avahi_simple_poll_iterate(simple_poll_api, -1)) < 0) {
1096
1097             /* We handle signals through an FD, so let's continue */
1098             if (errno == EINTR)
1099                 continue;
1100
1101             avahi_log_error("poll(): %s", strerror(errno));
1102             goto finish;
1103         } else if (r > 0)
1104             /* Quit */
1105             break;
1106     }
1107
1108
1109 finish:
1110
1111     static_service_remove_from_server();
1112     static_service_free_all();
1113
1114     static_hosts_remove_from_server();
1115     static_hosts_free_all();
1116
1117     remove_dns_server_entry_groups();
1118
1119     simple_protocol_shutdown();
1120
1121 #ifdef HAVE_DBUS
1122     if (c->enable_dbus)
1123         dbus_protocol_shutdown();
1124 #endif
1125
1126     if (avahi_server) {
1127         avahi_server_free(avahi_server);
1128         avahi_server = NULL;
1129     }
1130
1131     daemon_signal_done();
1132
1133     if (sig_watch)
1134         poll_api->watch_free(sig_watch);
1135
1136 #ifdef HAVE_INOTIFY
1137     if (inotify_watch)
1138         poll_api->watch_free(inotify_watch);
1139     if (inotify_fd >= 0)
1140         close(inotify_fd);
1141 #endif
1142
1143 #ifdef HAVE_KQUEUE
1144     if (kqueue_watch)
1145         poll_api->watch_free(kqueue_watch);
1146     if (kq >= 0)
1147         close(kq);
1148     for (i = 0; i < num_kfds; i++) {
1149         if (kfds[i] >= 0)
1150             close(kfds[i]);
1151     }
1152 #endif
1153
1154     if (simple_poll_api) {
1155         avahi_simple_poll_free(simple_poll_api);
1156         simple_poll_api = NULL;
1157     }
1158
1159     if (!retval_is_sent && c->daemonize)
1160         daemon_retval_send(1);
1161
1162     return r;
1163 }
1164
1165 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
1166
1167 static int drop_root(void) {
1168     struct passwd *pw;
1169     struct group * gr;
1170     int r;
1171
1172     if (!(pw = getpwnam(AVAHI_USER))) {
1173         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
1174         return -1;
1175     }
1176
1177     if (!(gr = getgrnam(AVAHI_GROUP))) {
1178         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
1179         return -1;
1180     }
1181
1182     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);
1183
1184     if (initgroups(AVAHI_USER, gr->gr_gid) != 0) {
1185         avahi_log_error("Failed to change group list: %s", strerror(errno));
1186         return -1;
1187     }
1188
1189 #if defined(HAVE_SETRESGID)
1190     r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
1191 #elif defined(HAVE_SETEGID)
1192     if ((r = setgid(gr->gr_gid)) >= 0)
1193         r = setegid(gr->gr_gid);
1194 #elif defined(HAVE_SETREGID)
1195     r = setregid(gr->gr_gid, gr->gr_gid);
1196 #else
1197 #error "No API to drop privileges"
1198 #endif
1199
1200     if (r < 0) {
1201         avahi_log_error("Failed to change GID: %s", strerror(errno));
1202         return -1;
1203     }
1204
1205 #if defined(HAVE_SETRESUID)
1206     r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
1207 #elif defined(HAVE_SETEUID)
1208     if ((r = setuid(pw->pw_uid)) >= 0)
1209         r = seteuid(pw->pw_uid);
1210 #elif defined(HAVE_SETREUID)
1211     r = setreuid(pw->pw_uid, pw->pw_uid);
1212 #else
1213 #error "No API to drop privileges"
1214 #endif
1215
1216     if (r < 0) {
1217         avahi_log_error("Failed to change UID: %s", strerror(errno));
1218         return -1;
1219     }
1220
1221     set_env("USER", pw->pw_name);
1222     set_env("LOGNAME", pw->pw_name);
1223     set_env("HOME", pw->pw_dir);
1224
1225     avahi_log_info("Successfully dropped root privileges.");
1226
1227     return 0;
1228 }
1229
1230 static const char* pid_file_proc(void) {
1231     return AVAHI_DAEMON_RUNTIME_DIR"/pid";
1232 }
1233
1234 static int make_runtime_dir(void) {
1235     int r = -1;
1236     mode_t u;
1237     int reset_umask = 0;
1238     struct passwd *pw;
1239     struct group * gr;
1240     struct stat st;
1241
1242     if (!(pw = getpwnam(AVAHI_USER))) {
1243         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
1244         goto fail;
1245     }
1246
1247     if (!(gr = getgrnam(AVAHI_GROUP))) {
1248         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
1249         goto fail;
1250     }
1251
1252     u = umask(0000);
1253     reset_umask = 1;
1254
1255     if (mkdir(AVAHI_DAEMON_RUNTIME_DIR, 0755) < 0 && errno != EEXIST) {
1256         avahi_log_error("mkdir(\""AVAHI_DAEMON_RUNTIME_DIR"\"): %s", strerror(errno));
1257         goto fail;
1258     }
1259
1260     chown(AVAHI_DAEMON_RUNTIME_DIR, pw->pw_uid, gr->gr_gid);
1261
1262     if (stat(AVAHI_DAEMON_RUNTIME_DIR, &st) < 0) {
1263         avahi_log_error("stat(): %s\n", strerror(errno));
1264         goto fail;
1265     }
1266
1267     if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
1268         avahi_log_error("Failed to create runtime directory "AVAHI_DAEMON_RUNTIME_DIR".");
1269         goto fail;
1270     }
1271
1272     r = 0;
1273
1274 fail:
1275     if (reset_umask)
1276         umask(u);
1277     return r;
1278 }
1279
1280 static void set_one_rlimit(int resource, rlim_t limit, const char *name) {
1281     struct rlimit rl;
1282     rl.rlim_cur = rl.rlim_max = limit;
1283
1284     if (setrlimit(resource, &rl) < 0)
1285         avahi_log_warn("setrlimit(%s, {%u, %u}) failed: %s", name, (unsigned) limit, (unsigned) limit, strerror(errno));
1286 }
1287
1288 static void enforce_rlimits(void) {
1289 #ifdef RLIMIT_AS
1290     if (config.rlimit_as_set)
1291         set_one_rlimit(RLIMIT_AS, config.rlimit_as, "RLIMIT_AS");
1292 #endif
1293     if (config.rlimit_core_set)
1294         set_one_rlimit(RLIMIT_CORE, config.rlimit_core, "RLIMIT_CORE");
1295     if (config.rlimit_data_set)
1296         set_one_rlimit(RLIMIT_DATA, config.rlimit_data, "RLIMIT_DATA");
1297     if (config.rlimit_fsize_set)
1298         set_one_rlimit(RLIMIT_FSIZE, config.rlimit_fsize, "RLIMIT_FSIZE");
1299     if (config.rlimit_nofile_set)
1300         set_one_rlimit(RLIMIT_NOFILE, config.rlimit_nofile, "RLIMIT_NOFILE");
1301     if (config.rlimit_stack_set)
1302         set_one_rlimit(RLIMIT_STACK, config.rlimit_stack, "RLIMIT_STACK");
1303 #ifdef RLIMIT_NPROC
1304     if (config.rlimit_nproc_set)
1305         set_one_rlimit(RLIMIT_NPROC, config.rlimit_nproc, "RLIMIT_NPROC");
1306 #endif
1307
1308     /* the sysctl() call from iface-pfroute.c needs locked memory on FreeBSD */
1309 #if defined(RLIMIT_MEMLOCK) && !defined(__FreeBSD__)
1310     /* We don't need locked memory */
1311     set_one_rlimit(RLIMIT_MEMLOCK, 0, "RLIMIT_MEMLOCK");
1312 #endif
1313 }
1314
1315 #define RANDOM_DEVICE "/dev/urandom"
1316
1317 static void init_rand_seed(void) {
1318     int fd;
1319     unsigned seed = 0;
1320
1321     /* Try to initialize seed from /dev/urandom, to make it a little
1322      * less predictable, and to make sure that multiple machines
1323      * booted at the same time choose different random seeds.  */
1324     if ((fd = open(RANDOM_DEVICE, O_RDONLY)) >= 0) {
1325         read(fd, &seed, sizeof(seed));
1326         close(fd);
1327     }
1328
1329     /* If the initialization failed by some reason, we add the time to the seed*/
1330     seed ^= (unsigned) time(NULL);
1331
1332     srand(seed);
1333 }
1334
1335 int main(int argc, char *argv[]) {
1336     int r = 255;
1337     int wrote_pid_file = 0;
1338
1339     avahi_set_log_function(log_function);
1340
1341     init_rand_seed();
1342
1343     avahi_server_config_init(&config.server_config);
1344     config.command = DAEMON_RUN;
1345     config.daemonize = 0;
1346     config.config_file = NULL;
1347 #ifdef HAVE_DBUS
1348     config.enable_dbus = 1;
1349     config.fail_on_missing_dbus = 1;
1350 #endif
1351
1352     config.drop_root = 1;
1353     config.set_rlimits = 1;
1354 #ifdef ENABLE_CHROOT
1355     config.use_chroot = 1;
1356 #endif
1357     config.modify_proc_title = 1;
1358
1359     config.disable_user_service_publishing = 0;
1360     config.publish_dns_servers = NULL;
1361     config.publish_resolv_conf = 0;
1362     config.use_syslog = 0;
1363     config.debug = 0;
1364     config.rlimit_as_set = 0;
1365     config.rlimit_core_set = 0;
1366     config.rlimit_data_set = 0;
1367     config.rlimit_fsize_set = 0;
1368     config.rlimit_nofile_set = 0;
1369     config.rlimit_stack_set = 0;
1370 #ifdef RLIMIT_NPROC
1371     config.rlimit_nproc_set = 0;
1372 #endif
1373
1374     if ((argv0 = strrchr(argv[0], '/')))
1375         argv0 = avahi_strdup(argv0 + 1);
1376     else
1377         argv0 = avahi_strdup(argv[0]);
1378
1379     daemon_pid_file_ident = (const char *) argv0;
1380     daemon_log_ident = (char*) argv0;
1381     daemon_pid_file_proc = pid_file_proc;
1382
1383     if (parse_command_line(&config, argc, argv) < 0)
1384         goto finish;
1385
1386     if (config.modify_proc_title)
1387         avahi_init_proc_title(argc, argv);
1388
1389 #ifdef ENABLE_CHROOT
1390     config.use_chroot = config.use_chroot && config.drop_root;
1391 #endif
1392
1393     if (config.command == DAEMON_HELP) {
1394         help(stdout);
1395         r = 0;
1396     } else if (config.command == DAEMON_VERSION) {
1397         printf("%s "PACKAGE_VERSION"\n", argv0);
1398         r = 0;
1399     } else if (config.command == DAEMON_KILL) {
1400         if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
1401             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
1402             goto finish;
1403         }
1404
1405         r = 0;
1406
1407     } else if (config.command == DAEMON_RELOAD) {
1408         if (daemon_pid_file_kill(SIGHUP) < 0) {
1409             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
1410             goto finish;
1411         }
1412
1413         r = 0;
1414
1415     } else if (config.command == DAEMON_CHECK)
1416         r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
1417     else if (config.command == DAEMON_RUN) {
1418         pid_t pid;
1419
1420         if (getuid() != 0 && config.drop_root) {
1421             avahi_log_error("This program is intended to be run as root.");
1422             goto finish;
1423         }
1424
1425         if ((pid = daemon_pid_file_is_running()) >= 0) {
1426             avahi_log_error("Daemon already running on PID %u", pid);
1427             goto finish;
1428         }
1429
1430         if (load_config_file(&config) < 0)
1431             goto finish;
1432
1433         if (config.daemonize) {
1434             daemon_retval_init();
1435
1436             if ((pid = daemon_fork()) < 0)
1437                 goto finish;
1438             else if (pid != 0) {
1439                 int ret;
1440                 /** Parent **/
1441
1442                 if ((ret = daemon_retval_wait(20)) < 0) {
1443                     avahi_log_error("Could not receive return value from daemon process.");
1444                     goto finish;
1445                 }
1446
1447                 r = ret;
1448                 goto finish;
1449             }
1450
1451             /* Child */
1452         }
1453
1454         if (config.use_syslog || config.daemonize)
1455             daemon_log_use = DAEMON_LOG_SYSLOG;
1456
1457         if (sd_listen_fds(0) <= 0)
1458             if (daemon_close_all(-1) < 0) {
1459                 avahi_log_error("Failed to close remaining file descriptors: %s", strerror(errno));
1460                 goto finish;
1461             }
1462
1463         if (make_runtime_dir() < 0)
1464             goto finish;
1465
1466         if (config.drop_root) {
1467 #ifdef ENABLE_CHROOT
1468             if (config.use_chroot)
1469                 if (avahi_caps_reduce() < 0)
1470                     goto finish;
1471 #endif
1472
1473             if (drop_root() < 0)
1474                 goto finish;
1475
1476 #ifdef ENABLE_CHROOT
1477             if (config.use_chroot)
1478                 if (avahi_caps_reduce2() < 0)
1479                     goto finish;
1480 #endif
1481         }
1482
1483         if (daemon_pid_file_create() < 0) {
1484             avahi_log_error("Failed to create PID file: %s", strerror(errno));
1485
1486             if (config.daemonize)
1487                 daemon_retval_send(1);
1488             goto finish;
1489         } else
1490             wrote_pid_file = 1;
1491
1492         if (config.set_rlimits)
1493             enforce_rlimits();
1494
1495         chdir("/");
1496
1497 #ifdef ENABLE_CHROOT
1498         if (config.drop_root && config.use_chroot)
1499             if (avahi_chroot_helper_start(argv0) < 0) {
1500                 avahi_log_error("failed to start chroot() helper daemon.");
1501                 goto finish;
1502             }
1503 #endif
1504         avahi_log_info("%s "PACKAGE_VERSION" starting up.", argv0);
1505
1506         avahi_set_proc_title(argv0, "%s: starting up", argv0);
1507
1508         if (run_server(&config) == 0)
1509             r = 0;
1510     }
1511
1512 finish:
1513
1514     if (config.daemonize)
1515         daemon_retval_done();
1516
1517     avahi_server_config_free(&config.server_config);
1518     avahi_free(config.config_file);
1519     avahi_strfreev(config.publish_dns_servers);
1520     avahi_strfreev(resolv_conf_name_servers);
1521     avahi_strfreev(resolv_conf_search_domains);
1522
1523     if (wrote_pid_file) {
1524 #ifdef ENABLE_CHROOT
1525         avahi_chroot_helper_unlink(pid_file_proc());
1526 #else
1527         daemon_pid_file_remove();
1528 #endif
1529     }
1530
1531 #ifdef ENABLE_CHROOT
1532     avahi_chroot_helper_shutdown();
1533 #endif
1534
1535     avahi_free(argv0);
1536
1537     return r;
1538 }