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