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