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