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