]> git.meshlink.io Git - catta/blob - avahi-daemon/main.c
reconnect if the DBUS daemon kicks avahi-daemon. Since the DBUS system bus socket...
[catta] / avahi-daemon / main.c
1 /* $Id$ */
2
3 /***
4   This file is part of avahi.
5  
6   avahi is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as
8   published by the Free Software Foundation; either version 2.1 of the
9   License, or (at your option) any later version.
10  
11   avahi is distributed in the hope that it will be useful, but WITHOUT
12   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13   or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
14   Public License for more details.
15  
16   You should have received a copy of the GNU Lesser General Public
17   License along with avahi; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <assert.h>
27 #include <getopt.h>
28 #include <string.h>
29 #include <signal.h>
30 #include <errno.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <grp.h>
34 #include <pwd.h>
35 #include <sys/stat.h>
36 #include <stdio.h>
37 #include <fcntl.h>
38 #include <time.h>
39 #include <stdlib.h>
40 #include <sys/time.h>
41 #include <sys/resource.h>
42 #include <sys/socket.h>
43
44 #include <libdaemon/dfork.h>
45 #include <libdaemon/dsignal.h>
46 #include <libdaemon/dlog.h>
47 #include <libdaemon/dpid.h>
48
49 #include <avahi-common/malloc.h>
50 #include <avahi-common/simple-watch.h>
51 #include <avahi-common/error.h>
52 #include <avahi-common/alternative.h>
53 #include <avahi-common/domain.h>
54
55 #include <avahi-core/core.h>
56 #include <avahi-core/publish.h>
57 #include <avahi-core/dns-srv-rr.h>
58 #include <avahi-core/log.h>
59
60 #ifdef ENABLE_CHROOT
61 #include "chroot.h"
62 #include "caps.h"
63 #endif
64
65 #include "setproctitle.h"
66 #include "main.h"
67 #include "simple-protocol.h"
68 #include "static-services.h"
69 #include "static-hosts.h"
70 #include "ini-file-parser.h"
71
72 #ifdef HAVE_DBUS
73 #include "dbus-protocol.h"
74 #endif
75
76 AvahiServer *avahi_server = NULL;
77 AvahiSimplePoll *simple_poll_api = NULL;
78 static char *argv0 = NULL;
79 int nss_support = 0;
80
81 typedef enum {
82     DAEMON_RUN,
83     DAEMON_KILL,
84     DAEMON_VERSION,
85     DAEMON_HELP,
86     DAEMON_RELOAD,
87     DAEMON_CHECK
88 } DaemonCommand;
89
90 typedef struct {
91     AvahiServerConfig server_config;
92     DaemonCommand command;
93     int daemonize;
94     int use_syslog;
95     char *config_file;
96 #ifdef HAVE_DBUS
97     int enable_dbus;
98     int fail_on_missing_dbus;
99 #endif
100     int drop_root;
101     int set_rlimits;
102 #ifdef ENABLE_CHROOT
103     int use_chroot;
104 #endif
105     int modify_proc_title;
106
107     int disable_user_service_publishing;
108     int publish_resolv_conf;
109     char ** publish_dns_servers;
110     int debug;
111
112     int rlimit_as_set, rlimit_core_set, rlimit_data_set, rlimit_fsize_set, rlimit_nofile_set, rlimit_stack_set;
113     rlim_t rlimit_as, rlimit_core, rlimit_data, rlimit_fsize, rlimit_nofile, rlimit_stack;
114
115 #ifdef RLIMIT_NPROC
116     int rlimit_nproc_set;
117     rlim_t rlimit_nproc;
118 #endif
119 } DaemonConfig;
120
121 #define RESOLV_CONF "/etc/resolv.conf"
122
123 static AvahiSEntryGroup *dns_servers_entry_group = NULL;
124 static AvahiSEntryGroup *resolv_conf_entry_group = NULL;
125
126 static char **resolv_conf = NULL;
127
128 static DaemonConfig config;
129
130 static int has_prefix(const char *s, const char *prefix) {
131     size_t l;
132
133     l = strlen(prefix);
134     
135     return strlen(s) >= l && strncmp(s, prefix, l) == 0;
136 }
137
138 static int load_resolv_conf(void) {
139     int ret = -1;
140     FILE *f;
141     int i = 0;
142     
143     avahi_strfreev(resolv_conf);
144     resolv_conf = NULL;
145
146 #ifdef ENABLE_CHROOT
147     f = avahi_chroot_helper_get_file(RESOLV_CONF);
148 #else
149     f = fopen(RESOLV_CONF, "r");
150 #endif
151     
152     if (!f) {
153         avahi_log_warn("Failed to open "RESOLV_CONF": %s", strerror(errno));
154         goto finish;
155     }
156
157     resolv_conf = avahi_new0(char*, AVAHI_WIDE_AREA_SERVERS_MAX+1);
158
159     while (!feof(f) && i < AVAHI_WIDE_AREA_SERVERS_MAX) {
160         char ln[128];
161         char *p;
162
163         if (!(fgets(ln, sizeof(ln), f)))
164             break;
165
166         ln[strcspn(ln, "\r\n#")] = 0;
167         p = ln + strspn(ln, "\t ");
168
169         if (has_prefix(p, "nameserver")) {
170             p += 10;
171             p += strspn(p, "\t ");
172             p[strcspn(p, "\t ")] = 0;
173             resolv_conf[i++] = avahi_strdup(p);
174         }
175     }
176
177     ret = 0;
178
179 finish:
180
181     if (ret != 0) {
182         avahi_strfreev(resolv_conf);
183         resolv_conf = NULL;
184     }
185         
186     if (f)
187         fclose(f);
188
189     return ret;
190 }
191
192 static AvahiSEntryGroup* add_dns_servers(AvahiServer *s, AvahiSEntryGroup* g, char **l) {
193     char **p;
194
195     assert(s);
196     assert(l);
197
198     if (!g) 
199         g = avahi_s_entry_group_new(s, NULL, NULL);
200
201     assert(avahi_s_entry_group_is_empty(g));
202
203     for (p = l; *p; p++) {
204         AvahiAddress a;
205         
206         if (!avahi_address_parse(*p, AVAHI_PROTO_UNSPEC, &a))
207             avahi_log_warn("Failed to parse address '%s', ignoring.", *p);
208         else
209             if (avahi_server_add_dns_server_address(s, g, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, 0, NULL, AVAHI_DNS_SERVER_RESOLVE, &a, 53) < 0) {
210                 avahi_s_entry_group_free(g);
211                 avahi_log_error("Failed to add DNS server address: %s", avahi_strerror(avahi_server_errno(s)));
212                 return NULL;
213             }
214     }
215
216     avahi_s_entry_group_commit(g);
217
218     return g;
219 }
220
221 static void remove_dns_server_entry_groups(void) {
222
223     if (resolv_conf_entry_group)
224         avahi_s_entry_group_reset(resolv_conf_entry_group);
225     
226     if (dns_servers_entry_group) 
227         avahi_s_entry_group_reset(dns_servers_entry_group);
228 }
229
230 static void update_wide_area_servers(void) {
231     AvahiAddress a[AVAHI_WIDE_AREA_SERVERS_MAX];
232     unsigned n = 0;
233     char **p;
234
235     if (!resolv_conf) {
236         avahi_server_set_wide_area_servers(avahi_server, NULL, 0);
237         return;
238     }
239
240     for (p = resolv_conf; *p && n < AVAHI_WIDE_AREA_SERVERS_MAX; p++) {
241         if (!avahi_address_parse(*p, AVAHI_PROTO_UNSPEC, &a[n]))
242             avahi_log_warn("Failed to parse address '%s', ignoring.", *p);
243         else
244             n++;
245     }
246
247     avahi_server_set_wide_area_servers(avahi_server, a, n);
248 }
249
250 static void server_callback(AvahiServer *s, AvahiServerState state, void *userdata) {
251     DaemonConfig *c = userdata;
252     
253     assert(s);
254     assert(c);
255
256     /* This function is possibly called before the global variable
257      * avahi_server has been set, therefore we do it explicitly */
258
259     avahi_server = s;
260     
261 #ifdef HAVE_DBUS
262     if (c->enable_dbus && state != AVAHI_SERVER_INVALID && state != AVAHI_SERVER_FAILURE)
263         dbus_protocol_server_state_changed(state);
264 #endif
265
266     switch (state) {
267         case AVAHI_SERVER_RUNNING:
268             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));
269             
270             avahi_set_proc_title("%s: running [%s]", argv0, avahi_server_get_host_name_fqdn(s));
271             
272             static_service_add_to_server();
273             static_hosts_add_to_server();
274             
275             remove_dns_server_entry_groups();
276             
277             if (c->publish_resolv_conf && resolv_conf && resolv_conf[0])
278                 resolv_conf_entry_group = add_dns_servers(s, resolv_conf_entry_group, resolv_conf);
279             
280             if (c->publish_dns_servers && c->publish_dns_servers[0])
281                 dns_servers_entry_group = add_dns_servers(s, dns_servers_entry_group, c->publish_dns_servers);
282             
283             simple_protocol_restart_queries();
284             break;
285             
286         case AVAHI_SERVER_COLLISION: {
287             char *n;
288             
289             static_service_remove_from_server();
290             static_hosts_remove_from_server();
291             
292             remove_dns_server_entry_groups();
293             
294             n = avahi_alternative_host_name(avahi_server_get_host_name(s));
295             avahi_log_warn("Host name conflict, retrying with <%s>", n);
296             avahi_server_set_host_name(s, n);
297             avahi_free(n);
298
299             avahi_set_proc_title("%s: collision", argv0);
300             
301             break;
302         }
303
304         case AVAHI_SERVER_FAILURE:
305
306             avahi_log_error("Server error: %s", avahi_strerror(avahi_server_errno(s)));
307             avahi_simple_poll_quit(simple_poll_api);
308             break;
309
310         case AVAHI_SERVER_REGISTERING:
311             avahi_set_proc_title("%s: registering [%s]", argv0, avahi_server_get_host_name_fqdn(s));
312
313
314         case AVAHI_SERVER_INVALID:
315             break;
316             
317     }
318 }
319
320 static void help(FILE *f) {
321     fprintf(f,
322             "%s [options]\n"
323             "    -h --help          Show this help\n"
324             "    -D --daemonize     Daemonize after startup (implies -s)\n"
325             "    -s --syslog        Write log messages to syslog(3) instead of STDERR\n"
326             "    -k --kill          Kill a running daemon\n"
327             "    -r --reload        Request a running daemon to reload static services\n"
328             "    -c --check         Return 0 if a daemon is already running\n"
329             "    -V --version       Show version\n"
330             "    -f --file=FILE     Load the specified configuration file instead of\n"
331             "                       "AVAHI_CONFIG_FILE"\n"
332             "       --no-rlimits    Don't enforce resource limits\n"
333             "       --no-drop-root  Don't drop privileges\n"
334 #ifdef ENABLE_CHROOT            
335             "       --no-chroot     Don't chroot()\n"
336 #endif            
337             "       --no-proc-title Don't modify process title\n"
338             "       --debug         Increase verbosity\n",
339             argv0);
340 }
341
342
343 static int parse_command_line(DaemonConfig *c, int argc, char *argv[]) {
344     int o;
345
346     enum {
347         OPTION_NO_RLIMITS = 256,
348         OPTION_NO_DROP_ROOT,
349 #ifdef ENABLE_CHROOT        
350         OPTION_NO_CHROOT,
351 #endif
352         OPTION_NO_PROC_TITLE,
353         OPTION_DEBUG
354     };
355     
356     static const struct option long_options[] = {
357         { "help",           no_argument,       NULL, 'h' },
358         { "daemonize",      no_argument,       NULL, 'D' },
359         { "kill",           no_argument,       NULL, 'k' },
360         { "version",        no_argument,       NULL, 'V' },
361         { "file",           required_argument, NULL, 'f' },
362         { "reload",         no_argument,       NULL, 'r' },
363         { "check",          no_argument,       NULL, 'c' },
364         { "syslog",         no_argument,       NULL, 's' },
365         { "no-rlimits",     no_argument,       NULL, OPTION_NO_RLIMITS },
366         { "no-drop-root",   no_argument,       NULL, OPTION_NO_DROP_ROOT },
367 #ifdef ENABLE_CHROOT
368         { "no-chroot",      no_argument,       NULL, OPTION_NO_CHROOT },
369 #endif
370         { "no-proc-title",  no_argument,       NULL, OPTION_NO_PROC_TITLE },
371         { "debug",          no_argument,       NULL, OPTION_DEBUG },
372         { NULL, 0, NULL, 0 }
373     };
374
375     assert(c);
376
377     opterr = 0;
378     while ((o = getopt_long(argc, argv, "hDkVf:rcs", long_options, NULL)) >= 0) {
379
380         switch(o) {
381             case 's':
382                 c->use_syslog = 1;
383                 break;
384             case 'h':
385                 c->command = DAEMON_HELP;
386                 break;
387             case 'D':
388                 c->daemonize = 1;
389                 break;
390             case 'k':
391                 c->command = DAEMON_KILL;
392                 break;
393             case 'V':
394                 c->command = DAEMON_VERSION;
395                 break;
396             case 'f':
397                 avahi_free(c->config_file);
398                 c->config_file = avahi_strdup(optarg);
399                 break;
400             case 'r':
401                 c->command = DAEMON_RELOAD;
402                 break;
403             case 'c':
404                 c->command = DAEMON_CHECK;
405                 break;
406             case OPTION_NO_RLIMITS:
407                 c->set_rlimits = 0;
408                 break;
409             case OPTION_NO_DROP_ROOT:
410                 c->drop_root = 0;
411                 break;
412 #ifdef ENABLE_CHROOT
413             case OPTION_NO_CHROOT:
414                 c->use_chroot = 0;
415                 break;
416 #endif
417             case OPTION_NO_PROC_TITLE:
418                 c->modify_proc_title = 0;
419                 break;
420             case OPTION_DEBUG:
421                 c->debug = 1;
422                 break;
423             default:
424                 fprintf(stderr, "Invalid command line argument: %c\n", o);
425                 return -1;
426         }
427     }
428
429     if (optind < argc) {
430         fprintf(stderr, "Too many arguments\n");
431         return -1;
432     }
433         
434     return 0;
435 }
436
437 static int is_yes(const char *s) {
438     assert(s);
439     
440     return *s == 'y' || *s == 'Y';
441 }
442
443 static int load_config_file(DaemonConfig *c) {
444     int r = -1;
445     AvahiIniFile *f;
446     AvahiIniFileGroup *g;
447
448     assert(c);
449
450     if (!(f = avahi_ini_file_load(c->config_file ? c->config_file : AVAHI_CONFIG_FILE)))
451         goto finish;
452     
453     for (g = f->groups; g; g = g->groups_next) {
454         
455         if (strcasecmp(g->name, "server") == 0) {
456             AvahiIniFilePair *p;
457
458             for (p = g->pairs; p; p = p->pairs_next) {
459
460                 if (strcasecmp(p->key, "host-name") == 0) {
461                     avahi_free(c->server_config.host_name);
462                     c->server_config.host_name = avahi_strdup(p->value);
463                 } else if (strcasecmp(p->key, "domain-name") == 0) {
464                     avahi_free(c->server_config.domain_name);
465                     c->server_config.domain_name = avahi_strdup(p->value);
466                 } else if (strcasecmp(p->key, "browse-domains") == 0) {
467                     char **e, **t;
468
469                     e = avahi_split_csv(p->value);
470                     
471                     for (t = e; *t; t++) {
472                         char cleaned[AVAHI_DOMAIN_NAME_MAX];
473
474                         if (!avahi_normalize_name(*t, cleaned, sizeof(cleaned))) {
475                             avahi_log_error("Invalid domain name \"%s\" for key \"%s\" in group \"%s\"\n", *t, p->key, g->name);
476                             avahi_strfreev(e);
477                             goto finish;
478                         }
479
480                         c->server_config.browse_domains = avahi_string_list_add(c->server_config.browse_domains, cleaned);
481                     }
482                     
483                     avahi_strfreev(e);
484                 } else if (strcasecmp(p->key, "use-ipv4") == 0)
485                     c->server_config.use_ipv4 = is_yes(p->value);
486                 else if (strcasecmp(p->key, "use-ipv6") == 0)
487                     c->server_config.use_ipv6 = is_yes(p->value);
488                 else if (strcasecmp(p->key, "check-response-ttl") == 0)
489                     c->server_config.check_response_ttl = is_yes(p->value);
490                 else if (strcasecmp(p->key, "allow-point-to-point") == 0)
491                     c->server_config.allow_point_to_point = is_yes(p->value);
492                 else if (strcasecmp(p->key, "use-iff-running") == 0)
493                     c->server_config.use_iff_running = is_yes(p->value);
494                 else if (strcasecmp(p->key, "disallow-other-stacks") == 0)
495                     c->server_config.disallow_other_stacks = is_yes(p->value);
496 #ifdef HAVE_DBUS
497                 else if (strcasecmp(p->key, "enable-dbus") == 0) {
498
499                     if (*(p->value) == 'w' || *(p->value) == 'W') {
500                         c->fail_on_missing_dbus = 0;
501                         c->enable_dbus = 1;
502                     } else if (*(p->value) == 'y' || *(p->value) == 'Y') {
503                         c->fail_on_missing_dbus = 1;
504                         c->enable_dbus = 1;
505                     } else {
506                         c->enable_dbus = 0;
507                     }
508                 }
509 #endif
510                 else {
511                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
512                     goto finish;
513                 }
514             }
515             
516         } else if (strcasecmp(g->name, "publish") == 0) {
517             AvahiIniFilePair *p;
518
519             for (p = g->pairs; p; p = p->pairs_next) {
520                 
521                 if (strcasecmp(p->key, "publish-addresses") == 0)
522                     c->server_config.publish_addresses = is_yes(p->value);
523                 else if (strcasecmp(p->key, "publish-hinfo") == 0)
524                     c->server_config.publish_hinfo = is_yes(p->value);
525                 else if (strcasecmp(p->key, "publish-workstation") == 0)
526                     c->server_config.publish_workstation = is_yes(p->value);
527                 else if (strcasecmp(p->key, "publish-domain") == 0)
528                     c->server_config.publish_domain = is_yes(p->value);
529                 else if (strcasecmp(p->key, "publish-resolv-conf-dns-servers") == 0)
530                     c->publish_resolv_conf = is_yes(p->value);
531                 else if (strcasecmp(p->key, "disable-publishing") == 0)
532                     c->server_config.disable_publishing = is_yes(p->value);
533                 else if (strcasecmp(p->key, "disable-user-service-publishing") == 0)
534                     c->disable_user_service_publishing = is_yes(p->value);
535                 else if (strcasecmp(p->key, "add-service-cookie") == 0)
536                     c->server_config.add_service_cookie = is_yes(p->value);
537                 else if (strcasecmp(p->key, "publish-dns-servers") == 0) {
538                     avahi_strfreev(c->publish_dns_servers);
539                     c->publish_dns_servers = avahi_split_csv(p->value); 
540                 } else {
541                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
542                     goto finish;
543                 }
544             }
545
546         } else if (strcasecmp(g->name, "wide-area") == 0) {
547             AvahiIniFilePair *p;
548
549             for (p = g->pairs; p; p = p->pairs_next) {
550                 
551                 if (strcasecmp(p->key, "enable-wide-area") == 0)
552                     c->server_config.enable_wide_area = is_yes(p->value);
553                 else {
554                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
555                     goto finish;
556                 }
557             }
558             
559         } else if (strcasecmp(g->name, "reflector") == 0) {
560             AvahiIniFilePair *p;
561
562             for (p = g->pairs; p; p = p->pairs_next) {
563                 
564                 if (strcasecmp(p->key, "enable-reflector") == 0)
565                     c->server_config.enable_reflector = is_yes(p->value);
566                 else if (strcasecmp(p->key, "reflect-ipv") == 0)
567                     c->server_config.reflect_ipv = is_yes(p->value);
568                 else {
569                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
570                     goto finish;
571                 }
572             }
573             
574         } else if (strcasecmp(g->name, "rlimits") == 0) {
575             AvahiIniFilePair *p;
576
577             for (p = g->pairs; p; p = p->pairs_next) {
578                 
579                 if (strcasecmp(p->key, "rlimit-as") == 0) {
580                     c->rlimit_as_set = 1;
581                     c->rlimit_as = atoi(p->value);
582                 } else if (strcasecmp(p->key, "rlimit-core") == 0) {
583                     c->rlimit_core_set = 1;
584                     c->rlimit_core = atoi(p->value);
585                 } else if (strcasecmp(p->key, "rlimit-data") == 0) {
586                     c->rlimit_data_set = 1;
587                     c->rlimit_data = atoi(p->value);
588                 } else if (strcasecmp(p->key, "rlimit-fsize") == 0) {
589                     c->rlimit_fsize_set = 1;
590                     c->rlimit_fsize = atoi(p->value);
591                 } else if (strcasecmp(p->key, "rlimit-nofile") == 0) {
592                     c->rlimit_nofile_set = 1;
593                     c->rlimit_nofile = atoi(p->value);
594                 } else if (strcasecmp(p->key, "rlimit-stack") == 0) {
595                     c->rlimit_stack_set = 1;
596                     c->rlimit_stack = atoi(p->value);
597 #ifdef RLIMIT_NPROC
598                 } else if (strcasecmp(p->key, "rlimit-nproc") == 0) {
599                     c->rlimit_nproc_set = 1;
600                     c->rlimit_nproc = atoi(p->value);
601 #endif
602                 } else {
603                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
604                     goto finish;
605                 }
606
607             }
608             
609         } else {
610             avahi_log_error("Invalid configuration file group \"%s\".\n", g->name);
611             goto finish;
612         }
613     }
614
615     r = 0;
616
617 finish:
618
619     if (f)
620         avahi_ini_file_free(f);
621     
622     return r;
623 }
624
625 static void log_function(AvahiLogLevel level, const char *txt) {
626
627     static const int log_level_map[] = {
628         LOG_ERR,
629         LOG_WARNING,
630         LOG_NOTICE,
631         LOG_INFO,
632         LOG_DEBUG
633     };
634     
635     assert(level < AVAHI_LOG_LEVEL_MAX);
636     assert(txt);
637
638     if (!config.debug && level == AVAHI_LOG_DEBUG)
639         return;
640
641     daemon_log(log_level_map[level], "%s", txt);
642 }
643
644 static void dump(const char *text, AVAHI_GCC_UNUSED void* userdata) {
645     avahi_log_info("%s", text);
646 }
647
648 static void signal_callback(AvahiWatch *watch, AVAHI_GCC_UNUSED int fd, AVAHI_GCC_UNUSED AvahiWatchEvent event, AVAHI_GCC_UNUSED void *userdata) {
649     int sig;
650     const AvahiPoll *poll_api;
651     
652     assert(watch);
653     assert(simple_poll_api);
654
655     poll_api = avahi_simple_poll_get(simple_poll_api);
656
657     if ((sig = daemon_signal_next()) <= 0) {
658         avahi_log_error("daemon_signal_next() failed");
659         poll_api->watch_free(watch);
660         return;
661     }
662
663     switch (sig) {
664         case SIGINT:
665         case SIGQUIT:
666         case SIGTERM:
667             avahi_log_info(
668                 "Got %s, quitting.",
669                 sig == SIGINT ? "SIGINT" :
670                 (sig == SIGQUIT ? "SIGQUIT" : "SIGTERM"));
671             avahi_simple_poll_quit(simple_poll_api);
672             break;
673
674         case SIGHUP:
675             avahi_log_info("Got SIGHUP, reloading.");
676 #ifdef ENABLE_CHROOT
677             static_service_load(config.use_chroot);
678             static_hosts_load(config.use_chroot);
679 #else
680             static_service_load(0);
681             static_hosts_load(0);
682 #endif            
683             static_service_add_to_server();
684             static_service_remove_from_server();
685
686             if (resolv_conf_entry_group)
687                 avahi_s_entry_group_reset(resolv_conf_entry_group);
688
689             load_resolv_conf();
690
691             update_wide_area_servers();
692             
693             if (config.publish_resolv_conf && resolv_conf && resolv_conf[0])
694                 resolv_conf_entry_group = add_dns_servers(avahi_server, resolv_conf_entry_group, resolv_conf);
695
696             break;
697
698         case SIGUSR1:
699             avahi_log_info("Got SIGUSR1, dumping record data.");
700             avahi_server_dump(avahi_server, dump, NULL);
701             break;
702
703         default:
704             avahi_log_warn("Got spurious signal, ignoring.");
705             break;
706     }
707 }
708
709 /* Imported from ../avahi-client/nss-check.c */
710 int avahi_nss_support(void);
711
712 static int run_server(DaemonConfig *c) {
713     int r = -1;
714     int error;
715     const AvahiPoll *poll_api = NULL;
716     AvahiWatch *sig_watch = NULL;
717     int retval_is_sent = 0;
718
719     assert(c);
720
721     if (!(nss_support = avahi_nss_support()))
722         avahi_log_warn("WARNING: No NSS support for mDNS detected, consider installing nss-mdns!");
723
724     if (!(simple_poll_api = avahi_simple_poll_new())) {
725         avahi_log_error("Failed to create main loop object.");
726         goto finish;
727     }
728
729     poll_api = avahi_simple_poll_get(simple_poll_api);
730
731     if (daemon_signal_init(SIGINT, SIGQUIT, SIGHUP, SIGTERM, SIGUSR1, 0) < 0) {
732         avahi_log_error("Could not register signal handlers (%s).", strerror(errno));
733         goto finish;
734     }
735
736     if (!(sig_watch = poll_api->watch_new(poll_api, daemon_signal_fd(), AVAHI_WATCH_IN, signal_callback, simple_poll_api))) {
737         avahi_log_error( "Failed to create signal watcher");
738         goto finish;
739     }
740
741     if (simple_protocol_setup(poll_api) < 0)
742         goto finish;
743
744 #ifdef HAVE_DBUS
745     if (c->enable_dbus) {
746         if (dbus_protocol_setup(poll_api, config.disable_user_service_publishing, !c->fail_on_missing_dbus && !config.use_chroot) < 0) {
747
748             avahi_log_warn("WARNING: Failed to contact D-BUS daemon.");
749
750             if (c->fail_on_missing_dbus)
751                 goto finish;
752         }
753     }
754 #endif
755
756 #ifdef ENABLE_CHROOT
757
758     if (config.drop_root && config.use_chroot) {
759         if (chroot(AVAHI_CONFIG_DIR) < 0) {
760             avahi_log_error("Failed to chroot(): %s", strerror(errno));
761             goto finish;
762         }
763         
764         avahi_log_info("Successfully called chroot().");
765         chdir("/");
766         
767         if (avahi_caps_drop_all() < 0) {
768             avahi_log_error("Failed to drop capabilities.");
769             goto finish;
770         }
771         avahi_log_info("Successfully dropped remaining capabilities.");
772     }
773     
774 #endif
775
776     load_resolv_conf();
777 #ifdef ENABLE_CHROOT
778     static_service_load(config.use_chroot);
779     static_hosts_load(config.use_chroot);
780 #else
781     static_service_load(0);
782     static_hosts_load(0);
783 #endif
784
785     if (!(avahi_server = avahi_server_new(poll_api, &c->server_config, server_callback, c, &error))) {
786         avahi_log_error("Failed to create server: %s", avahi_strerror(error));
787         goto finish;
788     }
789
790     update_wide_area_servers();
791
792     if (c->daemonize) {
793         daemon_retval_send(0);
794         retval_is_sent = 1;
795     }
796
797     for (;;) {
798         if ((r = avahi_simple_poll_iterate(simple_poll_api, -1)) < 0) {
799
800             /* We handle signals through an FD, so let's continue */
801             if (errno == EINTR)
802                 continue;
803             
804             avahi_log_error("poll(): %s", strerror(errno));
805             goto finish;
806         } else if (r > 0)
807             /* Quit */
808             break;
809     }
810     
811
812 finish:
813     
814     static_service_remove_from_server();
815     static_service_free_all();
816
817     static_hosts_remove_from_server();
818     static_hosts_free_all();
819
820     remove_dns_server_entry_groups();
821     
822     simple_protocol_shutdown();
823
824 #ifdef HAVE_DBUS
825     if (c->enable_dbus)
826         dbus_protocol_shutdown();
827 #endif
828
829     if (avahi_server) {
830         avahi_server_free(avahi_server);
831         avahi_server = NULL;
832     }
833
834     daemon_signal_done();
835
836     if (sig_watch)
837         poll_api->watch_free(sig_watch);
838
839     if (simple_poll_api) {
840         avahi_simple_poll_free(simple_poll_api);
841         simple_poll_api = NULL;
842     }
843
844     if (!retval_is_sent && c->daemonize)
845         daemon_retval_send(1);
846     
847     return r;
848 }
849
850 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
851
852 static int drop_root(void) {
853     struct passwd *pw;
854     struct group * gr;
855     int r;
856     
857     if (!(pw = getpwnam(AVAHI_USER))) {
858         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
859         return -1;
860     }
861
862     if (!(gr = getgrnam(AVAHI_GROUP))) {
863         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
864         return -1;
865     }
866
867     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);
868
869     if (initgroups(AVAHI_USER, gr->gr_gid) != 0) {
870         avahi_log_error("Failed to change group list: %s", strerror(errno));
871         return -1;
872     }
873
874 #if defined(HAVE_SETRESGID)
875     r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
876 #elif defined(HAVE_SETEGID)
877     if ((r = setgid(gr->gr_gid)) >= 0)
878         r = setegid(gr->gr_gid);
879 #elif defined(HAVE_SETREGID)
880     r = setregid(gr->gr_gid, gr->gr_gid);
881 #else
882 #error "No API to drop priviliges"
883 #endif
884
885     if (r < 0) {
886         avahi_log_error("Failed to change GID: %s", strerror(errno));
887         return -1;
888     }
889
890 #if defined(HAVE_SETRESUID)
891     r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
892 #elif defined(HAVE_SETEUID)
893     if ((r = setuid(pw->pw_uid)) >= 0)
894         r = seteuid(pw->pw_uid);
895 #elif defined(HAVE_SETREUID)
896     r = setreuid(pw->pw_uid, pw->pw_uid);
897 #else
898 #error "No API to drop priviliges"
899 #endif
900
901     if (r < 0) {
902         avahi_log_error("Failed to change UID: %s", strerror(errno));
903         return -1;
904     }
905
906     set_env("USER", pw->pw_name);
907     set_env("LOGNAME", pw->pw_name);
908     set_env("HOME", pw->pw_dir);
909
910     avahi_log_info("Successfully dropped root privileges.");
911
912     return 0;
913 }
914
915 static const char* pid_file_proc(void) {
916     return AVAHI_DAEMON_RUNTIME_DIR"/pid";
917 }
918
919 static int make_runtime_dir(void) {
920     int r = -1;
921     mode_t u;
922     int reset_umask = 0;
923     struct passwd *pw;
924     struct group * gr;
925     struct stat st;
926
927     if (!(pw = getpwnam(AVAHI_USER))) {
928         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
929         goto fail;
930     }
931
932     if (!(gr = getgrnam(AVAHI_GROUP))) {
933         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
934         goto fail;
935     }
936
937     u = umask(0000);
938     reset_umask = 1;
939     
940     if (mkdir(AVAHI_DAEMON_RUNTIME_DIR, 0755) < 0 && errno != EEXIST) {
941         avahi_log_error("mkdir(\""AVAHI_DAEMON_RUNTIME_DIR"\"): %s", strerror(errno));
942         goto fail;
943     }
944     
945     chown(AVAHI_DAEMON_RUNTIME_DIR, pw->pw_uid, gr->gr_gid);
946
947     if (stat(AVAHI_DAEMON_RUNTIME_DIR, &st) < 0) {
948         avahi_log_error("stat(): %s\n", strerror(errno));
949         goto fail;
950     }
951
952     if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
953         avahi_log_error("Failed to create runtime directory "AVAHI_DAEMON_RUNTIME_DIR".");
954         goto fail;
955     }
956
957     r = 0;
958
959 fail:
960     if (reset_umask)
961         umask(u);
962     return r;
963 }
964
965 static void set_one_rlimit(int resource, rlim_t limit, const char *name) {
966     struct rlimit rl;
967     rl.rlim_cur = rl.rlim_max = limit;
968
969     if (setrlimit(resource, &rl) < 0)
970         avahi_log_warn("setrlimit(%s, {%u, %u}) failed: %s", name, (unsigned) limit, (unsigned) limit, strerror(errno));
971 }
972
973 static void enforce_rlimits(void) {
974 #ifdef RLIMIT_AS
975     if (config.rlimit_as_set)
976         set_one_rlimit(RLIMIT_AS, config.rlimit_as, "RLIMIT_AS");
977 #endif
978     if (config.rlimit_core_set)
979         set_one_rlimit(RLIMIT_CORE, config.rlimit_core, "RLIMIT_CORE");
980     if (config.rlimit_data_set)
981         set_one_rlimit(RLIMIT_DATA, config.rlimit_data, "RLIMIT_DATA");
982     if (config.rlimit_fsize_set)
983         set_one_rlimit(RLIMIT_FSIZE, config.rlimit_fsize, "RLIMIT_FSIZE");
984     if (config.rlimit_nofile_set)
985         set_one_rlimit(RLIMIT_NOFILE, config.rlimit_nofile, "RLIMIT_NOFILE");
986     if (config.rlimit_stack_set)
987         set_one_rlimit(RLIMIT_STACK, config.rlimit_stack, "RLIMIT_STACK");
988 #ifdef RLIMIT_NPROC
989     if (config.rlimit_nproc_set)
990         set_one_rlimit(RLIMIT_NPROC, config.rlimit_nproc, "RLIMIT_NPROC");
991 #endif
992
993     /* the sysctl() call from iface-pfroute.c needs locked memory on FreeBSD */
994 #if defined(RLIMIT_MEMLOCK) && !defined(__FreeBSD__)
995     /* We don't need locked memory */
996     set_one_rlimit(RLIMIT_MEMLOCK, 0, "RLIMIT_MEMLOCK");
997 #endif
998 }
999
1000 #define RANDOM_DEVICE "/dev/urandom"
1001
1002 static void init_rand_seed(void) {
1003     int fd;
1004     unsigned seed = 0;
1005
1006     /* Try to initialize seed from /dev/urandom, to make it a little
1007      * less predictable, and to make sure that multiple machines
1008      * booted at the same time choose different random seeds.  */
1009     if ((fd = open(RANDOM_DEVICE, O_RDONLY)) >= 0) {
1010         read(fd, &seed, sizeof(seed));
1011         close(fd);
1012     }
1013
1014     /* If the initialization failed by some reason, we add the time to the seed*/
1015     seed |= (unsigned) time(NULL);
1016
1017     srand(seed);
1018 }
1019
1020 int main(int argc, char *argv[]) {
1021     int r = 255;
1022     int wrote_pid_file = 0;
1023
1024     avahi_set_log_function(log_function);
1025
1026     init_rand_seed();
1027     
1028     avahi_server_config_init(&config.server_config);
1029     config.command = DAEMON_RUN;
1030     config.daemonize = 0;
1031     config.config_file = NULL;
1032 #ifdef HAVE_DBUS
1033     config.enable_dbus = 1;
1034     config.fail_on_missing_dbus = 1;
1035 #endif
1036     
1037     config.drop_root = 1;
1038     config.set_rlimits = 1;
1039 #ifdef ENABLE_CHROOT
1040     config.use_chroot = 1;
1041 #endif
1042     config.modify_proc_title = 1;
1043
1044     config.disable_user_service_publishing = 0;
1045     config.publish_dns_servers = NULL;
1046     config.publish_resolv_conf = 0;
1047     config.use_syslog = 0;
1048     config.debug = 0;
1049     config.rlimit_as_set = 0;
1050     config.rlimit_core_set = 0;
1051     config.rlimit_data_set = 0;
1052     config.rlimit_fsize_set = 0;
1053     config.rlimit_nofile_set = 0;
1054     config.rlimit_stack_set = 0;
1055 #ifdef RLIMIT_NPROC
1056     config.rlimit_nproc_set = 0;
1057 #endif
1058     
1059     if ((argv0 = strrchr(argv[0], '/')))
1060         argv0 = avahi_strdup(argv0 + 1);
1061     else
1062         argv0 = avahi_strdup(argv[0]);
1063
1064     daemon_pid_file_ident = (const char *) argv0;
1065     daemon_log_ident = (char*) argv0;
1066     daemon_pid_file_proc = pid_file_proc;
1067     
1068     if (parse_command_line(&config, argc, argv) < 0)
1069         goto finish;
1070
1071     if (config.modify_proc_title)
1072         avahi_init_proc_title(argc, argv);
1073
1074 #ifdef ENABLE_CHROOT
1075     config.use_chroot = config.use_chroot && config.drop_root;
1076 #endif
1077     
1078     if (config.command == DAEMON_HELP) {
1079         help(stdout);
1080         r = 0;
1081     } else if (config.command == DAEMON_VERSION) {
1082         printf("%s "PACKAGE_VERSION"\n", argv0);
1083         r = 0;
1084     } else if (config.command == DAEMON_KILL) {
1085         if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
1086             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
1087             goto finish;
1088         }
1089
1090         r = 0;
1091
1092     } else if (config.command == DAEMON_RELOAD) {
1093         if (daemon_pid_file_kill(SIGHUP) < 0) {
1094             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
1095             goto finish;
1096         }
1097
1098         r = 0;
1099         
1100     } else if (config.command == DAEMON_CHECK)
1101         r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
1102     else if (config.command == DAEMON_RUN) {
1103         pid_t pid;
1104
1105         if (getuid() != 0 && config.drop_root) {
1106             avahi_log_error("This program is intended to be run as root.");
1107             goto finish;
1108         }
1109         
1110         if ((pid = daemon_pid_file_is_running()) >= 0) {
1111             avahi_log_error("Daemon already running on PID %u", pid);
1112             goto finish;
1113         }
1114
1115         if (load_config_file(&config) < 0)
1116             goto finish;
1117         
1118         if (config.daemonize) {
1119             daemon_retval_init();
1120             
1121             if ((pid = daemon_fork()) < 0)
1122                 goto finish;
1123             else if (pid != 0) {
1124                 int ret;
1125                 /** Parent **/
1126
1127                 if ((ret = daemon_retval_wait(20)) < 0) {
1128                     avahi_log_error("Could not receive return value from daemon process.");
1129                     goto finish;
1130                 }
1131
1132                 r = ret;
1133                 goto finish;
1134             }
1135
1136             /* Child */
1137         }
1138
1139         if (config.use_syslog || config.daemonize)
1140             daemon_log_use = DAEMON_LOG_SYSLOG;
1141
1142         if (make_runtime_dir() < 0)
1143             goto finish;
1144
1145         if (config.drop_root) {
1146 #ifdef ENABLE_CHROOT
1147             if (config.use_chroot)
1148                 if (avahi_caps_reduce() < 0)
1149                     goto finish;
1150 #endif
1151             
1152             if (drop_root() < 0)
1153                 goto finish;
1154
1155 #ifdef ENABLE_CHROOT
1156             if (config.use_chroot)
1157                 if (avahi_caps_reduce2() < 0)
1158                     goto finish;
1159 #endif
1160         }
1161
1162         if (daemon_pid_file_create() < 0) {
1163             avahi_log_error("Failed to create PID file: %s", strerror(errno));
1164
1165             if (config.daemonize)
1166                 daemon_retval_send(1);
1167             goto finish;
1168         } else
1169             wrote_pid_file = 1;
1170
1171         if (config.set_rlimits)
1172             enforce_rlimits();
1173
1174         chdir("/");
1175
1176 #ifdef ENABLE_CHROOT
1177         if (config.drop_root && config.use_chroot)
1178             if (avahi_chroot_helper_start(argv0) < 0) {
1179                 avahi_log_error("failed to start chroot() helper daemon.");
1180                 goto finish;
1181             }
1182 #endif
1183         avahi_log_info("%s "PACKAGE_VERSION" starting up.", argv0);
1184
1185         avahi_set_proc_title("%s: starting up", argv0);
1186         
1187         if (run_server(&config) == 0)
1188             r = 0;
1189     }
1190         
1191 finish:
1192
1193     if (config.daemonize)
1194         daemon_retval_done();
1195
1196     avahi_server_config_free(&config.server_config);
1197     avahi_free(config.config_file);
1198     avahi_strfreev(config.publish_dns_servers);
1199     avahi_strfreev(resolv_conf);
1200
1201     if (wrote_pid_file) {
1202 #ifdef ENABLE_CHROOT
1203         avahi_chroot_helper_unlink(pid_file_proc());
1204 #else
1205         daemon_pid_file_remove();
1206 #endif
1207     }
1208
1209 #ifdef ENABLE_CHROOT
1210     avahi_chroot_helper_shutdown();
1211 #endif
1212
1213     avahi_free(argv0);
1214     
1215     return r;
1216 }