]> git.meshlink.io Git - catta/blob - avahi-daemon/main.c
1e8b2559173a8bcef3147c2864c3f32ddfb87c4d
[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 SIGQUIT:
1050         case SIGTERM:
1051             avahi_log_info(
1052                     "Got %s, quitting.",
1053                     sig == SIGINT ? "SIGINT" :
1054                     (sig == SIGQUIT ? "SIGQUIT" : "SIGTERM"));
1055             avahi_simple_poll_quit(simple_poll_api);
1056             break;
1057
1058         case SIGHUP:
1059             avahi_log_info("Got SIGHUP, reloading.");
1060
1061             reload_config();
1062             break;
1063
1064         case SIGUSR1:
1065             avahi_log_info("Got SIGUSR1, dumping record data.");
1066             avahi_server_dump(avahi_server, dump, NULL);
1067             break;
1068
1069         default:
1070             avahi_log_warn("Got spurious signal, ignoring.");
1071             break;
1072     }
1073 }
1074
1075 /* Imported from ../avahi-client/nss-check.c */
1076 int avahi_nss_support(void);
1077
1078 static void ignore_signal(int sig)  {
1079     struct sigaction sa;
1080
1081     memset(&sa, 0, sizeof(sa));
1082     sa.sa_handler = SIG_IGN;
1083     sa.sa_flags = SA_RESTART;
1084
1085     sigaction(sig, &sa, NULL);
1086 }
1087
1088 static int run_server(DaemonConfig *c) {
1089     int r = -1;
1090     int error;
1091     const AvahiPoll *poll_api = NULL;
1092     AvahiWatch *sig_watch = NULL;
1093     int retval_is_sent = 0;
1094 #ifdef HAVE_INOTIFY
1095     AvahiWatch *inotify_watch = NULL;
1096 #endif
1097 #ifdef HAVE_KQUEUE
1098     int i;
1099     AvahiWatch *kqueue_watch = NULL;
1100 #endif
1101
1102     assert(c);
1103
1104     ignore_signal(SIGPIPE);
1105
1106     if (!(nss_support = avahi_nss_support()))
1107         avahi_log_warn("WARNING: No NSS support for mDNS detected, consider installing nss-mdns!");
1108
1109     if (!(simple_poll_api = avahi_simple_poll_new())) {
1110         avahi_log_error("Failed to create main loop object.");
1111         goto finish;
1112     }
1113
1114     poll_api = avahi_simple_poll_get(simple_poll_api);
1115
1116     if (daemon_signal_init(SIGINT, SIGQUIT, SIGHUP, SIGTERM, SIGUSR1, 0) < 0) {
1117         avahi_log_error("Could not register signal handlers (%s).", strerror(errno));
1118         goto finish;
1119     }
1120
1121     if (!(sig_watch = poll_api->watch_new(poll_api, daemon_signal_fd(), AVAHI_WATCH_IN, signal_callback, simple_poll_api))) {
1122         avahi_log_error( "Failed to create signal watcher");
1123         goto finish;
1124     }
1125
1126     if (simple_protocol_setup(poll_api) < 0)
1127         goto finish;
1128
1129 #ifdef HAVE_DBUS
1130     if (c->enable_dbus) {
1131         if (dbus_protocol_setup(poll_api,
1132                                 config.disable_user_service_publishing,
1133                                 config.n_clients_max,
1134                                 config.n_objects_per_client_max,
1135                                 config.n_entries_per_entry_group_max,
1136                                 !c->fail_on_missing_dbus
1137 #ifdef ENABLE_CHROOT
1138                                 && !config.use_chroot
1139 #endif
1140             ) < 0) {
1141
1142             avahi_log_warn("WARNING: Failed to contact D-Bus daemon.");
1143
1144             if (c->fail_on_missing_dbus)
1145                 goto finish;
1146         }
1147     }
1148 #endif
1149
1150 #ifdef ENABLE_CHROOT
1151
1152     if (config.drop_root && config.use_chroot) {
1153         if (chroot(AVAHI_CONFIG_DIR) < 0) {
1154             avahi_log_error("Failed to chroot(): %s", strerror(errno));
1155             goto finish;
1156         }
1157
1158         avahi_log_info("Successfully called chroot().");
1159         chdir("/");
1160
1161         if (avahi_caps_drop_all() < 0) {
1162             avahi_log_error("Failed to drop capabilities.");
1163             goto finish;
1164         }
1165         avahi_log_info("Successfully dropped remaining capabilities.");
1166     }
1167
1168 #endif
1169
1170 #ifdef HAVE_INOTIFY
1171     if ((inotify_fd = inotify_init()) < 0)
1172         avahi_log_warn( "Failed to initialize inotify: %s", strerror(errno));
1173     else {
1174         add_inotify_watches();
1175
1176         if (!(inotify_watch = poll_api->watch_new(poll_api, inotify_fd, AVAHI_WATCH_IN, inotify_callback, NULL))) {
1177             avahi_log_error( "Failed to create inotify watcher");
1178             goto finish;
1179         }
1180     }
1181 #endif
1182
1183 #ifdef HAVE_KQUEUE
1184     if ((kq = kqueue()) < 0)
1185         avahi_log_warn( "Failed to initialize kqueue: %s", strerror(errno));
1186     else {
1187         add_kqueue_watches();
1188
1189         if (!(kqueue_watch = poll_api->watch_new(poll_api, kq, AVAHI_WATCH_IN, kqueue_callback, NULL))) {
1190             avahi_log_error( "Failed to create kqueue watcher");
1191             goto finish;
1192         }
1193     }
1194 #endif
1195
1196     load_resolv_conf();
1197 #ifdef ENABLE_CHROOT
1198     static_service_load(config.use_chroot);
1199     static_hosts_load(config.use_chroot);
1200 #else
1201     static_service_load(0);
1202     static_hosts_load(0);
1203 #endif
1204
1205     if (!(avahi_server = avahi_server_new(poll_api, &c->server_config, server_callback, c, &error))) {
1206         avahi_log_error("Failed to create server: %s", avahi_strerror(error));
1207         goto finish;
1208     }
1209
1210     update_wide_area_servers();
1211     update_browse_domains();
1212
1213     if (c->daemonize) {
1214         daemon_retval_send(0);
1215         retval_is_sent = 1;
1216     }
1217
1218     for (;;) {
1219         if ((r = avahi_simple_poll_iterate(simple_poll_api, -1)) < 0) {
1220
1221             /* We handle signals through an FD, so let's continue */
1222             if (errno == EINTR)
1223                 continue;
1224
1225             avahi_log_error("poll(): %s", strerror(errno));
1226             goto finish;
1227         } else if (r > 0)
1228             /* Quit */
1229             break;
1230     }
1231
1232     r = 0;
1233
1234 finish:
1235
1236     static_service_remove_from_server();
1237     static_service_free_all();
1238
1239     static_hosts_remove_from_server();
1240     static_hosts_free_all();
1241
1242     remove_dns_server_entry_groups();
1243
1244     simple_protocol_shutdown();
1245
1246 #ifdef HAVE_DBUS
1247     if (c->enable_dbus)
1248         dbus_protocol_shutdown();
1249 #endif
1250
1251     if (avahi_server) {
1252         avahi_server_free(avahi_server);
1253         avahi_server = NULL;
1254     }
1255
1256     daemon_signal_done();
1257
1258     if (sig_watch)
1259         poll_api->watch_free(sig_watch);
1260
1261 #ifdef HAVE_INOTIFY
1262     if (inotify_watch)
1263         poll_api->watch_free(inotify_watch);
1264     if (inotify_fd >= 0)
1265         close(inotify_fd);
1266 #endif
1267
1268 #ifdef HAVE_KQUEUE
1269     if (kqueue_watch)
1270         poll_api->watch_free(kqueue_watch);
1271     if (kq >= 0)
1272         close(kq);
1273     for (i = 0; i < num_kfds; i++) {
1274         if (kfds[i] >= 0)
1275             close(kfds[i]);
1276     }
1277 #endif
1278
1279     if (simple_poll_api) {
1280         avahi_simple_poll_free(simple_poll_api);
1281         simple_poll_api = NULL;
1282     }
1283
1284     if (!retval_is_sent && c->daemonize)
1285         daemon_retval_send(1);
1286
1287     return r;
1288 }
1289
1290 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
1291
1292 static int drop_root(void) {
1293     struct passwd *pw;
1294     struct group * gr;
1295     int r;
1296
1297     if (!(pw = getpwnam(AVAHI_USER))) {
1298         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
1299         return -1;
1300     }
1301
1302     if (!(gr = getgrnam(AVAHI_GROUP))) {
1303         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
1304         return -1;
1305     }
1306
1307     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);
1308
1309     if (initgroups(AVAHI_USER, gr->gr_gid) != 0) {
1310         avahi_log_error("Failed to change group list: %s", strerror(errno));
1311         return -1;
1312     }
1313
1314 #if defined(HAVE_SETRESGID)
1315     r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
1316 #elif defined(HAVE_SETEGID)
1317     if ((r = setgid(gr->gr_gid)) >= 0)
1318         r = setegid(gr->gr_gid);
1319 #elif defined(HAVE_SETREGID)
1320     r = setregid(gr->gr_gid, gr->gr_gid);
1321 #else
1322 #error "No API to drop privileges"
1323 #endif
1324
1325     if (r < 0) {
1326         avahi_log_error("Failed to change GID: %s", strerror(errno));
1327         return -1;
1328     }
1329
1330 #if defined(HAVE_SETRESUID)
1331     r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
1332 #elif defined(HAVE_SETEUID)
1333     if ((r = setuid(pw->pw_uid)) >= 0)
1334         r = seteuid(pw->pw_uid);
1335 #elif defined(HAVE_SETREUID)
1336     r = setreuid(pw->pw_uid, pw->pw_uid);
1337 #else
1338 #error "No API to drop privileges"
1339 #endif
1340
1341     if (r < 0) {
1342         avahi_log_error("Failed to change UID: %s", strerror(errno));
1343         return -1;
1344     }
1345
1346     set_env("USER", pw->pw_name);
1347     set_env("LOGNAME", pw->pw_name);
1348     set_env("HOME", pw->pw_dir);
1349
1350     avahi_log_info("Successfully dropped root privileges.");
1351
1352     return 0;
1353 }
1354
1355 static const char* pid_file_proc(void) {
1356     return AVAHI_DAEMON_RUNTIME_DIR"/pid";
1357 }
1358
1359 static int make_runtime_dir(void) {
1360     int r = -1;
1361     mode_t u;
1362     int reset_umask = 0;
1363     struct passwd *pw;
1364     struct group * gr;
1365     struct stat st;
1366
1367     if (!(pw = getpwnam(AVAHI_USER))) {
1368         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
1369         goto fail;
1370     }
1371
1372     if (!(gr = getgrnam(AVAHI_GROUP))) {
1373         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
1374         goto fail;
1375     }
1376
1377     u = umask(0000);
1378     reset_umask = 1;
1379
1380     if (mkdir(AVAHI_DAEMON_RUNTIME_DIR, 0755) < 0 && errno != EEXIST) {
1381         avahi_log_error("mkdir(\""AVAHI_DAEMON_RUNTIME_DIR"\"): %s", strerror(errno));
1382         goto fail;
1383     }
1384
1385     chown(AVAHI_DAEMON_RUNTIME_DIR, pw->pw_uid, gr->gr_gid);
1386
1387     if (stat(AVAHI_DAEMON_RUNTIME_DIR, &st) < 0) {
1388         avahi_log_error("stat(): %s\n", strerror(errno));
1389         goto fail;
1390     }
1391
1392     if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
1393         avahi_log_error("Failed to create runtime directory "AVAHI_DAEMON_RUNTIME_DIR".");
1394         goto fail;
1395     }
1396
1397     r = 0;
1398
1399 fail:
1400     if (reset_umask)
1401         umask(u);
1402     return r;
1403 }
1404
1405 static void set_one_rlimit(int resource, rlim_t limit, const char *name) {
1406     struct rlimit rl;
1407     rl.rlim_cur = rl.rlim_max = limit;
1408
1409     if (setrlimit(resource, &rl) < 0)
1410         avahi_log_warn("setrlimit(%s, {%u, %u}) failed: %s", name, (unsigned) limit, (unsigned) limit, strerror(errno));
1411 }
1412
1413 static void enforce_rlimits(void) {
1414 #ifdef RLIMIT_AS
1415     if (config.rlimit_as_set)
1416         set_one_rlimit(RLIMIT_AS, config.rlimit_as, "RLIMIT_AS");
1417 #endif
1418     if (config.rlimit_core_set)
1419         set_one_rlimit(RLIMIT_CORE, config.rlimit_core, "RLIMIT_CORE");
1420     if (config.rlimit_data_set)
1421         set_one_rlimit(RLIMIT_DATA, config.rlimit_data, "RLIMIT_DATA");
1422     if (config.rlimit_fsize_set)
1423         set_one_rlimit(RLIMIT_FSIZE, config.rlimit_fsize, "RLIMIT_FSIZE");
1424     if (config.rlimit_nofile_set)
1425         set_one_rlimit(RLIMIT_NOFILE, config.rlimit_nofile, "RLIMIT_NOFILE");
1426     if (config.rlimit_stack_set)
1427         set_one_rlimit(RLIMIT_STACK, config.rlimit_stack, "RLIMIT_STACK");
1428 #ifdef RLIMIT_NPROC
1429     if (config.rlimit_nproc_set)
1430         set_one_rlimit(RLIMIT_NPROC, config.rlimit_nproc, "RLIMIT_NPROC");
1431 #endif
1432
1433     /* the sysctl() call from iface-pfroute.c needs locked memory on FreeBSD */
1434 #if defined(RLIMIT_MEMLOCK) && !defined(__FreeBSD__) && !defined(__FreeBSD_kernel__)
1435     /* We don't need locked memory */
1436     set_one_rlimit(RLIMIT_MEMLOCK, 0, "RLIMIT_MEMLOCK");
1437 #endif
1438 }
1439
1440 #define RANDOM_DEVICE "/dev/urandom"
1441
1442 static void init_rand_seed(void) {
1443     int fd;
1444     unsigned seed = 0;
1445
1446     /* Try to initialize seed from /dev/urandom, to make it a little
1447      * less predictable, and to make sure that multiple machines
1448      * booted at the same time choose different random seeds.  */
1449     if ((fd = open(RANDOM_DEVICE, O_RDONLY)) >= 0) {
1450         read(fd, &seed, sizeof(seed));
1451         close(fd);
1452     }
1453
1454     /* If the initialization failed by some reason, we add the time to the seed*/
1455     seed ^= (unsigned) time(NULL);
1456
1457     srand(seed);
1458 }
1459
1460 int main(int argc, char *argv[]) {
1461     int r = 255;
1462     int wrote_pid_file = 0;
1463
1464     avahi_set_log_function(log_function);
1465
1466     init_rand_seed();
1467
1468     avahi_server_config_init(&config.server_config);
1469     config.command = DAEMON_RUN;
1470     config.daemonize = 0;
1471     config.config_file = NULL;
1472 #ifdef HAVE_DBUS
1473     config.enable_dbus = 1;
1474     config.fail_on_missing_dbus = 1;
1475     config.n_clients_max = 0;
1476     config.n_objects_per_client_max = 0;
1477     config.n_entries_per_entry_group_max = 0;
1478 #endif
1479
1480     config.drop_root = 1;
1481     config.set_rlimits = 1;
1482 #ifdef ENABLE_CHROOT
1483     config.use_chroot = 1;
1484 #endif
1485     config.modify_proc_title = 1;
1486
1487     config.disable_user_service_publishing = 0;
1488     config.publish_dns_servers = NULL;
1489     config.publish_resolv_conf = 0;
1490     config.use_syslog = 0;
1491     config.debug = 0;
1492     config.rlimit_as_set = 0;
1493     config.rlimit_core_set = 0;
1494     config.rlimit_data_set = 0;
1495     config.rlimit_fsize_set = 0;
1496     config.rlimit_nofile_set = 0;
1497     config.rlimit_stack_set = 0;
1498 #ifdef RLIMIT_NPROC
1499     config.rlimit_nproc_set = 0;
1500 #endif
1501
1502     if ((argv0 = strrchr(argv[0], '/')))
1503         argv0 = avahi_strdup(argv0 + 1);
1504     else
1505         argv0 = avahi_strdup(argv[0]);
1506
1507     daemon_pid_file_ident = (const char *) argv0;
1508     daemon_log_ident = (char*) argv0;
1509     daemon_pid_file_proc = pid_file_proc;
1510
1511     if (parse_command_line(&config, argc, argv) < 0)
1512         goto finish;
1513
1514     if (config.modify_proc_title)
1515         avahi_init_proc_title(argc, argv);
1516
1517 #ifdef ENABLE_CHROOT
1518     config.use_chroot = config.use_chroot && config.drop_root;
1519 #endif
1520
1521     if (config.command == DAEMON_HELP) {
1522         help(stdout);
1523         r = 0;
1524     } else if (config.command == DAEMON_VERSION) {
1525         printf("%s "PACKAGE_VERSION"\n", argv0);
1526         r = 0;
1527     } else if (config.command == DAEMON_KILL) {
1528         if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
1529             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
1530             goto finish;
1531         }
1532
1533         r = 0;
1534
1535     } else if (config.command == DAEMON_RELOAD) {
1536         if (daemon_pid_file_kill(SIGHUP) < 0) {
1537             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
1538             goto finish;
1539         }
1540
1541         r = 0;
1542
1543     } else if (config.command == DAEMON_CHECK)
1544         r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
1545     else if (config.command == DAEMON_RUN) {
1546         pid_t pid;
1547
1548         if (getuid() != 0 && config.drop_root) {
1549             avahi_log_error("This program is intended to be run as root.");
1550             goto finish;
1551         }
1552
1553         if ((pid = daemon_pid_file_is_running()) >= 0) {
1554             avahi_log_error("Daemon already running on PID %u", pid);
1555             goto finish;
1556         }
1557
1558         if (load_config_file(&config) < 0)
1559             goto finish;
1560
1561         if (config.daemonize) {
1562             daemon_retval_init();
1563
1564             if ((pid = daemon_fork()) < 0)
1565                 goto finish;
1566             else if (pid != 0) {
1567                 int ret;
1568                 /** Parent **/
1569
1570                 if ((ret = daemon_retval_wait(20)) < 0) {
1571                     avahi_log_error("Could not receive return value from daemon process.");
1572                     goto finish;
1573                 }
1574
1575                 r = ret;
1576                 goto finish;
1577             }
1578
1579             /* Child */
1580         }
1581
1582         if (config.use_syslog || config.daemonize)
1583             daemon_log_use = DAEMON_LOG_SYSLOG;
1584
1585         if (sd_listen_fds(0) <= 0)
1586             if (daemon_close_all(-1) < 0)
1587                 avahi_log_warn("Failed to close all remaining file descriptors: %s", strerror(errno));
1588
1589         daemon_reset_sigs(-1);
1590         daemon_unblock_sigs(-1);
1591
1592         if (make_runtime_dir() < 0)
1593             goto finish;
1594
1595         if (config.drop_root) {
1596 #ifdef ENABLE_CHROOT
1597             if (config.use_chroot)
1598                 if (avahi_caps_reduce() < 0)
1599                     goto finish;
1600 #endif
1601
1602             if (drop_root() < 0)
1603                 goto finish;
1604
1605 #ifdef ENABLE_CHROOT
1606             if (config.use_chroot)
1607                 if (avahi_caps_reduce2() < 0)
1608                     goto finish;
1609 #endif
1610         }
1611
1612         if (daemon_pid_file_create() < 0) {
1613             avahi_log_error("Failed to create PID file: %s", strerror(errno));
1614
1615             if (config.daemonize)
1616                 daemon_retval_send(1);
1617             goto finish;
1618         } else
1619             wrote_pid_file = 1;
1620
1621         if (config.set_rlimits)
1622             enforce_rlimits();
1623
1624         chdir("/");
1625
1626 #ifdef ENABLE_CHROOT
1627         if (config.drop_root && config.use_chroot)
1628             if (avahi_chroot_helper_start(argv0) < 0) {
1629                 avahi_log_error("failed to start chroot() helper daemon.");
1630                 goto finish;
1631             }
1632 #endif
1633         avahi_log_info("%s "PACKAGE_VERSION" starting up.", argv0);
1634         sd_notifyf(0, "STATUS=%s "PACKAGE_VERSION" starting up.", argv0);
1635         avahi_set_proc_title(argv0, "%s: starting up", argv0);
1636
1637         if (run_server(&config) == 0)
1638             r = 0;
1639
1640         avahi_log_info("%s "PACKAGE_VERSION" exiting.", argv0);
1641         sd_notifyf(0, "STATUS=%s "PACKAGE_VERSION" exiting.", argv0);
1642     }
1643
1644 finish:
1645
1646     if (config.daemonize)
1647         daemon_retval_done();
1648
1649     avahi_server_config_free(&config.server_config);
1650     avahi_free(config.config_file);
1651     avahi_strfreev(config.publish_dns_servers);
1652     avahi_strfreev(resolv_conf_name_servers);
1653     avahi_strfreev(resolv_conf_search_domains);
1654
1655     if (wrote_pid_file) {
1656 #ifdef ENABLE_CHROOT
1657         avahi_chroot_helper_unlink(pid_file_proc());
1658 #else
1659         daemon_pid_file_remove();
1660 #endif
1661     }
1662
1663 #ifdef ENABLE_CHROOT
1664     avahi_chroot_helper_shutdown();
1665 #endif
1666
1667     avahi_free(argv0);
1668
1669     return r;
1670 }