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