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