]> git.meshlink.io Git - catta/blob - avahi-daemon/main.c
460a9d63da253e9096458d9072df8f00339aee23
[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 <sys/ioctl.h>
37 #include <stdio.h>
38 #include <fcntl.h>
39 #include <time.h>
40 #include <stdlib.h>
41 #include <sys/time.h>
42 #include <sys/resource.h>
43 #include <sys/socket.h>
44
45 #ifdef HAVE_INOTIFY
46 #ifdef HAVE_SYS_INOTIFY_H
47 #include <sys/inotify.h>
48 #else
49 #include "inotify-nosys.h"
50 #endif
51 #endif
52
53 #ifdef HAVE_KQUEUE
54 #include <sys/types.h>
55 #include <sys/event.h>
56 #include <unistd.h>
57 #endif
58
59 #include <libdaemon/dfork.h>
60 #include <libdaemon/dsignal.h>
61 #include <libdaemon/dlog.h>
62 #include <libdaemon/dpid.h>
63
64 #include <avahi-common/malloc.h>
65 #include <avahi-common/simple-watch.h>
66 #include <avahi-common/error.h>
67 #include <avahi-common/alternative.h>
68 #include <avahi-common/domain.h>
69
70 #include <avahi-core/core.h>
71 #include <avahi-core/publish.h>
72 #include <avahi-core/dns-srv-rr.h>
73 #include <avahi-core/log.h>
74
75 #ifdef ENABLE_CHROOT
76 #include "chroot.h"
77 #include "caps.h"
78 #endif
79
80 #include "setproctitle.h"
81 #include "main.h"
82 #include "simple-protocol.h"
83 #include "static-services.h"
84 #include "static-hosts.h"
85 #include "ini-file-parser.h"
86
87 #ifdef HAVE_DBUS
88 #include "dbus-protocol.h"
89 #endif
90
91 AvahiServer *avahi_server = NULL;
92 AvahiSimplePoll *simple_poll_api = NULL;
93 static char *argv0 = NULL;
94 int nss_support = 0;
95
96 typedef enum {
97     DAEMON_RUN,
98     DAEMON_KILL,
99     DAEMON_VERSION,
100     DAEMON_HELP,
101     DAEMON_RELOAD,
102     DAEMON_CHECK
103 } DaemonCommand;
104
105 typedef struct {
106     AvahiServerConfig server_config;
107     DaemonCommand command;
108     int daemonize;
109     int use_syslog;
110     char *config_file;
111 #ifdef HAVE_DBUS
112     int enable_dbus;
113     int fail_on_missing_dbus;
114 #endif
115     int drop_root;
116     int set_rlimits;
117 #ifdef ENABLE_CHROOT
118     int use_chroot;
119 #endif
120     int modify_proc_title;
121
122     int disable_user_service_publishing;
123     int publish_resolv_conf;
124     char ** publish_dns_servers;
125     int debug;
126
127     int rlimit_as_set, rlimit_core_set, rlimit_data_set, rlimit_fsize_set, rlimit_nofile_set, rlimit_stack_set;
128     rlim_t rlimit_as, rlimit_core, rlimit_data, rlimit_fsize, rlimit_nofile, rlimit_stack;
129
130 #ifdef RLIMIT_NPROC
131     int rlimit_nproc_set;
132     rlim_t rlimit_nproc;
133 #endif
134 } DaemonConfig;
135
136 #define RESOLV_CONF "/etc/resolv.conf"
137
138 static AvahiSEntryGroup *dns_servers_entry_group = NULL;
139 static AvahiSEntryGroup *resolv_conf_entry_group = NULL;
140
141 static char **resolv_conf = NULL;
142
143 static DaemonConfig config;
144
145 static int has_prefix(const char *s, const char *prefix) {
146     size_t l;
147
148     l = strlen(prefix);
149     
150     return strlen(s) >= l && strncmp(s, prefix, l) == 0;
151 }
152
153 static int load_resolv_conf(void) {
154     int ret = -1;
155     FILE *f;
156     int i = 0;
157     
158     avahi_strfreev(resolv_conf);
159     resolv_conf = NULL;
160
161 #ifdef ENABLE_CHROOT
162     f = avahi_chroot_helper_get_file(RESOLV_CONF);
163 #else
164     f = fopen(RESOLV_CONF, "r");
165 #endif
166     
167     if (!f) {
168         avahi_log_warn("Failed to open "RESOLV_CONF": %s", strerror(errno));
169         goto finish;
170     }
171
172     resolv_conf = avahi_new0(char*, AVAHI_WIDE_AREA_SERVERS_MAX+1);
173
174     while (!feof(f) && i < AVAHI_WIDE_AREA_SERVERS_MAX) {
175         char ln[128];
176         char *p;
177
178         if (!(fgets(ln, sizeof(ln), f)))
179             break;
180
181         ln[strcspn(ln, "\r\n#")] = 0;
182         p = ln + strspn(ln, "\t ");
183
184         if (has_prefix(p, "nameserver")) {
185             p += 10;
186             p += strspn(p, "\t ");
187             p[strcspn(p, "\t ")] = 0;
188             resolv_conf[i++] = avahi_strdup(p);
189         }
190     }
191
192     ret = 0;
193
194 finish:
195
196     if (ret != 0) {
197         avahi_strfreev(resolv_conf);
198         resolv_conf = NULL;
199     }
200         
201     if (f)
202         fclose(f);
203
204     return ret;
205 }
206
207 static AvahiSEntryGroup* add_dns_servers(AvahiServer *s, AvahiSEntryGroup* g, char **l) {
208     char **p;
209
210     assert(s);
211     assert(l);
212
213     if (!g) 
214         g = avahi_s_entry_group_new(s, NULL, NULL);
215
216     assert(avahi_s_entry_group_is_empty(g));
217
218     for (p = l; *p; p++) {
219         AvahiAddress a;
220         
221         if (!avahi_address_parse(*p, AVAHI_PROTO_UNSPEC, &a))
222             avahi_log_warn("Failed to parse address '%s', ignoring.", *p);
223         else
224             if (avahi_server_add_dns_server_address(s, g, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, 0, NULL, AVAHI_DNS_SERVER_RESOLVE, &a, 53) < 0) {
225                 avahi_s_entry_group_free(g);
226                 avahi_log_error("Failed to add DNS server address: %s", avahi_strerror(avahi_server_errno(s)));
227                 return NULL;
228             }
229     }
230
231     avahi_s_entry_group_commit(g);
232
233     return g;
234 }
235
236 static void remove_dns_server_entry_groups(void) {
237
238     if (resolv_conf_entry_group)
239         avahi_s_entry_group_reset(resolv_conf_entry_group);
240     
241     if (dns_servers_entry_group) 
242         avahi_s_entry_group_reset(dns_servers_entry_group);
243 }
244
245 static void update_wide_area_servers(void) {
246     AvahiAddress a[AVAHI_WIDE_AREA_SERVERS_MAX];
247     unsigned n = 0;
248     char **p;
249
250     if (!resolv_conf) {
251         avahi_server_set_wide_area_servers(avahi_server, NULL, 0);
252         return;
253     }
254
255     for (p = resolv_conf; *p && n < AVAHI_WIDE_AREA_SERVERS_MAX; p++) {
256         if (!avahi_address_parse(*p, AVAHI_PROTO_UNSPEC, &a[n]))
257             avahi_log_warn("Failed to parse address '%s', ignoring.", *p);
258         else
259             n++;
260     }
261
262     avahi_server_set_wide_area_servers(avahi_server, a, n);
263 }
264
265 static void server_callback(AvahiServer *s, AvahiServerState state, void *userdata) {
266     DaemonConfig *c = userdata;
267     
268     assert(s);
269     assert(c);
270
271     /* This function is possibly called before the global variable
272      * avahi_server has been set, therefore we do it explicitly */
273
274     avahi_server = s;
275     
276 #ifdef HAVE_DBUS
277     if (c->enable_dbus && state != AVAHI_SERVER_INVALID && state != AVAHI_SERVER_FAILURE)
278         dbus_protocol_server_state_changed(state);
279 #endif
280
281     switch (state) {
282         case AVAHI_SERVER_RUNNING:
283             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));
284             
285             avahi_set_proc_title(argv0, "%s: running [%s]", argv0, avahi_server_get_host_name_fqdn(s));
286             
287             static_service_add_to_server();
288             static_hosts_add_to_server();
289             
290             remove_dns_server_entry_groups();
291             
292             if (c->publish_resolv_conf && resolv_conf && resolv_conf[0])
293                 resolv_conf_entry_group = add_dns_servers(s, resolv_conf_entry_group, resolv_conf);
294             
295             if (c->publish_dns_servers && c->publish_dns_servers[0])
296                 dns_servers_entry_group = add_dns_servers(s, dns_servers_entry_group, c->publish_dns_servers);
297             
298             simple_protocol_restart_queries();
299             break;
300             
301         case AVAHI_SERVER_COLLISION: {
302             char *n;
303             
304             avahi_set_proc_title(argv0, "%s: collision", argv0);
305             
306             static_service_remove_from_server();
307             static_hosts_remove_from_server();
308             remove_dns_server_entry_groups();
309
310             n = avahi_alternative_host_name(avahi_server_get_host_name(s));
311             avahi_log_warn("Host name conflict, retrying with <%s>", n);
312             avahi_server_set_host_name(s, n);
313             avahi_free(n);
314
315             break;
316         }
317
318         case AVAHI_SERVER_FAILURE:
319
320             avahi_log_error("Server error: %s", avahi_strerror(avahi_server_errno(s)));
321             avahi_simple_poll_quit(simple_poll_api);
322             break;
323
324         case AVAHI_SERVER_REGISTERING:
325
326             avahi_set_proc_title(argv0, "%s: registering [%s]", argv0, avahi_server_get_host_name_fqdn(s));
327             
328             static_service_remove_from_server();
329             static_hosts_remove_from_server();
330             remove_dns_server_entry_groups();
331             
332             break;
333
334         case AVAHI_SERVER_INVALID:
335             break;
336             
337     }
338 }
339
340 static void help(FILE *f) {
341     fprintf(f,
342             "%s [options]\n"
343             "    -h --help          Show this help\n"
344             "    -D --daemonize     Daemonize after startup (implies -s)\n"
345             "    -s --syslog        Write log messages to syslog(3) instead of STDERR\n"
346             "    -k --kill          Kill a running daemon\n"
347             "    -r --reload        Request a running daemon to reload static services\n"
348             "    -c --check         Return 0 if a daemon is already running\n"
349             "    -V --version       Show version\n"
350             "    -f --file=FILE     Load the specified configuration file instead of\n"
351             "                       "AVAHI_CONFIG_FILE"\n"
352             "       --no-rlimits    Don't enforce resource limits\n"
353             "       --no-drop-root  Don't drop privileges\n"
354 #ifdef ENABLE_CHROOT            
355             "       --no-chroot     Don't chroot()\n"
356 #endif            
357             "       --no-proc-title Don't modify process title\n"
358             "       --debug         Increase verbosity\n",
359             argv0);
360 }
361
362
363 static int parse_command_line(DaemonConfig *c, int argc, char *argv[]) {
364     int o;
365
366     enum {
367         OPTION_NO_RLIMITS = 256,
368         OPTION_NO_DROP_ROOT,
369 #ifdef ENABLE_CHROOT        
370         OPTION_NO_CHROOT,
371 #endif
372         OPTION_NO_PROC_TITLE,
373         OPTION_DEBUG
374     };
375     
376     static const struct option long_options[] = {
377         { "help",           no_argument,       NULL, 'h' },
378         { "daemonize",      no_argument,       NULL, 'D' },
379         { "kill",           no_argument,       NULL, 'k' },
380         { "version",        no_argument,       NULL, 'V' },
381         { "file",           required_argument, NULL, 'f' },
382         { "reload",         no_argument,       NULL, 'r' },
383         { "check",          no_argument,       NULL, 'c' },
384         { "syslog",         no_argument,       NULL, 's' },
385         { "no-rlimits",     no_argument,       NULL, OPTION_NO_RLIMITS },
386         { "no-drop-root",   no_argument,       NULL, OPTION_NO_DROP_ROOT },
387 #ifdef ENABLE_CHROOT
388         { "no-chroot",      no_argument,       NULL, OPTION_NO_CHROOT },
389 #endif
390         { "no-proc-title",  no_argument,       NULL, OPTION_NO_PROC_TITLE },
391         { "debug",          no_argument,       NULL, OPTION_DEBUG },
392         { NULL, 0, NULL, 0 }
393     };
394
395     assert(c);
396
397     while ((o = getopt_long(argc, argv, "hDkVf:rcs", long_options, NULL)) >= 0) {
398
399         switch(o) {
400             case 's':
401                 c->use_syslog = 1;
402                 break;
403             case 'h':
404                 c->command = DAEMON_HELP;
405                 break;
406             case 'D':
407                 c->daemonize = 1;
408                 break;
409             case 'k':
410                 c->command = DAEMON_KILL;
411                 break;
412             case 'V':
413                 c->command = DAEMON_VERSION;
414                 break;
415             case 'f':
416                 avahi_free(c->config_file);
417                 c->config_file = avahi_strdup(optarg);
418                 break;
419             case 'r':
420                 c->command = DAEMON_RELOAD;
421                 break;
422             case 'c':
423                 c->command = DAEMON_CHECK;
424                 break;
425             case OPTION_NO_RLIMITS:
426                 c->set_rlimits = 0;
427                 break;
428             case OPTION_NO_DROP_ROOT:
429                 c->drop_root = 0;
430                 break;
431 #ifdef ENABLE_CHROOT
432             case OPTION_NO_CHROOT:
433                 c->use_chroot = 0;
434                 break;
435 #endif
436             case OPTION_NO_PROC_TITLE:
437                 c->modify_proc_title = 0;
438                 break;
439             case OPTION_DEBUG:
440                 c->debug = 1;
441                 break;
442             default:
443                 return -1;
444         }
445     }
446
447     if (optind < argc) {
448         fprintf(stderr, "Too many arguments\n");
449         return -1;
450     }
451         
452     return 0;
453 }
454
455 static int is_yes(const char *s) {
456     assert(s);
457     
458     return *s == 'y' || *s == 'Y' || *s == '1' || *s == 't' || *s == 'T';
459 }
460
461 static int load_config_file(DaemonConfig *c) {
462     int r = -1;
463     AvahiIniFile *f;
464     AvahiIniFileGroup *g;
465
466     assert(c);
467
468     if (!(f = avahi_ini_file_load(c->config_file ? c->config_file : AVAHI_CONFIG_FILE)))
469         goto finish;
470     
471     for (g = f->groups; g; g = g->groups_next) {
472         
473         if (strcasecmp(g->name, "server") == 0) {
474             AvahiIniFilePair *p;
475
476             for (p = g->pairs; p; p = p->pairs_next) {
477
478                 if (strcasecmp(p->key, "host-name") == 0) {
479                     avahi_free(c->server_config.host_name);
480                     c->server_config.host_name = avahi_strdup(p->value);
481                 } else if (strcasecmp(p->key, "domain-name") == 0) {
482                     avahi_free(c->server_config.domain_name);
483                     c->server_config.domain_name = avahi_strdup(p->value);
484                 } else if (strcasecmp(p->key, "browse-domains") == 0) {
485                     char **e, **t;
486
487                     e = avahi_split_csv(p->value);
488                     
489                     for (t = e; *t; t++) {
490                         char cleaned[AVAHI_DOMAIN_NAME_MAX];
491
492                         if (!avahi_normalize_name(*t, cleaned, sizeof(cleaned))) {
493                             avahi_log_error("Invalid domain name \"%s\" for key \"%s\" in group \"%s\"\n", *t, p->key, g->name);
494                             avahi_strfreev(e);
495                             goto finish;
496                         }
497
498                         c->server_config.browse_domains = avahi_string_list_add(c->server_config.browse_domains, cleaned);
499                     }
500                     
501                     avahi_strfreev(e);
502                 } else if (strcasecmp(p->key, "use-ipv4") == 0)
503                     c->server_config.use_ipv4 = is_yes(p->value);
504                 else if (strcasecmp(p->key, "use-ipv6") == 0)
505                     c->server_config.use_ipv6 = is_yes(p->value);
506                 else if (strcasecmp(p->key, "check-response-ttl") == 0)
507                     c->server_config.check_response_ttl = is_yes(p->value);
508                 else if (strcasecmp(p->key, "allow-point-to-point") == 0)
509                     c->server_config.allow_point_to_point = is_yes(p->value);
510                 else if (strcasecmp(p->key, "use-iff-running") == 0)
511                     c->server_config.use_iff_running = is_yes(p->value);
512                 else if (strcasecmp(p->key, "disallow-other-stacks") == 0)
513                     c->server_config.disallow_other_stacks = is_yes(p->value);
514 #ifdef HAVE_DBUS
515                 else if (strcasecmp(p->key, "enable-dbus") == 0) {
516
517                     if (*(p->value) == 'w' || *(p->value) == 'W') {
518                         c->fail_on_missing_dbus = 0;
519                         c->enable_dbus = 1;
520                     } else if (*(p->value) == 'y' || *(p->value) == 'Y') {
521                         c->fail_on_missing_dbus = 1;
522                         c->enable_dbus = 1;
523                     } else {
524                         c->enable_dbus = 0;
525                     }
526                 }
527 #endif
528                 else {
529                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
530                     goto finish;
531                 }
532             }
533             
534         } else if (strcasecmp(g->name, "publish") == 0) {
535             AvahiIniFilePair *p;
536
537             for (p = g->pairs; p; p = p->pairs_next) {
538                 
539                 if (strcasecmp(p->key, "publish-addresses") == 0)
540                     c->server_config.publish_addresses = is_yes(p->value);
541                 else if (strcasecmp(p->key, "publish-hinfo") == 0)
542                     c->server_config.publish_hinfo = is_yes(p->value);
543                 else if (strcasecmp(p->key, "publish-workstation") == 0)
544                     c->server_config.publish_workstation = is_yes(p->value);
545                 else if (strcasecmp(p->key, "publish-domain") == 0)
546                     c->server_config.publish_domain = is_yes(p->value);
547                 else if (strcasecmp(p->key, "publish-resolv-conf-dns-servers") == 0)
548                     c->publish_resolv_conf = is_yes(p->value);
549                 else if (strcasecmp(p->key, "disable-publishing") == 0)
550                     c->server_config.disable_publishing = is_yes(p->value);
551                 else if (strcasecmp(p->key, "disable-user-service-publishing") == 0)
552                     c->disable_user_service_publishing = is_yes(p->value);
553                 else if (strcasecmp(p->key, "add-service-cookie") == 0)
554                     c->server_config.add_service_cookie = is_yes(p->value);
555                 else if (strcasecmp(p->key, "publish-dns-servers") == 0) {
556                     avahi_strfreev(c->publish_dns_servers);
557                     c->publish_dns_servers = avahi_split_csv(p->value);
558                 } else if (strcasecmp(p->key, "publish-a-on-ipv6") == 0)
559                     c->server_config.publish_a_on_ipv6 = is_yes(p->value);
560                 else if (strcasecmp(p->key, "publish-aaaa-on-ipv4") == 0)
561                     c->server_config.publish_aaaa_on_ipv4 = is_yes(p->value);
562                 else {
563                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
564                     goto finish;
565                 }
566             }
567
568         } else if (strcasecmp(g->name, "wide-area") == 0) {
569             AvahiIniFilePair *p;
570
571             for (p = g->pairs; p; p = p->pairs_next) {
572                 
573                 if (strcasecmp(p->key, "enable-wide-area") == 0)
574                     c->server_config.enable_wide_area = is_yes(p->value);
575                 else {
576                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
577                     goto finish;
578                 }
579             }
580             
581         } else if (strcasecmp(g->name, "reflector") == 0) {
582             AvahiIniFilePair *p;
583
584             for (p = g->pairs; p; p = p->pairs_next) {
585                 
586                 if (strcasecmp(p->key, "enable-reflector") == 0)
587                     c->server_config.enable_reflector = is_yes(p->value);
588                 else if (strcasecmp(p->key, "reflect-ipv") == 0)
589                     c->server_config.reflect_ipv = is_yes(p->value);
590                 else {
591                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
592                     goto finish;
593                 }
594             }
595             
596         } else if (strcasecmp(g->name, "rlimits") == 0) {
597             AvahiIniFilePair *p;
598
599             for (p = g->pairs; p; p = p->pairs_next) {
600                 
601                 if (strcasecmp(p->key, "rlimit-as") == 0) {
602                     c->rlimit_as_set = 1;
603                     c->rlimit_as = atoi(p->value);
604                 } else if (strcasecmp(p->key, "rlimit-core") == 0) {
605                     c->rlimit_core_set = 1;
606                     c->rlimit_core = atoi(p->value);
607                 } else if (strcasecmp(p->key, "rlimit-data") == 0) {
608                     c->rlimit_data_set = 1;
609                     c->rlimit_data = atoi(p->value);
610                 } else if (strcasecmp(p->key, "rlimit-fsize") == 0) {
611                     c->rlimit_fsize_set = 1;
612                     c->rlimit_fsize = atoi(p->value);
613                 } else if (strcasecmp(p->key, "rlimit-nofile") == 0) {
614                     c->rlimit_nofile_set = 1;
615                     c->rlimit_nofile = atoi(p->value);
616                 } else if (strcasecmp(p->key, "rlimit-stack") == 0) {
617                     c->rlimit_stack_set = 1;
618                     c->rlimit_stack = atoi(p->value);
619                 } else if (strcasecmp(p->key, "rlimit-nproc") == 0) {
620 #ifdef RLIMIT_NPROC
621                     c->rlimit_nproc_set = 1;
622                     c->rlimit_nproc = atoi(p->value);
623 #else
624                     avahi_log_error("Ignoring configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
625 #endif
626                 } else {
627                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
628                     goto finish;
629                 }
630
631             }
632             
633         } else {
634             avahi_log_error("Invalid configuration file group \"%s\".\n", g->name);
635             goto finish;
636         }
637     }
638
639     r = 0;
640
641 finish:
642
643     if (f)
644         avahi_ini_file_free(f);
645     
646     return r;
647 }
648
649 static void log_function(AvahiLogLevel level, const char *txt) {
650
651     static const int log_level_map[] = {
652         LOG_ERR,
653         LOG_WARNING,
654         LOG_NOTICE,
655         LOG_INFO,
656         LOG_DEBUG
657     };
658     
659     assert(level < AVAHI_LOG_LEVEL_MAX);
660     assert(txt);
661
662     if (!config.debug && level == AVAHI_LOG_DEBUG)
663         return;
664
665     daemon_log(log_level_map[level], "%s", txt);
666 }
667
668 static void dump(const char *text, AVAHI_GCC_UNUSED void* userdata) {
669     avahi_log_info("%s", text);
670 }
671
672 #ifdef HAVE_INOTIFY
673
674 static int inotify_fd = -1;
675
676 static void add_inotify_watches(void) {
677     int c = 0;
678     /* We ignore the return values, because one or more of these files
679      * might not exist and we're OK with that. In addition we never
680      * want to remove these watches, hence we keep their ids? */
681
682 #ifdef ENABLE_CHROOT
683     c = config.use_chroot;
684 #endif
685     
686     inotify_add_watch(inotify_fd, c ? "/services" : AVAHI_SERVICE_DIR, IN_CLOSE_WRITE|IN_DELETE|IN_DELETE_SELF|IN_MOVED_FROM|IN_MOVED_TO|IN_MOVE_SELF
687 #ifdef IN_ONLYDIR
688                       |IN_ONLYDIR
689 #endif
690     );
691     inotify_add_watch(inotify_fd, c ? "/" : AVAHI_CONFIG_DIR, IN_CLOSE_WRITE|IN_DELETE|IN_DELETE_SELF|IN_MOVED_FROM|IN_MOVED_TO|IN_MOVE_SELF
692 #ifdef IN_ONLYDIR
693                       |IN_ONLYDIR
694 #endif
695     );
696 }
697
698 #endif
699
700 #ifdef HAVE_KQUEUE
701
702 #define NUM_WATCHES 2
703
704 static int kq = -1;
705 static int kfds[NUM_WATCHES];
706 static int num_kfds = 0;
707
708 static void add_kqueue_watch(const char *dir);
709
710 static void add_kqueue_watches(void) {
711         int c = 0;
712
713 #ifdef ENABLE_CHROOT
714         c = config.use_chroot;
715 #endif
716
717         add_kqueue_watch(c ? "/" : AVAHI_CONFIG_DIR);
718         add_kqueue_watch(c ? "/services" : AVAHI_SERVICE_DIR);
719 }
720
721 static void add_kqueue_watch(const char *dir) {
722         int fd;
723         struct kevent ev;
724
725         if (kq < 0)
726                 return;
727
728         if (num_kfds >= NUM_WATCHES)
729                 return;
730
731         fd = open(dir, O_RDONLY);
732         if (fd < 0)
733                 return;
734         EV_SET(&ev, fd, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_CLEAR,
735                         NOTE_DELETE | NOTE_EXTEND | NOTE_WRITE | NOTE_RENAME,
736                         0, 0);
737         if (kevent(kq, &ev, 1, NULL, 0, NULL) == -1) {
738                 close(fd);
739                 return;
740         }
741
742         kfds[num_kfds++] = fd;
743 }
744
745 #endif
746
747 static void reload_config(void) {
748
749 #ifdef HAVE_INOTIFY
750     /* Refresh in case the config dirs have been removed */
751     add_inotify_watches();
752 #endif
753
754 #ifdef HAVE_KQUEUE
755     add_kqueue_watches();
756 #endif
757
758 #ifdef ENABLE_CHROOT
759     static_service_load(config.use_chroot);
760     static_hosts_load(config.use_chroot);
761 #else
762     static_service_load(0);
763     static_hosts_load(0);
764 #endif            
765     static_service_add_to_server();
766     static_hosts_add_to_server();
767     
768     if (resolv_conf_entry_group)
769         avahi_s_entry_group_reset(resolv_conf_entry_group);
770     
771     load_resolv_conf();
772     
773     update_wide_area_servers();
774     
775     if (config.publish_resolv_conf && resolv_conf && resolv_conf[0])
776         resolv_conf_entry_group = add_dns_servers(avahi_server, resolv_conf_entry_group, resolv_conf);
777 }
778
779 #ifdef HAVE_INOTIFY
780
781 static void inotify_callback(AvahiWatch *watch, int fd, AVAHI_GCC_UNUSED AvahiWatchEvent event, AVAHI_GCC_UNUSED void *userdata) {
782     char* buffer;
783     int n = 0;
784
785     assert(fd == inotify_fd);
786     assert(watch);
787
788     ioctl(inotify_fd, FIONREAD, &n);
789     if (n <= 0)
790         n = 128;
791
792     buffer = avahi_malloc(n);
793     if (read(inotify_fd, buffer, n) < 0 ) {
794         avahi_free(buffer);
795         avahi_log_error("Failed to read inotify event: %s", avahi_strerror(errno));
796         return;
797     }
798     avahi_free(buffer);
799
800     avahi_log_info("Files changed, reloading.");
801     reload_config();
802 }
803
804 #endif
805
806 #ifdef HAVE_KQUEUE
807
808 static void kqueue_callback(AvahiWatch *watch, int fd, AVAHI_GCC_UNUSED AvahiWatchEvent event, AVAHI_GCC_UNUSED void *userdata) {
809         struct kevent ev;
810         struct timespec nullts = { 0, 0 };
811         int res;
812
813         assert(fd == kq);
814         assert(watch);
815
816         res = kevent(kq, NULL, 0, &ev, 1, &nullts);
817
818         if (res > 0) {
819                 /* Sleep for a half-second to avoid potential races
820                  * during install/uninstall. */
821                 usleep(500000);
822                 avahi_log_info("Files changed, reloading.");
823                 reload_config();
824         } else {
825                 avahi_log_error("Failed to read kqueue event: %s", avahi_strerror(errno));
826         }
827 }
828
829 #endif
830
831 static void signal_callback(AvahiWatch *watch, AVAHI_GCC_UNUSED int fd, AVAHI_GCC_UNUSED AvahiWatchEvent event, AVAHI_GCC_UNUSED void *userdata) {
832     int sig;
833     const AvahiPoll *poll_api;
834     
835     assert(watch);
836     assert(simple_poll_api);
837
838     poll_api = avahi_simple_poll_get(simple_poll_api);
839
840     if ((sig = daemon_signal_next()) <= 0) {
841         avahi_log_error("daemon_signal_next() failed");
842         poll_api->watch_free(watch);
843         return;
844     }
845
846     switch (sig) {
847         case SIGINT:
848         case SIGQUIT:
849         case SIGTERM:
850             avahi_log_info(
851                 "Got %s, quitting.",
852                 sig == SIGINT ? "SIGINT" :
853                 (sig == SIGQUIT ? "SIGQUIT" : "SIGTERM"));
854             avahi_simple_poll_quit(simple_poll_api);
855             break;
856
857         case SIGHUP:
858             avahi_log_info("Got SIGHUP, reloading.");
859
860             reload_config();
861             break;
862
863         case SIGUSR1:
864             avahi_log_info("Got SIGUSR1, dumping record data.");
865             avahi_server_dump(avahi_server, dump, NULL);
866             break;
867
868         default:
869             avahi_log_warn("Got spurious signal, ignoring.");
870             break;
871     }
872 }
873
874 /* Imported from ../avahi-client/nss-check.c */
875 int avahi_nss_support(void);
876
877 static int run_server(DaemonConfig *c) {
878     int r = -1;
879     int error;
880     const AvahiPoll *poll_api = NULL;
881     AvahiWatch *sig_watch = NULL;
882     int retval_is_sent = 0;
883 #ifdef HAVE_INOTIFY
884     AvahiWatch *inotify_watch = NULL;
885 #endif
886 #ifdef HAVE_KQUEUE
887     int i;
888     AvahiWatch *kqueue_watch = NULL;
889 #endif
890
891     assert(c);
892
893     if (!(nss_support = avahi_nss_support()))
894         avahi_log_warn("WARNING: No NSS support for mDNS detected, consider installing nss-mdns!");
895
896     if (!(simple_poll_api = avahi_simple_poll_new())) {
897         avahi_log_error("Failed to create main loop object.");
898         goto finish;
899     }
900
901     poll_api = avahi_simple_poll_get(simple_poll_api);
902
903     if (daemon_signal_init(SIGINT, SIGQUIT, SIGHUP, SIGTERM, SIGUSR1, 0) < 0) {
904         avahi_log_error("Could not register signal handlers (%s).", strerror(errno));
905         goto finish;
906     }
907
908     if (!(sig_watch = poll_api->watch_new(poll_api, daemon_signal_fd(), AVAHI_WATCH_IN, signal_callback, simple_poll_api))) {
909         avahi_log_error( "Failed to create signal watcher");
910         goto finish;
911     }
912
913     if (simple_protocol_setup(poll_api) < 0)
914         goto finish;
915
916 #ifdef HAVE_DBUS
917     if (c->enable_dbus) {
918         if (dbus_protocol_setup(poll_api, config.disable_user_service_publishing, !c->fail_on_missing_dbus
919 #ifdef ENABLE_CHROOT
920                                 && !config.use_chroot
921 #endif
922             ) < 0) {
923
924             avahi_log_warn("WARNING: Failed to contact D-Bus daemon.");
925
926             if (c->fail_on_missing_dbus)
927                 goto finish;
928         }
929     }
930 #endif
931
932 #ifdef ENABLE_CHROOT
933
934     if (config.drop_root && config.use_chroot) {
935         if (chroot(AVAHI_CONFIG_DIR) < 0) {
936             avahi_log_error("Failed to chroot(): %s", strerror(errno));
937             goto finish;
938         }
939         
940         avahi_log_info("Successfully called chroot().");
941         chdir("/");
942         
943         if (avahi_caps_drop_all() < 0) {
944             avahi_log_error("Failed to drop capabilities.");
945             goto finish;
946         }
947         avahi_log_info("Successfully dropped remaining capabilities.");
948     }
949     
950 #endif
951
952 #ifdef HAVE_INOTIFY
953     if ((inotify_fd = inotify_init()) < 0)
954         avahi_log_warn( "Failed to initialize inotify: %s", strerror(errno));
955     else {
956         add_inotify_watches();
957         
958         if (!(inotify_watch = poll_api->watch_new(poll_api, inotify_fd, AVAHI_WATCH_IN, inotify_callback, NULL))) {
959             avahi_log_error( "Failed to create inotify watcher");
960             goto finish;
961         }
962     }
963 #endif
964
965 #ifdef HAVE_KQUEUE
966     if ((kq = kqueue()) < 0)
967             avahi_log_warn( "Failed to initialize kqueue: %s", strerror(errno));
968     else {
969             add_kqueue_watches();
970
971             if (!(kqueue_watch = poll_api->watch_new(poll_api, kq, AVAHI_WATCH_IN, kqueue_callback, NULL))) {
972                     avahi_log_error( "Failed to create kqueue watcher");
973                     goto finish;
974             }
975     }
976 #endif
977
978     load_resolv_conf();
979 #ifdef ENABLE_CHROOT
980     static_service_load(config.use_chroot);
981     static_hosts_load(config.use_chroot);
982 #else
983     static_service_load(0);
984     static_hosts_load(0);
985 #endif
986
987     if (!(avahi_server = avahi_server_new(poll_api, &c->server_config, server_callback, c, &error))) {
988         avahi_log_error("Failed to create server: %s", avahi_strerror(error));
989         goto finish;
990     }
991
992     update_wide_area_servers();
993
994     if (c->daemonize) {
995         daemon_retval_send(0);
996         retval_is_sent = 1;
997     }
998
999     for (;;) {
1000         if ((r = avahi_simple_poll_iterate(simple_poll_api, -1)) < 0) {
1001
1002             /* We handle signals through an FD, so let's continue */
1003             if (errno == EINTR)
1004                 continue;
1005             
1006             avahi_log_error("poll(): %s", strerror(errno));
1007             goto finish;
1008         } else if (r > 0)
1009             /* Quit */
1010             break;
1011     }
1012     
1013
1014 finish:
1015     
1016     static_service_remove_from_server();
1017     static_service_free_all();
1018
1019     static_hosts_remove_from_server();
1020     static_hosts_free_all();
1021
1022     remove_dns_server_entry_groups();
1023     
1024     simple_protocol_shutdown();
1025
1026 #ifdef HAVE_DBUS
1027     if (c->enable_dbus)
1028         dbus_protocol_shutdown();
1029 #endif
1030
1031     if (avahi_server) {
1032         avahi_server_free(avahi_server);
1033         avahi_server = NULL;
1034     }
1035
1036     daemon_signal_done();
1037
1038     if (sig_watch)
1039         poll_api->watch_free(sig_watch);
1040
1041 #ifdef HAVE_INOTIFY
1042     if (inotify_watch)
1043         poll_api->watch_free(inotify_watch);
1044     if (inotify_fd >= 0)
1045         close(inotify_fd);
1046 #endif
1047
1048 #ifdef HAVE_KQUEUE
1049     if (kqueue_watch)
1050         poll_api->watch_free(kqueue_watch);
1051     if (kq >= 0)
1052         close(kq);
1053     for (i = 0; i < num_kfds; i++) {
1054         if (kfds[i] >= 0)
1055             close(kfds[i]);
1056     }
1057 #endif
1058     
1059     if (simple_poll_api) {
1060         avahi_simple_poll_free(simple_poll_api);
1061         simple_poll_api = NULL;
1062     }
1063
1064     if (!retval_is_sent && c->daemonize)
1065         daemon_retval_send(1);
1066     
1067     return r;
1068 }
1069
1070 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
1071
1072 static int drop_root(void) {
1073     struct passwd *pw;
1074     struct group * gr;
1075     int r;
1076     
1077     if (!(pw = getpwnam(AVAHI_USER))) {
1078         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
1079         return -1;
1080     }
1081
1082     if (!(gr = getgrnam(AVAHI_GROUP))) {
1083         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
1084         return -1;
1085     }
1086
1087     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);
1088
1089     if (initgroups(AVAHI_USER, gr->gr_gid) != 0) {
1090         avahi_log_error("Failed to change group list: %s", strerror(errno));
1091         return -1;
1092     }
1093
1094 #if defined(HAVE_SETRESGID)
1095     r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
1096 #elif defined(HAVE_SETEGID)
1097     if ((r = setgid(gr->gr_gid)) >= 0)
1098         r = setegid(gr->gr_gid);
1099 #elif defined(HAVE_SETREGID)
1100     r = setregid(gr->gr_gid, gr->gr_gid);
1101 #else
1102 #error "No API to drop priviliges"
1103 #endif
1104
1105     if (r < 0) {
1106         avahi_log_error("Failed to change GID: %s", strerror(errno));
1107         return -1;
1108     }
1109
1110 #if defined(HAVE_SETRESUID)
1111     r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
1112 #elif defined(HAVE_SETEUID)
1113     if ((r = setuid(pw->pw_uid)) >= 0)
1114         r = seteuid(pw->pw_uid);
1115 #elif defined(HAVE_SETREUID)
1116     r = setreuid(pw->pw_uid, pw->pw_uid);
1117 #else
1118 #error "No API to drop priviliges"
1119 #endif
1120
1121     if (r < 0) {
1122         avahi_log_error("Failed to change UID: %s", strerror(errno));
1123         return -1;
1124     }
1125
1126     set_env("USER", pw->pw_name);
1127     set_env("LOGNAME", pw->pw_name);
1128     set_env("HOME", pw->pw_dir);
1129
1130     avahi_log_info("Successfully dropped root privileges.");
1131
1132     return 0;
1133 }
1134
1135 static const char* pid_file_proc(void) {
1136     return AVAHI_DAEMON_RUNTIME_DIR"/pid";
1137 }
1138
1139 static int make_runtime_dir(void) {
1140     int r = -1;
1141     mode_t u;
1142     int reset_umask = 0;
1143     struct passwd *pw;
1144     struct group * gr;
1145     struct stat st;
1146
1147     if (!(pw = getpwnam(AVAHI_USER))) {
1148         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
1149         goto fail;
1150     }
1151
1152     if (!(gr = getgrnam(AVAHI_GROUP))) {
1153         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
1154         goto fail;
1155     }
1156
1157     u = umask(0000);
1158     reset_umask = 1;
1159     
1160     if (mkdir(AVAHI_DAEMON_RUNTIME_DIR, 0755) < 0 && errno != EEXIST) {
1161         avahi_log_error("mkdir(\""AVAHI_DAEMON_RUNTIME_DIR"\"): %s", strerror(errno));
1162         goto fail;
1163     }
1164     
1165     chown(AVAHI_DAEMON_RUNTIME_DIR, pw->pw_uid, gr->gr_gid);
1166
1167     if (stat(AVAHI_DAEMON_RUNTIME_DIR, &st) < 0) {
1168         avahi_log_error("stat(): %s\n", strerror(errno));
1169         goto fail;
1170     }
1171
1172     if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
1173         avahi_log_error("Failed to create runtime directory "AVAHI_DAEMON_RUNTIME_DIR".");
1174         goto fail;
1175     }
1176
1177     r = 0;
1178
1179 fail:
1180     if (reset_umask)
1181         umask(u);
1182     return r;
1183 }
1184
1185 static void set_one_rlimit(int resource, rlim_t limit, const char *name) {
1186     struct rlimit rl;
1187     rl.rlim_cur = rl.rlim_max = limit;
1188
1189     if (setrlimit(resource, &rl) < 0)
1190         avahi_log_warn("setrlimit(%s, {%u, %u}) failed: %s", name, (unsigned) limit, (unsigned) limit, strerror(errno));
1191 }
1192
1193 static void enforce_rlimits(void) {
1194 #ifdef RLIMIT_AS
1195     if (config.rlimit_as_set)
1196         set_one_rlimit(RLIMIT_AS, config.rlimit_as, "RLIMIT_AS");
1197 #endif
1198     if (config.rlimit_core_set)
1199         set_one_rlimit(RLIMIT_CORE, config.rlimit_core, "RLIMIT_CORE");
1200     if (config.rlimit_data_set)
1201         set_one_rlimit(RLIMIT_DATA, config.rlimit_data, "RLIMIT_DATA");
1202     if (config.rlimit_fsize_set)
1203         set_one_rlimit(RLIMIT_FSIZE, config.rlimit_fsize, "RLIMIT_FSIZE");
1204     if (config.rlimit_nofile_set)
1205         set_one_rlimit(RLIMIT_NOFILE, config.rlimit_nofile, "RLIMIT_NOFILE");
1206     if (config.rlimit_stack_set)
1207         set_one_rlimit(RLIMIT_STACK, config.rlimit_stack, "RLIMIT_STACK");
1208 #ifdef RLIMIT_NPROC
1209     if (config.rlimit_nproc_set)
1210         set_one_rlimit(RLIMIT_NPROC, config.rlimit_nproc, "RLIMIT_NPROC");
1211 #endif
1212
1213     /* the sysctl() call from iface-pfroute.c needs locked memory on FreeBSD */
1214 #if defined(RLIMIT_MEMLOCK) && !defined(__FreeBSD__)
1215     /* We don't need locked memory */
1216     set_one_rlimit(RLIMIT_MEMLOCK, 0, "RLIMIT_MEMLOCK");
1217 #endif
1218 }
1219
1220 #define RANDOM_DEVICE "/dev/urandom"
1221
1222 static void init_rand_seed(void) {
1223     int fd;
1224     unsigned seed = 0;
1225
1226     /* Try to initialize seed from /dev/urandom, to make it a little
1227      * less predictable, and to make sure that multiple machines
1228      * booted at the same time choose different random seeds.  */
1229     if ((fd = open(RANDOM_DEVICE, O_RDONLY)) >= 0) {
1230         read(fd, &seed, sizeof(seed));
1231         close(fd);
1232     }
1233
1234     /* If the initialization failed by some reason, we add the time to the seed*/
1235     seed ^= (unsigned) time(NULL);
1236
1237     srand(seed);
1238 }
1239
1240 int main(int argc, char *argv[]) {
1241     int r = 255;
1242     int wrote_pid_file = 0;
1243
1244     avahi_set_log_function(log_function);
1245
1246     init_rand_seed();
1247     
1248     avahi_server_config_init(&config.server_config);
1249     config.command = DAEMON_RUN;
1250     config.daemonize = 0;
1251     config.config_file = NULL;
1252 #ifdef HAVE_DBUS
1253     config.enable_dbus = 1;
1254     config.fail_on_missing_dbus = 1;
1255 #endif
1256     
1257     config.drop_root = 1;
1258     config.set_rlimits = 1;
1259 #ifdef ENABLE_CHROOT
1260     config.use_chroot = 1;
1261 #endif
1262     config.modify_proc_title = 1;
1263
1264     config.disable_user_service_publishing = 0;
1265     config.publish_dns_servers = NULL;
1266     config.publish_resolv_conf = 0;
1267     config.use_syslog = 0;
1268     config.debug = 0;
1269     config.rlimit_as_set = 0;
1270     config.rlimit_core_set = 0;
1271     config.rlimit_data_set = 0;
1272     config.rlimit_fsize_set = 0;
1273     config.rlimit_nofile_set = 0;
1274     config.rlimit_stack_set = 0;
1275 #ifdef RLIMIT_NPROC
1276     config.rlimit_nproc_set = 0;
1277 #endif
1278     
1279     if ((argv0 = strrchr(argv[0], '/')))
1280         argv0 = avahi_strdup(argv0 + 1);
1281     else
1282         argv0 = avahi_strdup(argv[0]);
1283
1284     daemon_pid_file_ident = (const char *) argv0;
1285     daemon_log_ident = (char*) argv0;
1286     daemon_pid_file_proc = pid_file_proc;
1287     
1288     if (parse_command_line(&config, argc, argv) < 0)
1289         goto finish;
1290
1291     if (config.modify_proc_title)
1292         avahi_init_proc_title(argc, argv);
1293
1294 #ifdef ENABLE_CHROOT
1295     config.use_chroot = config.use_chroot && config.drop_root;
1296 #endif
1297     
1298     if (config.command == DAEMON_HELP) {
1299         help(stdout);
1300         r = 0;
1301     } else if (config.command == DAEMON_VERSION) {
1302         printf("%s "PACKAGE_VERSION"\n", argv0);
1303         r = 0;
1304     } else if (config.command == DAEMON_KILL) {
1305         if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
1306             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
1307             goto finish;
1308         }
1309
1310         r = 0;
1311
1312     } else if (config.command == DAEMON_RELOAD) {
1313         if (daemon_pid_file_kill(SIGHUP) < 0) {
1314             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
1315             goto finish;
1316         }
1317
1318         r = 0;
1319         
1320     } else if (config.command == DAEMON_CHECK)
1321         r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
1322     else if (config.command == DAEMON_RUN) {
1323         pid_t pid;
1324
1325         if (getuid() != 0 && config.drop_root) {
1326             avahi_log_error("This program is intended to be run as root.");
1327             goto finish;
1328         }
1329         
1330         if ((pid = daemon_pid_file_is_running()) >= 0) {
1331             avahi_log_error("Daemon already running on PID %u", pid);
1332             goto finish;
1333         }
1334
1335         if (load_config_file(&config) < 0)
1336             goto finish;
1337         
1338         if (config.daemonize) {
1339             daemon_retval_init();
1340             
1341             if ((pid = daemon_fork()) < 0)
1342                 goto finish;
1343             else if (pid != 0) {
1344                 int ret;
1345                 /** Parent **/
1346
1347                 if ((ret = daemon_retval_wait(20)) < 0) {
1348                     avahi_log_error("Could not receive return value from daemon process.");
1349                     goto finish;
1350                 }
1351
1352                 r = ret;
1353                 goto finish;
1354             }
1355
1356             /* Child */
1357         }
1358
1359         if (config.use_syslog || config.daemonize)
1360             daemon_log_use = DAEMON_LOG_SYSLOG;
1361
1362         if (daemon_close_all(-1) < 0) {
1363             avahi_log_error("Failed to close remaining file descriptors: %s", strerror(errno));
1364             goto finish;
1365         }
1366         
1367         if (make_runtime_dir() < 0)
1368             goto finish;
1369
1370         if (config.drop_root) {
1371 #ifdef ENABLE_CHROOT
1372             if (config.use_chroot)
1373                 if (avahi_caps_reduce() < 0)
1374                     goto finish;
1375 #endif
1376             
1377             if (drop_root() < 0)
1378                 goto finish;
1379
1380 #ifdef ENABLE_CHROOT
1381             if (config.use_chroot)
1382                 if (avahi_caps_reduce2() < 0)
1383                     goto finish;
1384 #endif
1385         }
1386
1387         if (daemon_pid_file_create() < 0) {
1388             avahi_log_error("Failed to create PID file: %s", strerror(errno));
1389
1390             if (config.daemonize)
1391                 daemon_retval_send(1);
1392             goto finish;
1393         } else
1394             wrote_pid_file = 1;
1395
1396         if (config.set_rlimits)
1397             enforce_rlimits();
1398
1399         chdir("/");
1400
1401 #ifdef ENABLE_CHROOT
1402         if (config.drop_root && config.use_chroot)
1403             if (avahi_chroot_helper_start(argv0) < 0) {
1404                 avahi_log_error("failed to start chroot() helper daemon.");
1405                 goto finish;
1406             }
1407 #endif
1408         avahi_log_info("%s "PACKAGE_VERSION" starting up.", argv0);
1409
1410         avahi_set_proc_title(argv0, "%s: starting up", argv0);
1411         
1412         if (run_server(&config) == 0)
1413             r = 0;
1414     }
1415         
1416 finish:
1417
1418     if (config.daemonize)
1419         daemon_retval_done();
1420
1421     avahi_server_config_free(&config.server_config);
1422     avahi_free(config.config_file);
1423     avahi_strfreev(config.publish_dns_servers);
1424     avahi_strfreev(resolv_conf);
1425
1426     if (wrote_pid_file) {
1427 #ifdef ENABLE_CHROOT
1428         avahi_chroot_helper_unlink(pid_file_proc());
1429 #else
1430         daemon_pid_file_remove();
1431 #endif
1432     }
1433
1434 #ifdef ENABLE_CHROOT
1435     avahi_chroot_helper_shutdown();
1436 #endif
1437
1438     avahi_free(argv0);
1439     
1440     return r;
1441 }