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