]> git.meshlink.io Git - catta/blob - avahi-daemon/main.c
* adapt to recent avahi-core API changes
[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, 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, "enable-dbus") == 0) {
397
398                     if (*(p->value) == 'w' || *(p->value) == 'W') {
399                         c->fail_on_missing_dbus = 0;
400                         c->enable_dbus = 1;
401                     } else if (*(p->value) == 'y' || *(p->value) == 'Y') {
402                         c->fail_on_missing_dbus = 1;
403                         c->enable_dbus = 1;
404                     } else {
405                         c->enable_dbus = 0;
406                     }
407                 } else if (strcasecmp(p->key, "drop-root") == 0)
408                     c->drop_root = is_yes(p->value);
409                 else if (strcasecmp(p->key, "add-service-cookie") == 0)
410                     c->server_config.add_service_cookie = is_yes(p->value);
411                 else {
412                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
413                     goto finish;
414                 }
415             }
416             
417         } else if (strcasecmp(g->name, "publish") == 0) {
418             AvahiIniFilePair *p;
419
420             for (p = g->pairs; p; p = p->pairs_next) {
421                 
422                 if (strcasecmp(p->key, "publish-addresses") == 0)
423                     c->server_config.publish_addresses = is_yes(p->value);
424                 else if (strcasecmp(p->key, "publish-hinfo") == 0)
425                     c->server_config.publish_hinfo = is_yes(p->value);
426                 else if (strcasecmp(p->key, "publish-workstation") == 0)
427                     c->server_config.publish_workstation = is_yes(p->value);
428                 else if (strcasecmp(p->key, "publish-domain") == 0)
429                     c->server_config.publish_domain = is_yes(p->value);
430                 else if (strcasecmp(p->key, "publish-resolv-conf-dns-servers") == 0)
431                     c->publish_resolv_conf = is_yes(p->value);
432                 else if (strcasecmp(p->key, "publish-dns-servers") == 0) {
433                     avahi_strfreev(c->publish_dns_servers);
434                     c->publish_dns_servers = avahi_split_csv(p->value);
435                 } else {
436                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
437                     goto finish;
438                 }
439             }
440
441         } else if (strcasecmp(g->name, "wide-area") == 0) {
442             AvahiIniFilePair *p;
443
444             for (p = g->pairs; p; p = p->pairs_next) {
445                 
446                 if (strcasecmp(p->key, "enable-wide-area") == 0)
447                     c->server_config.enable_wide_area = is_yes(p->value);
448                 else {
449                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
450                     goto finish;
451                 }
452             }
453             
454         } else if (strcasecmp(g->name, "reflector") == 0) {
455             AvahiIniFilePair *p;
456
457             for (p = g->pairs; p; p = p->pairs_next) {
458                 
459                 if (strcasecmp(p->key, "enable-reflector") == 0)
460                     c->server_config.enable_reflector = is_yes(p->value);
461                 else if (strcasecmp(p->key, "reflect-ipv") == 0)
462                     c->server_config.reflect_ipv = is_yes(p->value);
463                 else {
464                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
465                     goto finish;
466                 }
467             }
468             
469         } else if (strcasecmp(g->name, "rlimits") == 0) {
470             AvahiIniFilePair *p;
471
472             for (p = g->pairs; p; p = p->pairs_next) {
473                 
474                 if (strcasecmp(p->key, "rlimit-as") == 0) {
475                     c->rlimit_as_set = 1;
476                     c->rlimit_as = atoi(p->value);
477                 } else if (strcasecmp(p->key, "rlimit-core") == 0) {
478                     c->rlimit_core_set = 1;
479                     c->rlimit_core = atoi(p->value);
480                 } else if (strcasecmp(p->key, "rlimit-data") == 0) {
481                     c->rlimit_data_set = 1;
482                     c->rlimit_data = atoi(p->value);
483                 } else if (strcasecmp(p->key, "rlimit-fsize") == 0) {
484                     c->rlimit_fsize_set = 1;
485                     c->rlimit_fsize = atoi(p->value);
486                 } else if (strcasecmp(p->key, "rlimit-nofile") == 0) {
487                     c->rlimit_nofile_set = 1;
488                     c->rlimit_nofile = atoi(p->value);
489                 } else if (strcasecmp(p->key, "rlimit-stack") == 0) {
490                     c->rlimit_stack_set = 1;
491                     c->rlimit_stack = atoi(p->value);
492 #ifdef RLIMIT_NPROC
493                 } else if (strcasecmp(p->key, "rlimit-nproc") == 0) {
494                     c->rlimit_nproc_set = 1;
495                     c->rlimit_nproc = atoi(p->value);
496 #endif
497                 } else {
498                     avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name);
499                     goto finish;
500                 }
501
502             }
503             
504         } else {
505             avahi_log_error("Invalid configuration file group \"%s\".\n", g->name);
506             goto finish;
507         }
508     }
509
510     r = 0;
511
512 finish:
513
514     if (f)
515         avahi_ini_file_free(f);
516     
517     return r;
518 }
519
520 static void log_function(AvahiLogLevel level, const char *txt) {
521
522     static const int log_level_map[] = {
523         LOG_ERR,
524         LOG_WARNING,
525         LOG_NOTICE,
526         LOG_INFO,
527         LOG_DEBUG
528     };
529     
530     assert(level < AVAHI_LOG_LEVEL_MAX);
531     assert(txt);
532
533     if (!config.debug && level == AVAHI_LOG_DEBUG)
534         return;
535
536     daemon_log(log_level_map[level], "%s", txt);
537 }
538
539 static void dump(const char *text, void* userdata) {
540     avahi_log_info("%s", text);
541 }
542
543 static void signal_callback(AvahiWatch *watch, int fd, AvahiWatchEvent event, void *userdata) {
544     int sig;
545     AvahiSimplePoll *simple_poll_api = userdata;
546     const AvahiPoll *poll_api;
547     
548     assert(watch);
549     assert(simple_poll_api);
550
551     poll_api = avahi_simple_poll_get(simple_poll_api);
552
553     if ((sig = daemon_signal_next()) <= 0) {
554         avahi_log_error("daemon_signal_next() failed");
555         poll_api->watch_free(watch);
556         return;
557     }
558
559     switch (sig) {
560         case SIGINT:
561         case SIGQUIT:
562         case SIGTERM:
563             avahi_log_info(
564                 "Got %s, quitting.",
565                 sig == SIGINT ? "SIGINT" :
566                 (sig == SIGQUIT ? "SIGQUIT" : "SIGTERM"));
567             avahi_simple_poll_quit(simple_poll_api);
568             break;
569
570         case SIGHUP:
571             avahi_log_info("Got SIGHUP, reloading.");
572             static_service_load();
573             static_service_add_to_server();
574
575             if (resolv_conf_entry_group)
576                 avahi_s_entry_group_reset(resolv_conf_entry_group);
577
578             load_resolv_conf(&config);
579
580             update_wide_area_servers();
581             
582             if (config.publish_resolv_conf && resolv_conf && resolv_conf[0])
583                 resolv_conf_entry_group = add_dns_servers(avahi_server, resolv_conf_entry_group, resolv_conf);
584
585             break;
586
587         case SIGUSR1:
588             avahi_log_info("Got SIGUSR1, dumping record data.");
589             avahi_server_dump(avahi_server, dump, NULL);
590             break;
591
592         default:
593             avahi_log_warn("Got spurious signal, ignoring.");
594             break;
595     }
596 }
597
598 static int run_server(DaemonConfig *c) {
599     int r = -1;
600     int error;
601     AvahiSimplePoll *simple_poll_api;
602     const AvahiPoll *poll_api;
603     AvahiWatch *sig_watch;
604
605     assert(c);
606
607     if (!(simple_poll_api = avahi_simple_poll_new())) {
608         avahi_log_error("Failed to create main loop object.");
609         goto finish;
610     }
611
612     poll_api = avahi_simple_poll_get(simple_poll_api);
613
614     if (daemon_signal_init(SIGINT, SIGQUIT, SIGHUP, SIGTERM, SIGUSR1, 0) < 0) {
615         avahi_log_error("Could not register signal handlers (%s).", strerror(errno));
616         goto finish;
617     }
618
619     if (!(sig_watch = poll_api->watch_new(poll_api, daemon_signal_fd(), AVAHI_WATCH_IN, signal_callback, simple_poll_api))) {
620         avahi_log_error( "Failed to create signal watcher");
621         goto finish;
622     }
623
624     if (simple_protocol_setup(poll_api) < 0)
625         goto finish;
626     if (c->enable_dbus) {
627 #ifdef HAVE_DBUS
628         if (dbus_protocol_setup(poll_api) < 0) {
629
630             if (c->fail_on_missing_dbus)
631                 goto finish;
632
633             avahi_log_warn("WARNING: Failed to contact D-BUS daemon, disabling D-BUS support.");
634             c->enable_dbus = 0;
635         }
636 #else
637         avahi_log_warn("WARNING: We are configured to enable D-BUS but it was not compiled in.");
638         c->enable_dbus = 0;
639 #endif
640     }
641     
642     load_resolv_conf(c);
643     static_service_load();
644
645     if (!(avahi_server = avahi_server_new(poll_api, &c->server_config, server_callback, c, &error))) {
646         avahi_log_error("Failed to create server: %s", avahi_strerror(error));
647         goto finish;
648     }
649
650     update_wide_area_servers();
651
652     if (c->daemonize)
653         daemon_retval_send(0);
654
655     for (;;) {
656         if ((r = avahi_simple_poll_iterate(simple_poll_api, -1)) < 0) {
657
658             /* We handle signals through an FD, so let's continue */
659             if (errno == EINTR)
660                 continue;
661             
662             avahi_log_error("poll(): %s", strerror(errno));
663             goto finish;
664         } else if (r > 0)
665             /* Quit */
666             break;
667     }
668     
669
670 finish:
671     
672     static_service_remove_from_server();
673     static_service_free_all();
674     remove_dns_server_entry_groups();
675     
676     simple_protocol_shutdown();
677
678 #ifdef ENABLE_DBUS
679     if (c->enable_dbus)
680         dbus_protocol_shutdown();
681 #endif
682
683     if (avahi_server)
684         avahi_server_free(avahi_server);
685
686     daemon_signal_done();
687
688     if (sig_watch)
689         poll_api->watch_free(sig_watch);
690
691     if (simple_poll_api)
692         avahi_simple_poll_free(simple_poll_api);
693
694     if (r != 0 && c->daemonize)
695         daemon_retval_send(1);
696     
697     return r;
698 }
699
700 #define set_env(key, value) putenv(avahi_strdup_printf("%s=%s", (key), (value)))
701
702 static int drop_root(void) {
703     struct passwd *pw;
704     struct group * gr;
705     int r;
706     
707     if (!(pw = getpwnam(AVAHI_USER))) {
708         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
709         return -1;
710     }
711
712     if (!(gr = getgrnam(AVAHI_GROUP))) {
713         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
714         return -1;
715     }
716
717     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);
718
719     if (initgroups(AVAHI_USER, gr->gr_gid) != 0) {
720         avahi_log_error("Failed to change group list: %s", strerror(errno));
721         return -1;
722     }
723
724 #if defined(HAVE_SETRESGID)
725     r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
726 #elif defined(HAVE_SETREGID)
727     r = setregid(gr->gr_gid, gr->gr_gid);
728 #else
729     if ((r = setgid(gr->gr_gid)) >= 0)
730         r = setegid(gr->gr_gid);
731 #endif
732
733     if (r < 0) {
734         avahi_log_error("Failed to change GID: %s", strerror(errno));
735         return -1;
736     }
737
738 #if defined(HAVE_SETRESUID)
739     r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
740 #elif defined(HAVE_SETREUID)
741     r = setreuid(pw->pw_uid, pw->pw_uid);
742 #else
743     if ((r = setuid(pw->pw_uid)) >= 0)
744         r = seteuid(pw->pw_uid);
745 #endif
746
747     if (r < 0) {
748         avahi_log_error("Failed to change UID: %s", strerror(errno));
749         return -1;
750     }
751
752     set_env("USER", pw->pw_name);
753     set_env("LOGNAME", pw->pw_name);
754     set_env("HOME", pw->pw_dir);
755     
756     avahi_log_info("Successfully dropped root privileges.");
757
758     return 0;
759 }
760
761 static const char* pid_file_proc(void) {
762     return AVAHI_DAEMON_RUNTIME_DIR"/pid";
763 }
764
765 static int make_runtime_dir(void) {
766     int r = -1;
767     mode_t u;
768     int reset_umask = 0;
769     struct passwd *pw;
770     struct group * gr;
771     struct stat st;
772
773     if (!(pw = getpwnam(AVAHI_USER))) {
774         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
775         goto fail;
776     }
777
778     if (!(gr = getgrnam(AVAHI_GROUP))) {
779         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
780         goto fail;
781     }
782
783     u = umask(0000);
784     reset_umask = 1;
785     
786     if (mkdir(AVAHI_DAEMON_RUNTIME_DIR, 0755) < 0 && errno != EEXIST) {
787         avahi_log_error("mkdir(\""AVAHI_DAEMON_RUNTIME_DIR"\"): %s", strerror(errno));
788         goto fail;
789     }
790     
791     chown(AVAHI_DAEMON_RUNTIME_DIR, pw->pw_uid, gr->gr_gid);
792
793     if (stat(AVAHI_DAEMON_RUNTIME_DIR, &st) < 0) {
794         avahi_log_error("stat(): %s\n", strerror(errno));
795         goto fail;
796     }
797
798     if (!S_ISDIR(st.st_mode) || st.st_uid != pw->pw_uid || st.st_gid != gr->gr_gid) {
799         avahi_log_error("Failed to create runtime directory "AVAHI_DAEMON_RUNTIME_DIR".");
800         goto fail;
801     }
802
803     r = 0;
804
805 fail:
806     if (reset_umask)
807         umask(u);
808     return r;
809 }
810
811 static void set_one_rlimit(int resource, rlim_t limit, const char *name) {
812     struct rlimit rl;
813     rl.rlim_cur = rl.rlim_max = limit;
814
815     if (setrlimit(resource, &rl) < 0)
816         avahi_log_warn("setrlimit(%s, {%u, %u}) failed: %s", name, (unsigned) limit, (unsigned) limit, strerror(errno));
817 }
818
819 static void enforce_rlimits(void) {
820
821     if (config.rlimit_as_set)
822         set_one_rlimit(RLIMIT_AS, config.rlimit_as, "RLIMIT_AS");
823     if (config.rlimit_core_set)
824         set_one_rlimit(RLIMIT_CORE, config.rlimit_core, "RLIMIT_CORE");
825     if (config.rlimit_data_set)
826         set_one_rlimit(RLIMIT_DATA, config.rlimit_data, "RLIMIT_DATA");
827     if (config.rlimit_fsize_set)
828         set_one_rlimit(RLIMIT_FSIZE, config.rlimit_fsize, "RLIMIT_FSIZE");
829     if (config.rlimit_nofile_set)
830         set_one_rlimit(RLIMIT_NOFILE, config.rlimit_nofile, "RLIMIT_NOFILE");
831     if (config.rlimit_stack_set)
832         set_one_rlimit(RLIMIT_STACK, config.rlimit_stack, "RLIMIT_STACK");
833 #ifdef RLIMIT_NPROC
834     if (config.rlimit_nproc_set)
835         set_one_rlimit(RLIMIT_NPROC, config.rlimit_nproc, "RLIMIT_NPROC");
836 #endif
837
838 #ifdef RLIMIT_MEMLOCK
839     /* We don't need locked memory */
840     set_one_rlimit(RLIMIT_MEMLOCK, 0, "RLIMIT_MEMLOCK");
841 #endif
842 }
843
844 #define RANDOM_DEVICE "/dev/urandom"
845
846 static void init_rand_seed(void) {
847     int fd;
848     unsigned seed = 0;
849
850     /* Try to initialize seed from /dev/urandom, to make it a little
851      * less predictable, and to make sure that multiple machines
852      * booted at the same time choose different random seeds.  */
853     if ((fd = open(RANDOM_DEVICE, O_RDONLY)) >= 0) {
854         read(fd, &seed, sizeof(seed));
855         close(fd);
856     }
857
858     /* If the initialization failed by some reason, we add the time to the seed*/
859     seed |= (unsigned) time(NULL);
860
861     srand(seed);
862 }
863
864 int main(int argc, char *argv[]) {
865     int r = 255;
866     const char *argv0;
867     int wrote_pid_file = 0;
868
869     avahi_set_log_function(log_function);
870
871     init_rand_seed();
872     
873     avahi_server_config_init(&config.server_config);
874     config.command = DAEMON_RUN;
875     config.daemonize = 0;
876     config.config_file = NULL;
877 #ifdef HAVE_DBUS
878     config.enable_dbus = 1;
879     config.fail_on_missing_dbus = 1;
880 #else
881     config.enable_dbus = 0;
882     config.fail_on_missing_dbus = 0;
883 #endif
884     config.drop_root = 1;
885     config.publish_dns_servers = NULL;
886     config.publish_resolv_conf = 0;
887     config.use_syslog = 0;
888     config.no_rlimits = 0;
889     config.debug = 0;
890     
891     config.rlimit_as_set = 0;
892     config.rlimit_core_set = 0;
893     config.rlimit_data_set = 0;
894     config.rlimit_fsize_set = 0;
895     config.rlimit_nofile_set = 0;
896     config.rlimit_stack_set = 0;
897 #ifdef RLIMIT_NPROC
898     config.rlimit_nproc_set = 0;
899 #endif
900     
901     if ((argv0 = strrchr(argv[0], '/')))
902         argv0++;
903     else
904         argv0 = argv[0];
905
906     daemon_pid_file_ident = (const char *) argv0;
907     daemon_log_ident = (char*) argv0;
908     daemon_pid_file_proc = pid_file_proc;
909     
910     if (parse_command_line(&config, argc, argv) < 0)
911         goto finish;
912
913     if (config.command == DAEMON_HELP) {
914         help(stdout, argv0);
915         r = 0;
916     } else if (config.command == DAEMON_VERSION) {
917         printf("%s "PACKAGE_VERSION"\n", argv0);
918         r = 0;
919     } else if (config.command == DAEMON_KILL) {
920         if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
921             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
922             goto finish;
923         }
924
925         r = 0;
926
927     } else if (config.command == DAEMON_RELOAD) {
928         if (daemon_pid_file_kill(SIGHUP) < 0) {
929             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
930             goto finish;
931         }
932
933         r = 0;
934         
935     } else if (config.command == DAEMON_CHECK)
936         r = (daemon_pid_file_is_running() >= 0) ? 0 : 1;
937     else if (config.command == DAEMON_RUN) {
938         pid_t pid;
939
940         if (getuid() != 0 && config.drop_root) {
941             avahi_log_error("This program is intended to be run as root.");
942             goto finish;
943         }
944         
945         if ((pid = daemon_pid_file_is_running()) >= 0) {
946             avahi_log_error("Daemon already running on PID %u", pid);
947             goto finish;
948         }
949
950         if (load_config_file(&config) < 0)
951             goto finish;
952         
953         if (config.daemonize) {
954             daemon_retval_init();
955             
956             if ((pid = daemon_fork()) < 0)
957                 goto finish;
958             else if (pid != 0) {
959                 int ret;
960                 /** Parent **/
961
962                 if ((ret = daemon_retval_wait(20)) < 0) {
963                     avahi_log_error("Could not recieve return value from daemon process.");
964                     goto finish;
965                 }
966
967                 r = ret;
968                 goto finish;
969             }
970
971             /* Child */
972         }
973
974         if (config.use_syslog || config.daemonize)
975             daemon_log_use = DAEMON_LOG_SYSLOG;
976
977         if (make_runtime_dir() < 0)
978             goto finish;
979
980         if (config.drop_root) {
981             if (drop_root() < 0)
982                 goto finish;
983         }
984
985         if (daemon_pid_file_create() < 0) {
986             avahi_log_error("Failed to create PID file: %s", strerror(errno));
987
988             if (config.daemonize)
989                 daemon_retval_send(1);
990             goto finish;
991         } else
992             wrote_pid_file = 1;
993
994         if (!config.no_rlimits)
995             enforce_rlimits();
996
997         chdir("/");
998         
999         avahi_log_info("%s "PACKAGE_VERSION" starting up.", argv0);
1000         
1001         if (run_server(&config) == 0)
1002             r = 0;
1003     }
1004         
1005 finish:
1006
1007     if (config.daemonize)
1008         daemon_retval_done();
1009
1010     avahi_server_config_free(&config.server_config);
1011     avahi_free(config.config_file);
1012     avahi_strfreev(config.publish_dns_servers);
1013     avahi_strfreev(resolv_conf);
1014
1015     if (wrote_pid_file)
1016         daemon_pid_file_remove();
1017     
1018     return r;
1019 }