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