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