]> git.meshlink.io Git - catta/blob - avahi-daemon/main.c
add new configuration file option "add-service-cookie"
[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. Local service cookie is %u.", avahi_server_get_host_name_fqdn(s), avahi_server_get_local_service_cookie(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                 } else if (strcasecmp(p->key, "drop-root") == 0)
396                     c->drop_root = is_yes(p->value);
397                 else if (strcasecmp(p->key, "add-service-cookie") == 0)
398                     c->server_config.add_service_cookie = is_yes(p->value);
399                 else {
400                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
401                     goto finish;
402                 }
403             }
404             
405         } else if (strcasecmp(g->name, "publish") == 0) {
406             AvahiIniFilePair *p;
407
408             for (p = g->pairs; p; p = p->pairs_next) {
409                 
410                 if (strcasecmp(p->key, "publish-addresses") == 0)
411                     c->server_config.publish_addresses = is_yes(p->value);
412                 else if (strcasecmp(p->key, "publish-hinfo") == 0)
413                     c->server_config.publish_hinfo = is_yes(p->value);
414                 else if (strcasecmp(p->key, "publish-workstation") == 0)
415                     c->server_config.publish_workstation = is_yes(p->value);
416                 else if (strcasecmp(p->key, "publish-domain") == 0)
417                     c->server_config.publish_domain = is_yes(p->value);
418                 else if (strcasecmp(p->key, "publish-resolv-conf-dns-servers") == 0)
419                     c->publish_resolv_conf = is_yes(p->value);
420                 else if (strcasecmp(p->key, "publish-dns-servers") == 0) {
421                     avahi_strfreev(c->publish_dns_servers);
422                     c->publish_dns_servers = avahi_split_csv(p->value);
423                 } else {
424                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
425                     goto finish;
426                 }
427             }
428
429         } else if (strcasecmp(g->name, "reflector") == 0) {
430             AvahiIniFilePair *p;
431
432             for (p = g->pairs; p; p = p->pairs_next) {
433                 
434                 if (strcasecmp(p->key, "enable-reflector") == 0)
435                     c->server_config.enable_reflector = is_yes(p->value);
436                 else if (strcasecmp(p->key, "reflect-ipv") == 0)
437                     c->server_config.reflect_ipv = is_yes(p->value);
438                 else {
439                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
440                     goto finish;
441                 }
442             }
443             
444         } else if (strcasecmp(g->name, "rlimits") == 0) {
445             AvahiIniFilePair *p;
446
447             for (p = g->pairs; p; p = p->pairs_next) {
448                 
449                 if (strcasecmp(p->key, "rlimit-as") == 0) {
450                     c->rlimit_as_set = 1;
451                     c->rlimit_as = atoi(p->value);
452                 } else if (strcasecmp(p->key, "rlimit-core") == 0) {
453                     c->rlimit_core_set = 1;
454                     c->rlimit_core = atoi(p->value);
455                 } else if (strcasecmp(p->key, "rlimit-data") == 0) {
456                     c->rlimit_data_set = 1;
457                     c->rlimit_data = atoi(p->value);
458                 } else if (strcasecmp(p->key, "rlimit-fsize") == 0) {
459                     c->rlimit_fsize_set = 1;
460                     c->rlimit_fsize = atoi(p->value);
461                 } else if (strcasecmp(p->key, "rlimit-nofile") == 0) {
462                     c->rlimit_nofile_set = 1;
463                     c->rlimit_nofile = atoi(p->value);
464                 } else if (strcasecmp(p->key, "rlimit-stack") == 0) {
465                     c->rlimit_stack_set = 1;
466                     c->rlimit_stack = atoi(p->value);
467 #ifdef RLIMIT_NPROC
468                 } else if (strcasecmp(p->key, "rlimit-nproc") == 0) {
469                     c->rlimit_nproc_set = 1;
470                     c->rlimit_nproc = atoi(p->value);
471 #endif
472                 } else {
473                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
474                     goto finish;
475                 }
476
477             }
478             
479         } else {
480             avahi_log_error("Invalid configuration file group \"%s\".\n", g->name);
481             goto finish;
482         }
483     }
484
485     r = 0;
486
487 finish:
488
489     if (f)
490         avahi_ini_file_free(f);
491     
492     return r;
493 }
494
495 static void log_function(AvahiLogLevel level, const char *txt) {
496
497     static const int log_level_map[] = {
498         LOG_ERR,
499         LOG_WARNING,
500         LOG_NOTICE,
501         LOG_INFO,
502         LOG_DEBUG
503     };
504     
505     assert(level < AVAHI_LOG_LEVEL_MAX);
506     assert(txt);
507
508     if (!config.debug && level == AVAHI_LOG_DEBUG)
509         return;
510
511     daemon_log(log_level_map[level], "%s", txt);
512 }
513
514 static void dump(const char *text, void* userdata) {
515     avahi_log_info("%s", text);
516 }
517
518 static void signal_callback(AvahiWatch *watch, int fd, AvahiWatchEvent event, void *userdata) {
519     int sig;
520     AvahiSimplePoll *simple_poll_api = userdata;
521     const AvahiPoll *poll_api;
522     
523     assert(watch);
524     assert(simple_poll_api);
525
526     poll_api = avahi_simple_poll_get(simple_poll_api);
527
528     if ((sig = daemon_signal_next()) <= 0) {
529         avahi_log_error("daemon_signal_next() failed");
530         poll_api->watch_free(watch);
531         return;
532     }
533
534     switch (sig) {
535         case SIGINT:
536         case SIGQUIT:
537         case SIGTERM:
538             avahi_log_info(
539                 "Got %s, quitting.",
540                 sig == SIGINT ? "SIGINT" :
541                 (sig == SIGQUIT ? "SIGQUIT" : "SIGTERM"));
542             avahi_simple_poll_quit(simple_poll_api);
543             break;
544
545         case SIGHUP:
546             avahi_log_info("Got SIGHUP, reloading.");
547             static_service_load();
548             static_service_add_to_server();
549
550             if (resolv_conf_entry_group)
551                 avahi_s_entry_group_reset(resolv_conf_entry_group);
552
553             load_resolv_conf(&config);
554             
555             if (resolv_conf && resolv_conf[0])
556                 resolv_conf_entry_group = add_dns_servers(avahi_server, resolv_conf_entry_group, resolv_conf);
557
558             break;
559
560         case SIGUSR1:
561             avahi_log_info("Got SIGUSR1, dumping record data.");
562             avahi_server_dump(avahi_server, dump, NULL);
563             break;
564
565         default:
566             avahi_log_warn("Got spurious signal, ignoring.");
567             break;
568     }
569 }
570
571 static int run_server(DaemonConfig *c) {
572     int r = -1;
573     int error;
574     AvahiSimplePoll *simple_poll_api;
575     const AvahiPoll *poll_api;
576     AvahiWatch *sig_watch;
577
578     assert(c);
579
580     if (!(simple_poll_api = avahi_simple_poll_new())) {
581         avahi_log_error("Failed to create main loop object.");
582         goto finish;
583     }
584
585     poll_api = avahi_simple_poll_get(simple_poll_api);
586
587     if (daemon_signal_init(SIGINT, SIGQUIT, SIGHUP, SIGTERM, SIGUSR1, 0) < 0) {
588         avahi_log_error("Could not register signal handlers (%s).", strerror(errno));
589         goto finish;
590     }
591
592     if (!(sig_watch = poll_api->watch_new(poll_api, daemon_signal_fd(), AVAHI_WATCH_IN, signal_callback, simple_poll_api))) {
593         avahi_log_error( "Failed to create signal watcher");
594         goto finish;
595     }
596
597     if (simple_protocol_setup(poll_api) < 0)
598         goto finish;
599     if (c->enable_dbus) {
600 #ifdef HAVE_DBUS
601         if (dbus_protocol_setup(poll_api) < 0) {
602
603             if (c->fail_on_missing_dbus)
604                 goto finish;
605
606             avahi_log_warn("WARNING: Failed to contact D-BUS daemon, disabling D-BUS support.");
607             c->enable_dbus = 0;
608         }
609 #else
610         avahi_log_warn("WARNING: We are configured to enable D-BUS but it was not compiled in.");
611         c->enable_dbus = 0;
612 #endif
613     }
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 #else
853     config.enable_dbus = 0;
854     config.fail_on_missing_dbus = 0;
855 #endif
856     config.drop_root = 1;
857     config.publish_dns_servers = NULL;
858     config.publish_resolv_conf = 0;
859     config.use_syslog = 0;
860     config.no_rlimits = 0;
861     config.debug = 0;
862     
863     config.rlimit_as_set = 0;
864     config.rlimit_core_set = 0;
865     config.rlimit_data_set = 0;
866     config.rlimit_fsize_set = 0;
867     config.rlimit_nofile_set = 0;
868     config.rlimit_stack_set = 0;
869 #ifdef RLIMIT_NPROC
870     config.rlimit_nproc_set = 0;
871 #endif
872     
873     if ((argv0 = strrchr(argv[0], '/')))
874         argv0++;
875     else
876         argv0 = argv[0];
877
878     daemon_pid_file_ident = (const char *) argv0;
879     daemon_log_ident = (char*) argv0;
880     daemon_pid_file_proc = pid_file_proc;
881     
882     if (parse_command_line(&config, argc, argv) < 0)
883         goto finish;
884
885     if (config.command == DAEMON_HELP) {
886         help(stdout, argv0);
887         r = 0;
888     } else if (config.command == DAEMON_VERSION) {
889         printf("%s "PACKAGE_VERSION"\n", argv0);
890         r = 0;
891     } else if (config.command == DAEMON_KILL) {
892         if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
893             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
894             goto finish;
895         }
896
897         r = 0;
898
899     } else if (config.command == DAEMON_RELOAD) {
900         if (daemon_pid_file_kill(SIGHUP) < 0) {
901             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
902             goto finish;
903         }
904
905         r = 0;
906         
907     } else if (config.command == DAEMON_CHECK)
908         r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
909     else if (config.command == DAEMON_RUN) {
910         pid_t pid;
911
912         if (getuid() != 0 && config.drop_root) {
913             avahi_log_error("This program is intended to be run as root.");
914             goto finish;
915         }
916         
917         if ((pid = daemon_pid_file_is_running()) >= 0) {
918             avahi_log_error("Daemon already running on PID %u", pid);
919             goto finish;
920         }
921
922         if (load_config_file(&config) < 0)
923             goto finish;
924         
925         if (config.daemonize) {
926             daemon_retval_init();
927             
928             if ((pid = daemon_fork()) < 0)
929                 goto finish;
930             else if (pid != 0) {
931                 int ret;
932                 /** Parent **/
933
934                 if ((ret = daemon_retval_wait(20)) < 0) {
935                     avahi_log_error("Could not recieve return value from daemon process.");
936                     goto finish;
937                 }
938
939                 r = ret;
940                 goto finish;
941             }
942
943             /* Child */
944         }
945
946         if (config.use_syslog || config.daemonize)
947             daemon_log_use = DAEMON_LOG_SYSLOG;
948
949         if (make_runtime_dir() < 0)
950             goto finish;
951
952         if (config.drop_root) {
953             if (drop_root() < 0)
954                 goto finish;
955         }
956
957         if (daemon_pid_file_create() < 0) {
958             avahi_log_error("Failed to create PID file: %s", strerror(errno));
959
960             if (config.daemonize)
961                 daemon_retval_send(1);
962             goto finish;
963         } else
964             wrote_pid_file = 1;
965
966         if (!config.no_rlimits)
967             enforce_rlimits();
968
969         chdir("/");
970         
971         avahi_log_info("%s "PACKAGE_VERSION" starting up.", argv0);
972         
973         if (run_server(&config) == 0)
974             r = 0;
975     }
976         
977 finish:
978
979     if (config.daemonize)
980         daemon_retval_done();
981
982     avahi_server_config_free(&config.server_config);
983     avahi_free(config.config_file);
984     avahi_strfreev(config.publish_dns_servers);
985     avahi_strfreev(resolv_conf);
986
987     if (wrote_pid_file)
988         daemon_pid_file_remove();
989     
990     return r;
991 }