]> git.meshlink.io Git - catta/blob - avahi-daemon/main.c
* Don't barf on enable-dbus if not compiled with dbus, but print a warning if the...
[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
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                 else if (strcasecmp(p->key, "enable-dbus") == 0) {
387
388                     if (*(p->value) == 'w' || *(p->value) == 'W') {
389                         c->fail_on_missing_dbus = 0;
390                         c->enable_dbus = 1;
391                     } else if (*(p->value) == 'y' || *(p->value) == 'Y') {
392                         c->fail_on_missing_dbus = 1;
393                         c->enable_dbus = 1;
394                     } else {
395                         c->enable_dbus = 0;
396                     }
397 #ifdef HAVE_DBUS                
398                     if (c->enable_dbus == 1) 
399                         avahi_log_warning("Avahi was compiled without d-bus support but you requested it was enabled in the config file");
400 #endif
401                 }
402                 else if (strcasecmp(p->key, "drop-root") == 0)
403                     c->drop_root = is_yes(p->value);
404                 else {
405                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
406                     goto finish;
407                 }
408             }
409             
410         } else if (strcasecmp(g->name, "publish") == 0) {
411             AvahiIniFilePair *p;
412
413             for (p = g->pairs; p; p = p->pairs_next) {
414                 
415                 if (strcasecmp(p->key, "publish-addresses") == 0)
416                     c->server_config.publish_addresses = is_yes(p->value);
417                 else if (strcasecmp(p->key, "publish-hinfo") == 0)
418                     c->server_config.publish_hinfo = is_yes(p->value);
419                 else if (strcasecmp(p->key, "publish-workstation") == 0)
420                     c->server_config.publish_workstation = is_yes(p->value);
421                 else if (strcasecmp(p->key, "publish-domain") == 0)
422                     c->server_config.publish_domain = is_yes(p->value);
423                 else if (strcasecmp(p->key, "publish-resolv-conf-dns-servers") == 0)
424                     c->publish_resolv_conf = is_yes(p->value);
425                 else if (strcasecmp(p->key, "publish-dns-servers") == 0) {
426                     avahi_strfreev(c->publish_dns_servers);
427                     c->publish_dns_servers = avahi_split_csv(p->value);
428                 } else {
429                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
430                     goto finish;
431                 }
432             }
433
434         } else if (strcasecmp(g->name, "reflector") == 0) {
435             AvahiIniFilePair *p;
436
437             for (p = g->pairs; p; p = p->pairs_next) {
438                 
439                 if (strcasecmp(p->key, "enable-reflector") == 0)
440                     c->server_config.enable_reflector = is_yes(p->value);
441                 else if (strcasecmp(p->key, "reflect-ipv") == 0)
442                     c->server_config.reflect_ipv = is_yes(p->value);
443                 else {
444                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
445                     goto finish;
446                 }
447             }
448             
449         } else if (strcasecmp(g->name, "rlimits") == 0) {
450             AvahiIniFilePair *p;
451
452             for (p = g->pairs; p; p = p->pairs_next) {
453                 
454                 if (strcasecmp(p->key, "rlimit-as") == 0) {
455                     c->rlimit_as_set = 1;
456                     c->rlimit_as = atoi(p->value);
457                 } else if (strcasecmp(p->key, "rlimit-core") == 0) {
458                     c->rlimit_core_set = 1;
459                     c->rlimit_core = atoi(p->value);
460                 } else if (strcasecmp(p->key, "rlimit-data") == 0) {
461                     c->rlimit_data_set = 1;
462                     c->rlimit_data = atoi(p->value);
463                 } else if (strcasecmp(p->key, "rlimit-fsize") == 0) {
464                     c->rlimit_fsize_set = 1;
465                     c->rlimit_fsize = atoi(p->value);
466                 } else if (strcasecmp(p->key, "rlimit-nofile") == 0) {
467                     c->rlimit_nofile_set = 1;
468                     c->rlimit_nofile = atoi(p->value);
469                 } else if (strcasecmp(p->key, "rlimit-stack") == 0) {
470                     c->rlimit_stack_set = 1;
471                     c->rlimit_stack = atoi(p->value);
472 #ifdef RLIMIT_NPROC
473                 } else if (strcasecmp(p->key, "rlimit-nproc") == 0) {
474                     c->rlimit_nproc_set = 1;
475                     c->rlimit_nproc = atoi(p->value);
476 #endif
477                 } else {
478                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
479                     goto finish;
480                 }
481
482             }
483             
484         } else {
485             avahi_log_error("Invalid configuration file group \"%s\".\n", g->name);
486             goto finish;
487         }
488     }
489
490     r = 0;
491
492 finish:
493
494     if (f)
495         avahi_ini_file_free(f);
496     
497     return r;
498 }
499
500 static void log_function(AvahiLogLevel level, const char *txt) {
501
502     static const int log_level_map[] = {
503         LOG_ERR,
504         LOG_WARNING,
505         LOG_NOTICE,
506         LOG_INFO,
507         LOG_DEBUG
508     };
509     
510     assert(level < AVAHI_LOG_LEVEL_MAX);
511     assert(txt);
512
513     if (!config.debug && level == AVAHI_LOG_DEBUG)
514         return;
515
516     daemon_log(log_level_map[level], "%s", txt);
517 }
518
519 static void dump(const char *text, void* userdata) {
520     avahi_log_info("%s", text);
521 }
522
523 static void signal_callback(AvahiWatch *watch, int fd, AvahiWatchEvent event, void *userdata) {
524     int sig;
525     AvahiSimplePoll *simple_poll_api = userdata;
526     const AvahiPoll *poll_api;
527     
528     assert(watch);
529     assert(simple_poll_api);
530
531     poll_api = avahi_simple_poll_get(simple_poll_api);
532
533     if ((sig = daemon_signal_next()) <= 0) {
534         avahi_log_error("daemon_signal_next() failed");
535         poll_api->watch_free(watch);
536         return;
537     }
538
539     switch (sig) {
540         case SIGINT:
541         case SIGQUIT:
542         case SIGTERM:
543             avahi_log_info(
544                 "Got %s, quitting.",
545                 sig == SIGINT ? "SIGINT" :
546                 (sig == SIGQUIT ? "SIGQUIT" : "SIGTERM"));
547             avahi_simple_poll_quit(simple_poll_api);
548             break;
549
550         case SIGHUP:
551             avahi_log_info("Got SIGHUP, reloading.");
552             static_service_load();
553             static_service_add_to_server();
554
555             if (resolv_conf_entry_group)
556                 avahi_s_entry_group_reset(resolv_conf_entry_group);
557
558             load_resolv_conf(&config);
559             
560             if (resolv_conf && resolv_conf[0])
561                 resolv_conf_entry_group = add_dns_servers(avahi_server, resolv_conf_entry_group, resolv_conf);
562
563             break;
564
565         case SIGUSR1:
566             avahi_log_info("Got SIGUSR1, dumping record data.");
567             avahi_server_dump(avahi_server, dump, NULL);
568             break;
569
570         default:
571             avahi_log_warn("Got spurious signal, ignoring.");
572             break;
573     }
574 }
575
576 static int run_server(DaemonConfig *c) {
577     int r = -1;
578     int error;
579     AvahiSimplePoll *simple_poll_api;
580     const AvahiPoll *poll_api;
581     AvahiWatch *sig_watch;
582
583     assert(c);
584
585     if (!(simple_poll_api = avahi_simple_poll_new())) {
586         avahi_log_error("Failed to create main loop object.");
587         goto finish;
588     }
589
590     poll_api = avahi_simple_poll_get(simple_poll_api);
591
592     if (daemon_signal_init(SIGINT, SIGQUIT, SIGHUP, SIGTERM, SIGUSR1, 0) < 0) {
593         avahi_log_error("Could not register signal handlers (%s).", strerror(errno));
594         goto finish;
595     }
596
597     if (!(sig_watch = poll_api->watch_new(poll_api, daemon_signal_fd(), AVAHI_WATCH_IN, signal_callback, simple_poll_api))) {
598         avahi_log_error( "Failed to create signal watcher");
599         goto finish;
600     }
601
602     if (simple_protocol_setup(poll_api) < 0)
603         goto finish;
604     
605 #ifdef HAVE_DBUS
606     if (c->enable_dbus)
607         if (dbus_protocol_setup(poll_api) < 0) {
608
609             if (c->fail_on_missing_dbus)
610                 goto finish;
611
612             avahi_log_warn("WARNING: Failed to contact D-BUS daemon, disabling D-BUS support.");
613             c->enable_dbus = 0;
614         }
615 #endif
616     
617     load_resolv_conf(c);
618     static_service_load();
619
620     if (!(avahi_server = avahi_server_new(poll_api, &c->server_config, server_callback, c, &error))) {
621         avahi_log_error("Failed to create server: %s", avahi_strerror(error));
622         goto finish;
623     }
624
625
626     if (c->daemonize)
627         daemon_retval_send(0);
628
629     for (;;) {
630         if ((r = avahi_simple_poll_iterate(simple_poll_api, -1)) < 0) {
631
632             /* We handle signals through an FD, so let's continue */
633             if (errno == EINTR)
634                 continue;
635             
636             avahi_log_error("poll(): %s", strerror(errno));
637             goto finish;
638         } else if (r > 0)
639             /* Quit */
640             break;
641     }
642     
643
644 finish:
645     
646     static_service_remove_from_server();
647     static_service_free_all();
648     remove_dns_server_entry_groups();
649     
650     simple_protocol_shutdown();
651
652 #ifdef ENABLE_DBUS
653     if (c->enable_dbus)
654         dbus_protocol_shutdown();
655 #endif
656
657     if (avahi_server)
658         avahi_server_free(avahi_server);
659
660     daemon_signal_done();
661
662     if (sig_watch)
663         poll_api->watch_free(sig_watch);
664
665     if (simple_poll_api)
666         avahi_simple_poll_free(simple_poll_api);
667
668     if (r != 0 && c->daemonize)
669         daemon_retval_send(1);
670     
671     return r;
672 }
673
674 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
675
676 static int drop_root(void) {
677     struct passwd *pw;
678     struct group * gr;
679     int r;
680     
681     if (!(pw = getpwnam(AVAHI_USER))) {
682         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
683         return -1;
684     }
685
686     if (!(gr = getgrnam(AVAHI_GROUP))) {
687         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
688         return -1;
689     }
690
691     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);
692
693     if (initgroups(AVAHI_USER, gr->gr_gid) != 0) {
694         avahi_log_error("Failed to change group list: %s", strerror(errno));
695         return -1;
696     }
697
698 #if defined(HAVE_SETRESGID)
699     r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
700 #elif defined(HAVE_SETREGID)
701     r = setregid(gr->gr_gid, gr->gr_gid);
702 #else
703     if ((r = setgid(gr->gr_gid)) >= 0)
704         r = setegid(gr->gr_gid);
705 #endif
706
707     if (r < 0) {
708         avahi_log_error("Failed to change GID: %s", strerror(errno));
709         return -1;
710     }
711
712 #if defined(HAVE_SETRESUID)
713     r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
714 #elif defined(HAVE_SETREUID)
715     r = setreuid(pw->pw_uid, pw->pw_uid);
716 #else
717     if ((r = setuid(pw->pw_uid)) >= 0)
718         r = seteuid(pw->pw_uid);
719 #endif
720
721     if (r < 0) {
722         avahi_log_error("Failed to change UID: %s", strerror(errno));
723         return -1;
724     }
725
726     set_env("USER", pw->pw_name);
727     set_env("LOGNAME", pw->pw_name);
728     set_env("HOME", pw->pw_dir);
729     
730     avahi_log_info("Successfully dropped root privileges.");
731
732     return 0;
733 }
734
735 static const char* pid_file_proc(void) {
736     return AVAHI_DAEMON_RUNTIME_DIR"/pid";
737 }
738
739 static int make_runtime_dir(void) {
740     int r = -1;
741     mode_t u;
742     int reset_umask = 0;
743     struct passwd *pw;
744     struct group * gr;
745     struct stat st;
746
747     if (!(pw = getpwnam(AVAHI_USER))) {
748         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
749         goto fail;
750     }
751
752     if (!(gr = getgrnam(AVAHI_GROUP))) {
753         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
754         goto fail;
755     }
756
757     u = umask(0000);
758     reset_umask = 1;
759     
760     if (mkdir(AVAHI_DAEMON_RUNTIME_DIR, 0755) < 0 && errno != EEXIST) {
761         avahi_log_error("mkdir(\""AVAHI_DAEMON_RUNTIME_DIR"\"): %s", strerror(errno));
762         goto fail;
763     }
764     
765     chown(AVAHI_DAEMON_RUNTIME_DIR, pw->pw_uid, gr->gr_gid);
766
767     if (stat(AVAHI_DAEMON_RUNTIME_DIR, &st) < 0) {
768         avahi_log_error("stat(): %s\n", strerror(errno));
769         goto fail;
770     }
771
772     if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
773         avahi_log_error("Failed to create runtime directory "AVAHI_DAEMON_RUNTIME_DIR".");
774         goto fail;
775     }
776
777     r = 0;
778
779 fail:
780     if (reset_umask)
781         umask(u);
782     return r;
783 }
784
785 static void set_one_rlimit(int resource, rlim_t limit, const char *name) {
786     struct rlimit rl;
787     rl.rlim_cur = rl.rlim_max = limit;
788
789     if (setrlimit(resource, &rl) < 0)
790         avahi_log_warn("setrlimit(%s, {%u, %u}) failed: %s", name, (unsigned) limit, (unsigned) limit, strerror(errno));
791 }
792
793 static void enforce_rlimits(void) {
794
795     if (config.rlimit_as_set)
796         set_one_rlimit(RLIMIT_AS, config.rlimit_as, "RLIMIT_AS");
797     if (config.rlimit_core_set)
798         set_one_rlimit(RLIMIT_CORE, config.rlimit_core, "RLIMIT_CORE");
799     if (config.rlimit_data_set)
800         set_one_rlimit(RLIMIT_DATA, config.rlimit_data, "RLIMIT_DATA");
801     if (config.rlimit_fsize_set)
802         set_one_rlimit(RLIMIT_FSIZE, config.rlimit_fsize, "RLIMIT_FSIZE");
803     if (config.rlimit_nofile_set)
804         set_one_rlimit(RLIMIT_NOFILE, config.rlimit_nofile, "RLIMIT_NOFILE");
805     if (config.rlimit_stack_set)
806         set_one_rlimit(RLIMIT_STACK, config.rlimit_stack, "RLIMIT_STACK");
807 #ifdef RLIMIT_NPROC
808     if (config.rlimit_nproc_set)
809         set_one_rlimit(RLIMIT_NPROC, config.rlimit_nproc, "RLIMIT_NPROC");
810 #endif
811
812 #ifdef RLIMIT_MEMLOCK
813     /* We don't need locked memory */
814     set_one_rlimit(RLIMIT_MEMLOCK, 0, "RLIMIT_MEMLOCK");
815 #endif
816 }
817
818 #define RANDOM_DEVICE "/dev/urandom"
819
820 static void init_rand_seed(void) {
821     int fd;
822     unsigned seed = 0;
823
824     /* Try to initialize seed from /dev/urandom, to make it a little
825      * less predictable, and to make sure that multiple machines
826      * booted at the same time choose different random seeds.  */
827     if ((fd = open(RANDOM_DEVICE, O_RDONLY)) >= 0) {
828         read(fd, &seed, sizeof(seed));
829         close(fd);
830     }
831
832     /* If the initialization failed by some reason, we add the time to the seed*/
833     seed |= (unsigned) time(NULL);
834
835     srand(seed);
836 }
837
838 int main(int argc, char *argv[]) {
839     int r = 255;
840     const char *argv0;
841     int wrote_pid_file = 0;
842
843     avahi_set_log_function(log_function);
844
845     init_rand_seed();
846     
847     avahi_server_config_init(&config.server_config);
848     config.command = DAEMON_RUN;
849     config.daemonize = 0;
850     config.config_file = NULL;
851 #ifdef HAVE_DBUS
852     config.enable_dbus = 1;
853     config.fail_on_missing_dbus = 1;
854 #endif
855     config.drop_root = 1;
856     config.publish_dns_servers = NULL;
857     config.publish_resolv_conf = 0;
858     config.use_syslog = 0;
859     config.no_rlimits = 0;
860     config.debug = 0;
861     
862     config.rlimit_as_set = 0;
863     config.rlimit_core_set = 0;
864     config.rlimit_data_set = 0;
865     config.rlimit_fsize_set = 0;
866     config.rlimit_nofile_set = 0;
867     config.rlimit_stack_set = 0;
868 #ifdef RLIMIT_NPROC
869     config.rlimit_nproc_set = 0;
870 #endif
871     
872     if ((argv0 = strrchr(argv[0], '/')))
873         argv0++;
874     else
875         argv0 = argv[0];
876
877     daemon_pid_file_ident = (const char *) argv0;
878     daemon_log_ident = (char*) argv0;
879     daemon_pid_file_proc = pid_file_proc;
880     
881     if (parse_command_line(&config, argc, argv) < 0)
882         goto finish;
883
884     if (config.command == DAEMON_HELP) {
885         help(stdout, argv0);
886         r = 0;
887     } else if (config.command == DAEMON_VERSION) {
888         printf("%s "PACKAGE_VERSION"\n", argv0);
889         r = 0;
890     } else if (config.command == DAEMON_KILL) {
891         if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
892             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
893             goto finish;
894         }
895
896         r = 0;
897
898     } else if (config.command == DAEMON_RELOAD) {
899         if (daemon_pid_file_kill(SIGHUP) < 0) {
900             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
901             goto finish;
902         }
903
904         r = 0;
905         
906     } else if (config.command == DAEMON_CHECK)
907         r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
908     else if (config.command == DAEMON_RUN) {
909         pid_t pid;
910
911         if (getuid() != 0 && config.drop_root) {
912             avahi_log_error("This program is intended to be run as root.");
913             goto finish;
914         }
915         
916         if ((pid = daemon_pid_file_is_running()) >= 0) {
917             avahi_log_error("Daemon already running on PID %u", pid);
918             goto finish;
919         }
920
921         if (load_config_file(&config) < 0)
922             goto finish;
923         
924         if (config.daemonize) {
925             daemon_retval_init();
926             
927             if ((pid = daemon_fork()) < 0)
928                 goto finish;
929             else if (pid != 0) {
930                 int ret;
931                 /** Parent **/
932
933                 if ((ret = daemon_retval_wait(20)) < 0) {
934                     avahi_log_error("Could not recieve return value from daemon process.");
935                     goto finish;
936                 }
937
938                 r = ret;
939                 goto finish;
940             }
941
942             /* Child */
943         }
944
945         if (config.use_syslog || config.daemonize)
946             daemon_log_use = DAEMON_LOG_SYSLOG;
947
948         if (make_runtime_dir() < 0)
949             goto finish;
950
951         if (config.drop_root) {
952             if (drop_root() < 0)
953                 goto finish;
954         }
955
956         if (daemon_pid_file_create() < 0) {
957             avahi_log_error("Failed to create PID file: %s", strerror(errno));
958
959             if (config.daemonize)
960                 daemon_retval_send(1);
961             goto finish;
962         } else
963             wrote_pid_file = 1;
964
965         if (!config.no_rlimits)
966             enforce_rlimits();
967
968         chdir("/");
969         
970         avahi_log_info("%s "PACKAGE_VERSION" starting up.", argv0);
971         
972         if (run_server(&config) == 0)
973             r = 0;
974     }
975         
976 finish:
977
978     if (config.daemonize)
979         daemon_retval_done();
980
981     avahi_server_config_free(&config.server_config);
982     avahi_free(config.config_file);
983     avahi_strfreev(config.publish_dns_servers);
984     avahi_strfreev(resolv_conf);
985
986     if (wrote_pid_file)
987         daemon_pid_file_remove();
988     
989     return r;
990 }