]> git.meshlink.io Git - catta/blob - avahi-daemon/main.c
* add two new configuration file options: "disable-publishing" and "disable-user...
[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
707     assert(c);
708
709     if (!(simple_poll_api = avahi_simple_poll_new())) {
710         avahi_log_error("Failed to create main loop object.");
711         goto finish;
712     }
713
714     poll_api = avahi_simple_poll_get(simple_poll_api);
715
716     if (daemon_signal_init(SIGINT, SIGQUIT, SIGHUP, SIGTERM, SIGUSR1, 0) < 0) {
717         avahi_log_error("Could not register signal handlers (%s).", strerror(errno));
718         goto finish;
719     }
720
721     if (!(sig_watch = poll_api->watch_new(poll_api, daemon_signal_fd(), AVAHI_WATCH_IN, signal_callback, simple_poll_api))) {
722         avahi_log_error( "Failed to create signal watcher");
723         goto finish;
724     }
725
726     if (simple_protocol_setup(poll_api) < 0)
727         goto finish;
728
729 #ifdef HAVE_DBUS
730     if (c->enable_dbus) {
731         if (dbus_protocol_setup(poll_api, config.disable_user_service_publishing) < 0) {
732
733             if (c->fail_on_missing_dbus)
734                 goto finish;
735
736             avahi_log_warn("WARNING: Failed to contact D-BUS daemon, disabling D-BUS support.");
737             c->enable_dbus = 0;
738         }
739     }
740 #endif
741
742 #ifdef ENABLE_CHROOT
743
744     if (config.drop_root && config.use_chroot) {
745         if (chroot(AVAHI_CONFIG_DIR) < 0) {
746             avahi_log_error("Failed to chroot(): %s", strerror(errno));
747             goto finish;
748         }
749         
750         chdir("/");
751         
752         if (avahi_caps_drop_all() < 0) {
753             avahi_log_error("Failed to drop capabilities.");
754             goto finish;
755         }
756
757         avahi_log_info("chroot() successful.");
758     }
759     
760 #endif
761
762     load_resolv_conf();
763 #ifdef ENABLE_CHROOT
764     static_service_load(config.use_chroot);
765 #else
766     static_service_load(0);
767 #endif
768
769     if (!(avahi_server = avahi_server_new(poll_api, &c->server_config, server_callback, c, &error))) {
770         avahi_log_error("Failed to create server: %s", avahi_strerror(error));
771         goto finish;
772     }
773
774     update_wide_area_servers();
775
776     if (c->daemonize)
777         daemon_retval_send(0);
778
779     for (;;) {
780         if ((r = avahi_simple_poll_iterate(simple_poll_api, -1)) < 0) {
781
782             /* We handle signals through an FD, so let's continue */
783             if (errno == EINTR)
784                 continue;
785             
786             avahi_log_error("poll(): %s", strerror(errno));
787             goto finish;
788         } else if (r > 0)
789             /* Quit */
790             break;
791     }
792     
793
794 finish:
795     
796     static_service_remove_from_server();
797     static_service_free_all();
798     remove_dns_server_entry_groups();
799     
800     simple_protocol_shutdown();
801
802 #ifdef HAVE_DBUS
803     if (c->enable_dbus)
804         dbus_protocol_shutdown();
805 #endif
806
807     if (avahi_server) {
808         avahi_server_free(avahi_server);
809         avahi_server = NULL;
810     }
811
812     daemon_signal_done();
813
814     if (sig_watch)
815         poll_api->watch_free(sig_watch);
816
817     if (simple_poll_api) {
818         avahi_simple_poll_free(simple_poll_api);
819         simple_poll_api = NULL;
820     }
821
822     if (r != 0 && c->daemonize)
823         daemon_retval_send(1);
824     
825     return r;
826 }
827
828 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
829
830 static int drop_root(void) {
831     struct passwd *pw;
832     struct group * gr;
833     int r;
834     
835     if (!(pw = getpwnam(AVAHI_USER))) {
836         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
837         return -1;
838     }
839
840     if (!(gr = getgrnam(AVAHI_GROUP))) {
841         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
842         return -1;
843     }
844
845     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);
846
847     if (initgroups(AVAHI_USER, gr->gr_gid) != 0) {
848         avahi_log_error("Failed to change group list: %s", strerror(errno));
849         return -1;
850     }
851
852 #if defined(HAVE_SETRESGID)
853     r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
854 #elif defined(HAVE_SETEGID)
855     if ((r = setgid(gr->gr_gid)) >= 0)
856         r = setegid(gr->gr_gid);
857 #elif defined(HAVE_SETREGID)
858     r = setregid(gr->gr_gid, gr->gr_gid);
859 #else
860 #error "No API to drop priviliges"
861 #endif
862
863     if (r < 0) {
864         avahi_log_error("Failed to change GID: %s", strerror(errno));
865         return -1;
866     }
867
868 #if defined(HAVE_SETRESUID)
869     r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
870 #elif defined(HAVE_SETEUID)
871     if ((r = setuid(pw->pw_uid)) >= 0)
872         r = seteuid(pw->pw_uid);
873 #elif defined(HAVE_SETREUID)
874     r = setreuid(pw->pw_uid, pw->pw_uid);
875 #else
876 #error "No API to drop priviliges"
877 #endif
878
879     if (r < 0) {
880         avahi_log_error("Failed to change UID: %s", strerror(errno));
881         return -1;
882     }
883
884     set_env("USER", pw->pw_name);
885     set_env("LOGNAME", pw->pw_name);
886     set_env("HOME", pw->pw_dir);
887
888     avahi_log_info("Successfully dropped root privileges.");
889
890     return 0;
891 }
892
893 static const char* pid_file_proc(void) {
894     return AVAHI_DAEMON_RUNTIME_DIR"/pid";
895 }
896
897 static int make_runtime_dir(void) {
898     int r = -1;
899     mode_t u;
900     int reset_umask = 0;
901     struct passwd *pw;
902     struct group * gr;
903     struct stat st;
904
905     if (!(pw = getpwnam(AVAHI_USER))) {
906         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
907         goto fail;
908     }
909
910     if (!(gr = getgrnam(AVAHI_GROUP))) {
911         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
912         goto fail;
913     }
914
915     u = umask(0000);
916     reset_umask = 1;
917     
918     if (mkdir(AVAHI_DAEMON_RUNTIME_DIR, 0755) < 0 && errno != EEXIST) {
919         avahi_log_error("mkdir(\""AVAHI_DAEMON_RUNTIME_DIR"\"): %s", strerror(errno));
920         goto fail;
921     }
922     
923     chown(AVAHI_DAEMON_RUNTIME_DIR, pw->pw_uid, gr->gr_gid);
924
925     if (stat(AVAHI_DAEMON_RUNTIME_DIR, &st) < 0) {
926         avahi_log_error("stat(): %s\n", strerror(errno));
927         goto fail;
928     }
929
930     if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
931         avahi_log_error("Failed to create runtime directory "AVAHI_DAEMON_RUNTIME_DIR".");
932         goto fail;
933     }
934
935     r = 0;
936
937 fail:
938     if (reset_umask)
939         umask(u);
940     return r;
941 }
942
943 static void set_one_rlimit(int resource, rlim_t limit, const char *name) {
944     struct rlimit rl;
945     rl.rlim_cur = rl.rlim_max = limit;
946
947     if (setrlimit(resource, &rl) < 0)
948         avahi_log_warn("setrlimit(%s, {%u, %u}) failed: %s", name, (unsigned) limit, (unsigned) limit, strerror(errno));
949 }
950
951 static void enforce_rlimits(void) {
952 #ifdef RLIMIT_AS
953     if (config.rlimit_as_set)
954         set_one_rlimit(RLIMIT_AS, config.rlimit_as, "RLIMIT_AS");
955 #endif
956     if (config.rlimit_core_set)
957         set_one_rlimit(RLIMIT_CORE, config.rlimit_core, "RLIMIT_CORE");
958     if (config.rlimit_data_set)
959         set_one_rlimit(RLIMIT_DATA, config.rlimit_data, "RLIMIT_DATA");
960     if (config.rlimit_fsize_set)
961         set_one_rlimit(RLIMIT_FSIZE, config.rlimit_fsize, "RLIMIT_FSIZE");
962     if (config.rlimit_nofile_set)
963         set_one_rlimit(RLIMIT_NOFILE, config.rlimit_nofile, "RLIMIT_NOFILE");
964     if (config.rlimit_stack_set)
965         set_one_rlimit(RLIMIT_STACK, config.rlimit_stack, "RLIMIT_STACK");
966 #ifdef RLIMIT_NPROC
967     if (config.rlimit_nproc_set)
968         set_one_rlimit(RLIMIT_NPROC, config.rlimit_nproc, "RLIMIT_NPROC");
969 #endif
970
971 #ifdef RLIMIT_MEMLOCK
972     /* We don't need locked memory */
973     set_one_rlimit(RLIMIT_MEMLOCK, 0, "RLIMIT_MEMLOCK");
974 #endif
975 }
976
977 #define RANDOM_DEVICE "/dev/urandom"
978
979 static void init_rand_seed(void) {
980     int fd;
981     unsigned seed = 0;
982
983     /* Try to initialize seed from /dev/urandom, to make it a little
984      * less predictable, and to make sure that multiple machines
985      * booted at the same time choose different random seeds.  */
986     if ((fd = open(RANDOM_DEVICE, O_RDONLY)) >= 0) {
987         read(fd, &seed, sizeof(seed));
988         close(fd);
989     }
990
991     /* If the initialization failed by some reason, we add the time to the seed*/
992     seed |= (unsigned) time(NULL);
993
994     srand(seed);
995 }
996
997 int main(int argc, char *argv[]) {
998     int r = 255;
999     int wrote_pid_file = 0;
1000
1001     avahi_set_log_function(log_function);
1002
1003     init_rand_seed();
1004     
1005     avahi_server_config_init(&config.server_config);
1006     config.command = DAEMON_RUN;
1007     config.daemonize = 0;
1008     config.config_file = NULL;
1009 #ifdef HAVE_DBUS
1010     config.enable_dbus = 1;
1011     config.fail_on_missing_dbus = 1;
1012 #endif
1013     
1014     config.drop_root = 1;
1015     config.set_rlimits = 1;
1016 #ifdef ENABLE_CHROOT
1017     config.use_chroot = 1;
1018 #endif
1019     config.modify_proc_title = 1;
1020
1021     config.disable_user_service_publishing = 0;
1022     config.publish_dns_servers = NULL;
1023     config.publish_resolv_conf = 0;
1024     config.use_syslog = 0;
1025     config.debug = 0;
1026     config.rlimit_as_set = 0;
1027     config.rlimit_core_set = 0;
1028     config.rlimit_data_set = 0;
1029     config.rlimit_fsize_set = 0;
1030     config.rlimit_nofile_set = 0;
1031     config.rlimit_stack_set = 0;
1032 #ifdef RLIMIT_NPROC
1033     config.rlimit_nproc_set = 0;
1034 #endif
1035     
1036     if ((argv0 = strrchr(argv[0], '/')))
1037         argv0 = avahi_strdup(argv0 + 1);
1038     else
1039         argv0 = avahi_strdup(argv[0]);
1040
1041     daemon_pid_file_ident = (const char *) argv0;
1042     daemon_log_ident = (char*) argv0;
1043     daemon_pid_file_proc = pid_file_proc;
1044     
1045     if (parse_command_line(&config, argc, argv) < 0)
1046         goto finish;
1047
1048     if (config.modify_proc_title)
1049         avahi_init_proc_title(argc, argv);
1050
1051 #ifdef ENABLE_CHROOT
1052     config.use_chroot = config.use_chroot && config.drop_root;
1053 #endif
1054     
1055     if (config.command == DAEMON_HELP) {
1056         help(stdout);
1057         r = 0;
1058     } else if (config.command == DAEMON_VERSION) {
1059         printf("%s "PACKAGE_VERSION"\n", argv0);
1060         r = 0;
1061     } else if (config.command == DAEMON_KILL) {
1062         if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
1063             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
1064             goto finish;
1065         }
1066
1067         r = 0;
1068
1069     } else if (config.command == DAEMON_RELOAD) {
1070         if (daemon_pid_file_kill(SIGHUP) < 0) {
1071             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
1072             goto finish;
1073         }
1074
1075         r = 0;
1076         
1077     } else if (config.command == DAEMON_CHECK)
1078         r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
1079     else if (config.command == DAEMON_RUN) {
1080         pid_t pid;
1081
1082         if (getuid() != 0 && config.drop_root) {
1083             avahi_log_error("This program is intended to be run as root.");
1084             goto finish;
1085         }
1086         
1087         if ((pid = daemon_pid_file_is_running()) >= 0) {
1088             avahi_log_error("Daemon already running on PID %u", pid);
1089             goto finish;
1090         }
1091
1092         if (load_config_file(&config) < 0)
1093             goto finish;
1094         
1095         if (config.daemonize) {
1096             daemon_retval_init();
1097             
1098             if ((pid = daemon_fork()) < 0)
1099                 goto finish;
1100             else if (pid != 0) {
1101                 int ret;
1102                 /** Parent **/
1103
1104                 if ((ret = daemon_retval_wait(20)) < 0) {
1105                     avahi_log_error("Could not receive return value from daemon process.");
1106                     goto finish;
1107                 }
1108
1109                 r = ret;
1110                 goto finish;
1111             }
1112
1113             /* Child */
1114         }
1115
1116         if (config.use_syslog || config.daemonize)
1117             daemon_log_use = DAEMON_LOG_SYSLOG;
1118
1119         if (make_runtime_dir() < 0)
1120             goto finish;
1121
1122         if (config.drop_root) {
1123 #ifdef ENABLE_CHROOT
1124             if (config.use_chroot)
1125                 if (avahi_caps_reduce() < 0)
1126                     goto finish;
1127 #endif
1128             
1129             if (drop_root() < 0)
1130                 goto finish;
1131
1132 #ifdef ENABLE_CHROOT
1133             if (config.use_chroot)
1134                 if (avahi_caps_reduce2() < 0)
1135                     goto finish;
1136 #endif
1137         }
1138
1139         if (daemon_pid_file_create() < 0) {
1140             avahi_log_error("Failed to create PID file: %s", strerror(errno));
1141
1142             if (config.daemonize)
1143                 daemon_retval_send(1);
1144             goto finish;
1145         } else
1146             wrote_pid_file = 1;
1147
1148         if (config.set_rlimits)
1149             enforce_rlimits();
1150
1151         chdir("/");
1152
1153 #ifdef ENABLE_CHROOT
1154         if (config.drop_root && config.use_chroot)
1155             if (avahi_chroot_helper_start(argv0) < 0) {
1156                 avahi_log_error("failed to start chroot() helper daemon.");
1157                 goto finish;
1158             }
1159 #endif
1160         avahi_log_info("%s "PACKAGE_VERSION" starting up.", argv0);
1161
1162         avahi_set_proc_title("%s: starting up", argv0);
1163         
1164         if (run_server(&config) == 0)
1165             r = 0;
1166     }
1167         
1168 finish:
1169
1170     if (config.daemonize)
1171         daemon_retval_done();
1172
1173     avahi_server_config_free(&config.server_config);
1174     avahi_free(config.config_file);
1175     avahi_strfreev(config.publish_dns_servers);
1176     avahi_strfreev(resolv_conf);
1177
1178     if (wrote_pid_file) {
1179 #ifdef ENABLE_CHROOT
1180         avahi_chroot_helper_unlink(pid_file_proc());
1181 #else
1182         daemon_pid_file_remove();
1183 #endif
1184     }
1185
1186 #ifdef ENABLE_CHROOT
1187     avahi_chroot_helper_shutdown();
1188 #endif
1189
1190     avahi_free(argv0);
1191     
1192     return r;
1193 }