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