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