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