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