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