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