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