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