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