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