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