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