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