]> git.meshlink.io Git - catta/blob - avahi-daemon/main.c
fix random seed initialization
[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             avahi_set_proc_title("%s: collision", argv0);
290             
291             static_service_remove_from_server();
292             static_hosts_remove_from_server();
293             remove_dns_server_entry_groups();
294
295             n = avahi_alternative_host_name(avahi_server_get_host_name(s));
296             avahi_log_warn("Host name conflict, retrying with <%s>", n);
297             avahi_server_set_host_name(s, n);
298             avahi_free(n);
299
300             break;
301         }
302
303         case AVAHI_SERVER_FAILURE:
304
305             avahi_log_error("Server error: %s", avahi_strerror(avahi_server_errno(s)));
306             avahi_simple_poll_quit(simple_poll_api);
307             break;
308
309         case AVAHI_SERVER_REGISTERING:
310
311             avahi_set_proc_title("%s: registering [%s]", argv0, avahi_server_get_host_name_fqdn(s));
312             
313             static_service_remove_from_server();
314             static_hosts_remove_from_server();
315             remove_dns_server_entry_groups();
316             
317             break;
318
319         case AVAHI_SERVER_INVALID:
320             break;
321             
322     }
323 }
324
325 static void help(FILE *f) {
326     fprintf(f,
327             "%s [options]\n"
328             "    -h --help          Show this help\n"
329             "    -D --daemonize     Daemonize after startup (implies -s)\n"
330             "    -s --syslog        Write log messages to syslog(3) instead of STDERR\n"
331             "    -k --kill          Kill a running daemon\n"
332             "    -r --reload        Request a running daemon to reload static services\n"
333             "    -c --check         Return 0 if a daemon is already running\n"
334             "    -V --version       Show version\n"
335             "    -f --file=FILE     Load the specified configuration file instead of\n"
336             "                       "AVAHI_CONFIG_FILE"\n"
337             "       --no-rlimits    Don't enforce resource limits\n"
338             "       --no-drop-root  Don't drop privileges\n"
339 #ifdef ENABLE_CHROOT            
340             "       --no-chroot     Don't chroot()\n"
341 #endif            
342             "       --no-proc-title Don't modify process title\n"
343             "       --debug         Increase verbosity\n",
344             argv0);
345 }
346
347
348 static int parse_command_line(DaemonConfig *c, int argc, char *argv[]) {
349     int o;
350
351     enum {
352         OPTION_NO_RLIMITS = 256,
353         OPTION_NO_DROP_ROOT,
354 #ifdef ENABLE_CHROOT        
355         OPTION_NO_CHROOT,
356 #endif
357         OPTION_NO_PROC_TITLE,
358         OPTION_DEBUG
359     };
360     
361     static const struct option long_options[] = {
362         { "help",           no_argument,       NULL, 'h' },
363         { "daemonize",      no_argument,       NULL, 'D' },
364         { "kill",           no_argument,       NULL, 'k' },
365         { "version",        no_argument,       NULL, 'V' },
366         { "file",           required_argument, NULL, 'f' },
367         { "reload",         no_argument,       NULL, 'r' },
368         { "check",          no_argument,       NULL, 'c' },
369         { "syslog",         no_argument,       NULL, 's' },
370         { "no-rlimits",     no_argument,       NULL, OPTION_NO_RLIMITS },
371         { "no-drop-root",   no_argument,       NULL, OPTION_NO_DROP_ROOT },
372 #ifdef ENABLE_CHROOT
373         { "no-chroot",      no_argument,       NULL, OPTION_NO_CHROOT },
374 #endif
375         { "no-proc-title",  no_argument,       NULL, OPTION_NO_PROC_TITLE },
376         { "debug",          no_argument,       NULL, OPTION_DEBUG },
377         { NULL, 0, NULL, 0 }
378     };
379
380     assert(c);
381
382     opterr = 0;
383     while ((o = getopt_long(argc, argv, "hDkVf:rcs", long_options, NULL)) >= 0) {
384
385         switch(o) {
386             case 's':
387                 c->use_syslog = 1;
388                 break;
389             case 'h':
390                 c->command = DAEMON_HELP;
391                 break;
392             case 'D':
393                 c->daemonize = 1;
394                 break;
395             case 'k':
396                 c->command = DAEMON_KILL;
397                 break;
398             case 'V':
399                 c->command = DAEMON_VERSION;
400                 break;
401             case 'f':
402                 avahi_free(c->config_file);
403                 c->config_file = avahi_strdup(optarg);
404                 break;
405             case 'r':
406                 c->command = DAEMON_RELOAD;
407                 break;
408             case 'c':
409                 c->command = DAEMON_CHECK;
410                 break;
411             case OPTION_NO_RLIMITS:
412                 c->set_rlimits = 0;
413                 break;
414             case OPTION_NO_DROP_ROOT:
415                 c->drop_root = 0;
416                 break;
417 #ifdef ENABLE_CHROOT
418             case OPTION_NO_CHROOT:
419                 c->use_chroot = 0;
420                 break;
421 #endif
422             case OPTION_NO_PROC_TITLE:
423                 c->modify_proc_title = 0;
424                 break;
425             case OPTION_DEBUG:
426                 c->debug = 1;
427                 break;
428             default:
429                 fprintf(stderr, "Invalid command line argument: %c\n", o);
430                 return -1;
431         }
432     }
433
434     if (optind < argc) {
435         fprintf(stderr, "Too many arguments\n");
436         return -1;
437     }
438         
439     return 0;
440 }
441
442 static int is_yes(const char *s) {
443     assert(s);
444     
445     return *s == 'y' || *s == 'Y';
446 }
447
448 static int load_config_file(DaemonConfig *c) {
449     int r = -1;
450     AvahiIniFile *f;
451     AvahiIniFileGroup *g;
452
453     assert(c);
454
455     if (!(f = avahi_ini_file_load(c->config_file ? c->config_file : AVAHI_CONFIG_FILE)))
456         goto finish;
457     
458     for (g = f->groups; g; g = g->groups_next) {
459         
460         if (strcasecmp(g->name, "server") == 0) {
461             AvahiIniFilePair *p;
462
463             for (p = g->pairs; p; p = p->pairs_next) {
464
465                 if (strcasecmp(p->key, "host-name") == 0) {
466                     avahi_free(c->server_config.host_name);
467                     c->server_config.host_name = avahi_strdup(p->value);
468                 } else if (strcasecmp(p->key, "domain-name") == 0) {
469                     avahi_free(c->server_config.domain_name);
470                     c->server_config.domain_name = avahi_strdup(p->value);
471                 } else if (strcasecmp(p->key, "browse-domains") == 0) {
472                     char **e, **t;
473
474                     e = avahi_split_csv(p->value);
475                     
476                     for (t = e; *t; t++) {
477                         char cleaned[AVAHI_DOMAIN_NAME_MAX];
478
479                         if (!avahi_normalize_name(*t, cleaned, sizeof(cleaned))) {
480                             avahi_log_error("Invalid domain name \"%s\" for key \"%s\" in group \"%s\"\n", *t, p->key, g->name);
481                             avahi_strfreev(e);
482                             goto finish;
483                         }
484
485                         c->server_config.browse_domains = avahi_string_list_add(c->server_config.browse_domains, cleaned);
486                     }
487                     
488                     avahi_strfreev(e);
489                 } else if (strcasecmp(p->key, "use-ipv4") == 0)
490                     c->server_config.use_ipv4 = is_yes(p->value);
491                 else if (strcasecmp(p->key, "use-ipv6") == 0)
492                     c->server_config.use_ipv6 = is_yes(p->value);
493                 else if (strcasecmp(p->key, "check-response-ttl") == 0)
494                     c->server_config.check_response_ttl = is_yes(p->value);
495                 else if (strcasecmp(p->key, "allow-point-to-point") == 0)
496                     c->server_config.allow_point_to_point = is_yes(p->value);
497                 else if (strcasecmp(p->key, "use-iff-running") == 0)
498                     c->server_config.use_iff_running = is_yes(p->value);
499                 else if (strcasecmp(p->key, "disallow-other-stacks") == 0)
500                     c->server_config.disallow_other_stacks = is_yes(p->value);
501 #ifdef HAVE_DBUS
502                 else if (strcasecmp(p->key, "enable-dbus") == 0) {
503
504                     if (*(p->value) == 'w' || *(p->value) == 'W') {
505                         c->fail_on_missing_dbus = 0;
506                         c->enable_dbus = 1;
507                     } else if (*(p->value) == 'y' || *(p->value) == 'Y') {
508                         c->fail_on_missing_dbus = 1;
509                         c->enable_dbus = 1;
510                     } else {
511                         c->enable_dbus = 0;
512                     }
513                 }
514 #endif
515                 else {
516                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
517                     goto finish;
518                 }
519             }
520             
521         } else if (strcasecmp(g->name, "publish") == 0) {
522             AvahiIniFilePair *p;
523
524             for (p = g->pairs; p; p = p->pairs_next) {
525                 
526                 if (strcasecmp(p->key, "publish-addresses") == 0)
527                     c->server_config.publish_addresses = is_yes(p->value);
528                 else if (strcasecmp(p->key, "publish-hinfo") == 0)
529                     c->server_config.publish_hinfo = is_yes(p->value);
530                 else if (strcasecmp(p->key, "publish-workstation") == 0)
531                     c->server_config.publish_workstation = is_yes(p->value);
532                 else if (strcasecmp(p->key, "publish-domain") == 0)
533                     c->server_config.publish_domain = is_yes(p->value);
534                 else if (strcasecmp(p->key, "publish-resolv-conf-dns-servers") == 0)
535                     c->publish_resolv_conf = is_yes(p->value);
536                 else if (strcasecmp(p->key, "disable-publishing") == 0)
537                     c->server_config.disable_publishing = is_yes(p->value);
538                 else if (strcasecmp(p->key, "disable-user-service-publishing") == 0)
539                     c->disable_user_service_publishing = is_yes(p->value);
540                 else if (strcasecmp(p->key, "add-service-cookie") == 0)
541                     c->server_config.add_service_cookie = is_yes(p->value);
542                 else if (strcasecmp(p->key, "publish-dns-servers") == 0) {
543                     avahi_strfreev(c->publish_dns_servers);
544                     c->publish_dns_servers = avahi_split_csv(p->value); 
545                 } else {
546                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
547                     goto finish;
548                 }
549             }
550
551         } else if (strcasecmp(g->name, "wide-area") == 0) {
552             AvahiIniFilePair *p;
553
554             for (p = g->pairs; p; p = p->pairs_next) {
555                 
556                 if (strcasecmp(p->key, "enable-wide-area") == 0)
557                     c->server_config.enable_wide_area = is_yes(p->value);
558                 else {
559                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
560                     goto finish;
561                 }
562             }
563             
564         } else if (strcasecmp(g->name, "reflector") == 0) {
565             AvahiIniFilePair *p;
566
567             for (p = g->pairs; p; p = p->pairs_next) {
568                 
569                 if (strcasecmp(p->key, "enable-reflector") == 0)
570                     c->server_config.enable_reflector = is_yes(p->value);
571                 else if (strcasecmp(p->key, "reflect-ipv") == 0)
572                     c->server_config.reflect_ipv = is_yes(p->value);
573                 else {
574                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
575                     goto finish;
576                 }
577             }
578             
579         } else if (strcasecmp(g->name, "rlimits") == 0) {
580             AvahiIniFilePair *p;
581
582             for (p = g->pairs; p; p = p->pairs_next) {
583                 
584                 if (strcasecmp(p->key, "rlimit-as") == 0) {
585                     c->rlimit_as_set = 1;
586                     c->rlimit_as = atoi(p->value);
587                 } else if (strcasecmp(p->key, "rlimit-core") == 0) {
588                     c->rlimit_core_set = 1;
589                     c->rlimit_core = atoi(p->value);
590                 } else if (strcasecmp(p->key, "rlimit-data") == 0) {
591                     c->rlimit_data_set = 1;
592                     c->rlimit_data = atoi(p->value);
593                 } else if (strcasecmp(p->key, "rlimit-fsize") == 0) {
594                     c->rlimit_fsize_set = 1;
595                     c->rlimit_fsize = atoi(p->value);
596                 } else if (strcasecmp(p->key, "rlimit-nofile") == 0) {
597                     c->rlimit_nofile_set = 1;
598                     c->rlimit_nofile = atoi(p->value);
599                 } else if (strcasecmp(p->key, "rlimit-stack") == 0) {
600                     c->rlimit_stack_set = 1;
601                     c->rlimit_stack = atoi(p->value);
602                 } else if (strcasecmp(p->key, "rlimit-nproc") == 0) {
603 #ifdef RLIMIT_NPROC
604                     c->rlimit_nproc_set = 1;
605                     c->rlimit_nproc = atoi(p->value);
606 #else
607                     avahi_log_error("Ignoring configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
608 #endif
609                 } else {
610                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
611                     goto finish;
612                 }
613
614             }
615             
616         } else {
617             avahi_log_error("Invalid configuration file group \"%s\".\n", g->name);
618             goto finish;
619         }
620     }
621
622     r = 0;
623
624 finish:
625
626     if (f)
627         avahi_ini_file_free(f);
628     
629     return r;
630 }
631
632 static void log_function(AvahiLogLevel level, const char *txt) {
633
634     static const int log_level_map[] = {
635         LOG_ERR,
636         LOG_WARNING,
637         LOG_NOTICE,
638         LOG_INFO,
639         LOG_DEBUG
640     };
641     
642     assert(level < AVAHI_LOG_LEVEL_MAX);
643     assert(txt);
644
645     if (!config.debug && level == AVAHI_LOG_DEBUG)
646         return;
647
648     daemon_log(log_level_map[level], "%s", txt);
649 }
650
651 static void dump(const char *text, AVAHI_GCC_UNUSED void* userdata) {
652     avahi_log_info("%s", text);
653 }
654
655 static void signal_callback(AvahiWatch *watch, AVAHI_GCC_UNUSED int fd, AVAHI_GCC_UNUSED AvahiWatchEvent event, AVAHI_GCC_UNUSED void *userdata) {
656     int sig;
657     const AvahiPoll *poll_api;
658     
659     assert(watch);
660     assert(simple_poll_api);
661
662     poll_api = avahi_simple_poll_get(simple_poll_api);
663
664     if ((sig = daemon_signal_next()) <= 0) {
665         avahi_log_error("daemon_signal_next() failed");
666         poll_api->watch_free(watch);
667         return;
668     }
669
670     switch (sig) {
671         case SIGINT:
672         case SIGQUIT:
673         case SIGTERM:
674             avahi_log_info(
675                 "Got %s, quitting.",
676                 sig == SIGINT ? "SIGINT" :
677                 (sig == SIGQUIT ? "SIGQUIT" : "SIGTERM"));
678             avahi_simple_poll_quit(simple_poll_api);
679             break;
680
681         case SIGHUP:
682             avahi_log_info("Got SIGHUP, reloading.");
683 #ifdef ENABLE_CHROOT
684             static_service_load(config.use_chroot);
685             static_hosts_load(config.use_chroot);
686 #else
687             static_service_load(0);
688             static_hosts_load(0);
689 #endif            
690             static_service_add_to_server();
691             static_hosts_add_to_server();
692
693             if (resolv_conf_entry_group)
694                 avahi_s_entry_group_reset(resolv_conf_entry_group);
695
696             load_resolv_conf();
697
698             update_wide_area_servers();
699             
700             if (config.publish_resolv_conf && resolv_conf && resolv_conf[0])
701                 resolv_conf_entry_group = add_dns_servers(avahi_server, resolv_conf_entry_group, resolv_conf);
702
703             break;
704
705         case SIGUSR1:
706             avahi_log_info("Got SIGUSR1, dumping record data.");
707             avahi_server_dump(avahi_server, dump, NULL);
708             break;
709
710         default:
711             avahi_log_warn("Got spurious signal, ignoring.");
712             break;
713     }
714 }
715
716 /* Imported from ../avahi-client/nss-check.c */
717 int avahi_nss_support(void);
718
719 static int run_server(DaemonConfig *c) {
720     int r = -1;
721     int error;
722     const AvahiPoll *poll_api = NULL;
723     AvahiWatch *sig_watch = NULL;
724     int retval_is_sent = 0;
725
726     assert(c);
727
728     if (!(nss_support = avahi_nss_support()))
729         avahi_log_warn("WARNING: No NSS support for mDNS detected, consider installing nss-mdns!");
730
731     if (!(simple_poll_api = avahi_simple_poll_new())) {
732         avahi_log_error("Failed to create main loop object.");
733         goto finish;
734     }
735
736     poll_api = avahi_simple_poll_get(simple_poll_api);
737
738     if (daemon_signal_init(SIGINT, SIGQUIT, SIGHUP, SIGTERM, SIGUSR1, 0) < 0) {
739         avahi_log_error("Could not register signal handlers (%s).", strerror(errno));
740         goto finish;
741     }
742
743     if (!(sig_watch = poll_api->watch_new(poll_api, daemon_signal_fd(), AVAHI_WATCH_IN, signal_callback, simple_poll_api))) {
744         avahi_log_error( "Failed to create signal watcher");
745         goto finish;
746     }
747
748     if (simple_protocol_setup(poll_api) < 0)
749         goto finish;
750
751 #ifdef HAVE_DBUS
752     if (c->enable_dbus) {
753         if (dbus_protocol_setup(poll_api, config.disable_user_service_publishing, !c->fail_on_missing_dbus
754 #ifdef ENABLE_CHROOT
755                                 && !config.use_chroot
756 #endif
757             ) < 0) {
758
759             avahi_log_warn("WARNING: Failed to contact D-BUS daemon.");
760
761             if (c->fail_on_missing_dbus)
762                 goto finish;
763         }
764     }
765 #endif
766
767 #ifdef ENABLE_CHROOT
768
769     if (config.drop_root && config.use_chroot) {
770         if (chroot(AVAHI_CONFIG_DIR) < 0) {
771             avahi_log_error("Failed to chroot(): %s", strerror(errno));
772             goto finish;
773         }
774         
775         avahi_log_info("Successfully called chroot().");
776         chdir("/");
777         
778         if (avahi_caps_drop_all() < 0) {
779             avahi_log_error("Failed to drop capabilities.");
780             goto finish;
781         }
782         avahi_log_info("Successfully dropped remaining capabilities.");
783     }
784     
785 #endif
786
787     load_resolv_conf();
788 #ifdef ENABLE_CHROOT
789     static_service_load(config.use_chroot);
790     static_hosts_load(config.use_chroot);
791 #else
792     static_service_load(0);
793     static_hosts_load(0);
794 #endif
795
796     if (!(avahi_server = avahi_server_new(poll_api, &c->server_config, server_callback, c, &error))) {
797         avahi_log_error("Failed to create server: %s", avahi_strerror(error));
798         goto finish;
799     }
800
801     update_wide_area_servers();
802
803     if (c->daemonize) {
804         daemon_retval_send(0);
805         retval_is_sent = 1;
806     }
807
808     for (;;) {
809         if ((r = avahi_simple_poll_iterate(simple_poll_api, -1)) < 0) {
810
811             /* We handle signals through an FD, so let's continue */
812             if (errno == EINTR)
813                 continue;
814             
815             avahi_log_error("poll(): %s", strerror(errno));
816             goto finish;
817         } else if (r > 0)
818             /* Quit */
819             break;
820     }
821     
822
823 finish:
824     
825     static_service_remove_from_server();
826     static_service_free_all();
827
828     static_hosts_remove_from_server();
829     static_hosts_free_all();
830
831     remove_dns_server_entry_groups();
832     
833     simple_protocol_shutdown();
834
835 #ifdef HAVE_DBUS
836     if (c->enable_dbus)
837         dbus_protocol_shutdown();
838 #endif
839
840     if (avahi_server) {
841         avahi_server_free(avahi_server);
842         avahi_server = NULL;
843     }
844
845     daemon_signal_done();
846
847     if (sig_watch)
848         poll_api->watch_free(sig_watch);
849
850     if (simple_poll_api) {
851         avahi_simple_poll_free(simple_poll_api);
852         simple_poll_api = NULL;
853     }
854
855     if (!retval_is_sent && c->daemonize)
856         daemon_retval_send(1);
857     
858     return r;
859 }
860
861 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
862
863 static int drop_root(void) {
864     struct passwd *pw;
865     struct group * gr;
866     int r;
867     
868     if (!(pw = getpwnam(AVAHI_USER))) {
869         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
870         return -1;
871     }
872
873     if (!(gr = getgrnam(AVAHI_GROUP))) {
874         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
875         return -1;
876     }
877
878     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);
879
880     if (initgroups(AVAHI_USER, gr->gr_gid) != 0) {
881         avahi_log_error("Failed to change group list: %s", strerror(errno));
882         return -1;
883     }
884
885 #if defined(HAVE_SETRESGID)
886     r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
887 #elif defined(HAVE_SETEGID)
888     if ((r = setgid(gr->gr_gid)) >= 0)
889         r = setegid(gr->gr_gid);
890 #elif defined(HAVE_SETREGID)
891     r = setregid(gr->gr_gid, gr->gr_gid);
892 #else
893 #error "No API to drop priviliges"
894 #endif
895
896     if (r < 0) {
897         avahi_log_error("Failed to change GID: %s", strerror(errno));
898         return -1;
899     }
900
901 #if defined(HAVE_SETRESUID)
902     r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
903 #elif defined(HAVE_SETEUID)
904     if ((r = setuid(pw->pw_uid)) >= 0)
905         r = seteuid(pw->pw_uid);
906 #elif defined(HAVE_SETREUID)
907     r = setreuid(pw->pw_uid, pw->pw_uid);
908 #else
909 #error "No API to drop priviliges"
910 #endif
911
912     if (r < 0) {
913         avahi_log_error("Failed to change UID: %s", strerror(errno));
914         return -1;
915     }
916
917     set_env("USER", pw->pw_name);
918     set_env("LOGNAME", pw->pw_name);
919     set_env("HOME", pw->pw_dir);
920
921     avahi_log_info("Successfully dropped root privileges.");
922
923     return 0;
924 }
925
926 static const char* pid_file_proc(void) {
927     return AVAHI_DAEMON_RUNTIME_DIR"/pid";
928 }
929
930 static int make_runtime_dir(void) {
931     int r = -1;
932     mode_t u;
933     int reset_umask = 0;
934     struct passwd *pw;
935     struct group * gr;
936     struct stat st;
937
938     if (!(pw = getpwnam(AVAHI_USER))) {
939         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
940         goto fail;
941     }
942
943     if (!(gr = getgrnam(AVAHI_GROUP))) {
944         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
945         goto fail;
946     }
947
948     u = umask(0000);
949     reset_umask = 1;
950     
951     if (mkdir(AVAHI_DAEMON_RUNTIME_DIR, 0755) < 0 && errno != EEXIST) {
952         avahi_log_error("mkdir(\""AVAHI_DAEMON_RUNTIME_DIR"\"): %s", strerror(errno));
953         goto fail;
954     }
955     
956     chown(AVAHI_DAEMON_RUNTIME_DIR, pw->pw_uid, gr->gr_gid);
957
958     if (stat(AVAHI_DAEMON_RUNTIME_DIR, &st) < 0) {
959         avahi_log_error("stat(): %s\n", strerror(errno));
960         goto fail;
961     }
962
963     if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
964         avahi_log_error("Failed to create runtime directory "AVAHI_DAEMON_RUNTIME_DIR".");
965         goto fail;
966     }
967
968     r = 0;
969
970 fail:
971     if (reset_umask)
972         umask(u);
973     return r;
974 }
975
976 static void set_one_rlimit(int resource, rlim_t limit, const char *name) {
977     struct rlimit rl;
978     rl.rlim_cur = rl.rlim_max = limit;
979
980     if (setrlimit(resource, &rl) < 0)
981         avahi_log_warn("setrlimit(%s, {%u, %u}) failed: %s", name, (unsigned) limit, (unsigned) limit, strerror(errno));
982 }
983
984 static void enforce_rlimits(void) {
985 #ifdef RLIMIT_AS
986     if (config.rlimit_as_set)
987         set_one_rlimit(RLIMIT_AS, config.rlimit_as, "RLIMIT_AS");
988 #endif
989     if (config.rlimit_core_set)
990         set_one_rlimit(RLIMIT_CORE, config.rlimit_core, "RLIMIT_CORE");
991     if (config.rlimit_data_set)
992         set_one_rlimit(RLIMIT_DATA, config.rlimit_data, "RLIMIT_DATA");
993     if (config.rlimit_fsize_set)
994         set_one_rlimit(RLIMIT_FSIZE, config.rlimit_fsize, "RLIMIT_FSIZE");
995     if (config.rlimit_nofile_set)
996         set_one_rlimit(RLIMIT_NOFILE, config.rlimit_nofile, "RLIMIT_NOFILE");
997     if (config.rlimit_stack_set)
998         set_one_rlimit(RLIMIT_STACK, config.rlimit_stack, "RLIMIT_STACK");
999 #ifdef RLIMIT_NPROC
1000     if (config.rlimit_nproc_set)
1001         set_one_rlimit(RLIMIT_NPROC, config.rlimit_nproc, "RLIMIT_NPROC");
1002 #endif
1003
1004     /* the sysctl() call from iface-pfroute.c needs locked memory on FreeBSD */
1005 #if defined(RLIMIT_MEMLOCK) && !defined(__FreeBSD__)
1006     /* We don't need locked memory */
1007     set_one_rlimit(RLIMIT_MEMLOCK, 0, "RLIMIT_MEMLOCK");
1008 #endif
1009 }
1010
1011 #define RANDOM_DEVICE "/dev/urandom"
1012
1013 static void init_rand_seed(void) {
1014     int fd;
1015     unsigned seed = 0;
1016
1017     /* Try to initialize seed from /dev/urandom, to make it a little
1018      * less predictable, and to make sure that multiple machines
1019      * booted at the same time choose different random seeds.  */
1020     if ((fd = open(RANDOM_DEVICE, O_RDONLY)) >= 0) {
1021         read(fd, &seed, sizeof(seed));
1022         close(fd);
1023     }
1024
1025     /* If the initialization failed by some reason, we add the time to the seed*/
1026     seed ^= (unsigned) time(NULL);
1027
1028     srand(seed);
1029 }
1030
1031 int main(int argc, char *argv[]) {
1032     int r = 255;
1033     int wrote_pid_file = 0;
1034
1035     avahi_set_log_function(log_function);
1036
1037     init_rand_seed();
1038     
1039     avahi_server_config_init(&config.server_config);
1040     config.command = DAEMON_RUN;
1041     config.daemonize = 0;
1042     config.config_file = NULL;
1043 #ifdef HAVE_DBUS
1044     config.enable_dbus = 1;
1045     config.fail_on_missing_dbus = 1;
1046 #endif
1047     
1048     config.drop_root = 1;
1049     config.set_rlimits = 1;
1050 #ifdef ENABLE_CHROOT
1051     config.use_chroot = 1;
1052 #endif
1053     config.modify_proc_title = 1;
1054
1055     config.disable_user_service_publishing = 0;
1056     config.publish_dns_servers = NULL;
1057     config.publish_resolv_conf = 0;
1058     config.use_syslog = 0;
1059     config.debug = 0;
1060     config.rlimit_as_set = 0;
1061     config.rlimit_core_set = 0;
1062     config.rlimit_data_set = 0;
1063     config.rlimit_fsize_set = 0;
1064     config.rlimit_nofile_set = 0;
1065     config.rlimit_stack_set = 0;
1066 #ifdef RLIMIT_NPROC
1067     config.rlimit_nproc_set = 0;
1068 #endif
1069     
1070     if ((argv0 = strrchr(argv[0], '/')))
1071         argv0 = avahi_strdup(argv0 + 1);
1072     else
1073         argv0 = avahi_strdup(argv[0]);
1074
1075     daemon_pid_file_ident = (const char *) argv0;
1076     daemon_log_ident = (char*) argv0;
1077     daemon_pid_file_proc = pid_file_proc;
1078     
1079     if (parse_command_line(&config, argc, argv) < 0)
1080         goto finish;
1081
1082     if (config.modify_proc_title)
1083         avahi_init_proc_title(argc, argv);
1084
1085 #ifdef ENABLE_CHROOT
1086     config.use_chroot = config.use_chroot && config.drop_root;
1087 #endif
1088     
1089     if (config.command == DAEMON_HELP) {
1090         help(stdout);
1091         r = 0;
1092     } else if (config.command == DAEMON_VERSION) {
1093         printf("%s "PACKAGE_VERSION"\n", argv0);
1094         r = 0;
1095     } else if (config.command == DAEMON_KILL) {
1096         if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
1097             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
1098             goto finish;
1099         }
1100
1101         r = 0;
1102
1103     } else if (config.command == DAEMON_RELOAD) {
1104         if (daemon_pid_file_kill(SIGHUP) < 0) {
1105             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
1106             goto finish;
1107         }
1108
1109         r = 0;
1110         
1111     } else if (config.command == DAEMON_CHECK)
1112         r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
1113     else if (config.command == DAEMON_RUN) {
1114         pid_t pid;
1115
1116         if (getuid() != 0 && config.drop_root) {
1117             avahi_log_error("This program is intended to be run as root.");
1118             goto finish;
1119         }
1120         
1121         if ((pid = daemon_pid_file_is_running()) >= 0) {
1122             avahi_log_error("Daemon already running on PID %u", pid);
1123             goto finish;
1124         }
1125
1126         if (load_config_file(&config) < 0)
1127             goto finish;
1128         
1129         if (config.daemonize) {
1130             daemon_retval_init();
1131             
1132             if ((pid = daemon_fork()) < 0)
1133                 goto finish;
1134             else if (pid != 0) {
1135                 int ret;
1136                 /** Parent **/
1137
1138                 if ((ret = daemon_retval_wait(20)) < 0) {
1139                     avahi_log_error("Could not receive return value from daemon process.");
1140                     goto finish;
1141                 }
1142
1143                 r = ret;
1144                 goto finish;
1145             }
1146
1147             /* Child */
1148         }
1149
1150         if (config.use_syslog || config.daemonize)
1151             daemon_log_use = DAEMON_LOG_SYSLOG;
1152
1153         if (make_runtime_dir() < 0)
1154             goto finish;
1155
1156         if (config.drop_root) {
1157 #ifdef ENABLE_CHROOT
1158             if (config.use_chroot)
1159                 if (avahi_caps_reduce() < 0)
1160                     goto finish;
1161 #endif
1162             
1163             if (drop_root() < 0)
1164                 goto finish;
1165
1166 #ifdef ENABLE_CHROOT
1167             if (config.use_chroot)
1168                 if (avahi_caps_reduce2() < 0)
1169                     goto finish;
1170 #endif
1171         }
1172
1173         if (daemon_pid_file_create() < 0) {
1174             avahi_log_error("Failed to create PID file: %s", strerror(errno));
1175
1176             if (config.daemonize)
1177                 daemon_retval_send(1);
1178             goto finish;
1179         } else
1180             wrote_pid_file = 1;
1181
1182         if (config.set_rlimits)
1183             enforce_rlimits();
1184
1185         chdir("/");
1186
1187 #ifdef ENABLE_CHROOT
1188         if (config.drop_root && config.use_chroot)
1189             if (avahi_chroot_helper_start(argv0) < 0) {
1190                 avahi_log_error("failed to start chroot() helper daemon.");
1191                 goto finish;
1192             }
1193 #endif
1194         avahi_log_info("%s "PACKAGE_VERSION" starting up.", argv0);
1195
1196         avahi_set_proc_title("%s: starting up", argv0);
1197         
1198         if (run_server(&config) == 0)
1199             r = 0;
1200     }
1201         
1202 finish:
1203
1204     if (config.daemonize)
1205         daemon_retval_done();
1206
1207     avahi_server_config_free(&config.server_config);
1208     avahi_free(config.config_file);
1209     avahi_strfreev(config.publish_dns_servers);
1210     avahi_strfreev(resolv_conf);
1211
1212     if (wrote_pid_file) {
1213 #ifdef ENABLE_CHROOT
1214         avahi_chroot_helper_unlink(pid_file_proc());
1215 #else
1216         daemon_pid_file_remove();
1217 #endif
1218     }
1219
1220 #ifdef ENABLE_CHROOT
1221     avahi_chroot_helper_shutdown();
1222 #endif
1223
1224     avahi_free(argv0);
1225     
1226     return r;
1227 }