]> git.meshlink.io Git - catta/blob - avahi-daemon/main.c
* drop priviliges
[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
35 #include <libdaemon/dfork.h>
36 #include <libdaemon/dsignal.h>
37 #include <libdaemon/dlog.h>
38 #include <libdaemon/dpid.h>
39
40 #include <avahi-core/core.h>
41 #include <avahi-core/log.h>
42
43 #include "main.h"
44 #include "simple-protocol.h"
45 #include "dbus-protocol.h"
46 #include "static-services.h"
47
48 AvahiServer *avahi_server = NULL;
49
50 typedef enum {
51     DAEMON_RUN,
52     DAEMON_KILL,
53     DAEMON_VERSION,
54     DAEMON_HELP,
55     DAEMON_RELOAD
56 } DaemonCommand;
57
58 typedef struct {
59     AvahiServerConfig server_config;
60     DaemonCommand command;
61     gboolean daemonize;
62     gchar *config_file;
63     gboolean enable_dbus;
64     gboolean drop_root;
65 } DaemonConfig;
66
67 static void server_callback(AvahiServer *s, AvahiServerState state, gpointer userdata) {
68     g_assert(s);
69
70     if (state == AVAHI_SERVER_RUNNING) {
71         avahi_log_info("Server startup complete.  Host name is <%s>", avahi_server_get_host_name_fqdn(s));
72         static_service_add_to_server();
73     } else if (state == AVAHI_SERVER_COLLISION) {
74         gchar *n;
75
76         static_service_remove_from_server();
77         
78         n = avahi_alternative_host_name(avahi_server_get_host_name(s));
79         avahi_log_warn("Host name conflict, retrying with <%s>", n);
80         avahi_server_set_host_name(s, n);
81         g_free(n);
82     }
83 }
84
85 static void help(FILE *f, const gchar *argv0) {
86     fprintf(f,
87             "%s [options]\n"
88             "    -h --help        Show this help\n"
89             "    -D --daemonize   Daemonize after startup\n"
90             "    -k --kill        Kill a running daemon\n"
91             "    -r --reload      Request a running daemon to reload static services\n"
92             "    -V --version     Show version\n"
93             "    -f --file=FILE   Load the specified configuration file instead of\n"
94             "                     "AVAHI_CONFIG_FILE"\n",
95             argv0);
96 }
97
98 static gint parse_command_line(DaemonConfig *config, int argc, char *argv[]) {
99     gint c;
100     
101     static const struct option const long_options[] = {
102         { "help",      no_argument,       NULL, 'h' },
103         { "daemonize", no_argument,       NULL, 'D' },
104         { "kill",      no_argument,       NULL, 'k' },
105         { "version",   no_argument,       NULL, 'V' },
106         { "file",      required_argument, NULL, 'f' },
107         { "reload",    no_argument,       NULL, 'r' },
108     };
109
110     g_assert(config);
111
112     opterr = 0;
113     while ((c = getopt_long(argc, argv, "hDkVf:r", long_options, NULL)) >= 0) {
114
115         switch(c) {
116             case 'h':
117                 config->command = DAEMON_HELP;
118                 break;
119             case 'D':
120                 config->daemonize = TRUE;
121                 break;
122             case 'k':
123                 config->command = DAEMON_KILL;
124                 break;
125             case 'V':
126                 config->command = DAEMON_VERSION;
127                 break;
128             case 'f':
129                 g_free(config->config_file);
130                 config->config_file = g_strdup(optarg);
131                 break;
132             case 'r':
133                 config->command = DAEMON_RELOAD;
134                 break;
135             default:
136                 fprintf(stderr, "Invalid command line argument: %c\n", c);
137                 return -1;
138         }
139     }
140
141     if (optind < argc) {
142         fprintf(stderr, "Too many arguments\n");
143         return -1;
144     }
145         
146     return 0;
147 }
148
149 static gboolean is_yes(const gchar *s) {
150     g_assert(s);
151     
152     return *s == 'y' || *s == 'Y';
153 }
154
155 static gint load_config_file(DaemonConfig *config) {
156     int r = -1;
157     GKeyFile *f = NULL;
158     GError *err = NULL;
159     gchar **groups = NULL, **g, **keys = NULL, *v = NULL;
160
161     g_assert(config);
162     
163     f = g_key_file_new();
164     
165     if (!g_key_file_load_from_file(f, config->config_file ? config->config_file : AVAHI_CONFIG_FILE, G_KEY_FILE_NONE, &err)) {
166         fprintf(stderr, "Unable to read config file: %s\n", err->message);
167         goto finish;
168     }
169
170     groups = g_key_file_get_groups(f, NULL);
171
172     for (g = groups; *g; g++) {
173         if (g_strcasecmp(*g, "server") == 0) {
174             gchar **k;
175             
176             keys = g_key_file_get_keys(f, *g, NULL, NULL);
177
178             for (k = keys; *k; k++) {
179
180                 v = g_key_file_get_value(f, *g, *k, NULL);
181                 
182                 if (g_strcasecmp(*k, "host-name") == 0) {
183                     g_free(config->server_config.host_name);
184                     config->server_config.host_name = v;
185                     v = NULL;
186                 } else if (g_strcasecmp(*k, "domain-name") == 0) {
187                     g_free(config->server_config.domain_name);
188                     config->server_config.domain_name = v;
189                     v = NULL;
190                 } else if (g_strcasecmp(*k, "use-ipv4") == 0)
191                     config->server_config.use_ipv4 = is_yes(v);
192                 else if (g_strcasecmp(*k, "use-ipv6") == 0)
193                     config->server_config.use_ipv6 = is_yes(v);
194                 else if (g_strcasecmp(*k, "check-response-ttl") == 0)
195                     config->server_config.check_response_ttl = is_yes(v);
196                 else if (g_strcasecmp(*k, "use-iff-running") == 0)
197                     config->server_config.use_iff_running = is_yes(v);
198                 else if (g_strcasecmp(*k, "enable-dbus") == 0)
199                     config->enable_dbus = is_yes(v);
200                 else if (g_strcasecmp(*k, "drop-root") == 0)
201                     config->drop_root = is_yes(v);
202                 else {
203                     fprintf(stderr, "Invalid configuration key \"%s\" in group \"%s\"\n", *k, *g);
204                     goto finish;
205                 }
206
207                 g_free(v);
208                 v = NULL;
209             }
210         
211             g_strfreev(keys);
212             keys = NULL;
213             
214         } else if (g_strcasecmp(*g, "publish") == 0) {
215             gchar **k;
216             
217             keys = g_key_file_get_keys(f, *g, NULL, NULL);
218
219             for (k = keys; *k; k++) {
220
221                 v = g_key_file_get_string(f, *g, *k, NULL);
222                 
223                 if (g_strcasecmp(*k, "publish-addresses") == 0)
224                     config->server_config.publish_addresses = is_yes(v);
225                 else if (g_strcasecmp(*k, "publish-hinfo") == 0)
226                     config->server_config.publish_hinfo = is_yes(v);
227                 else if (g_strcasecmp(*k, "publish-workstation") == 0)
228                     config->server_config.publish_workstation = is_yes(v);
229                 else if (g_strcasecmp(*k, "publish-domain") == 0)
230                     config->server_config.publish_domain = is_yes(v);
231                 else {
232                     fprintf(stderr, "Invalid configuration key \"%s\" in group \"%s\"\n", *k, *g);
233                     goto finish;
234                 }
235
236                 g_free(v);
237                 v = NULL;
238             }
239
240             g_strfreev(keys);
241             keys = NULL;
242
243         } else if (g_strcasecmp(*g, "reflector") == 0) {
244             gchar **k;
245             
246             keys = g_key_file_get_keys(f, *g, NULL, NULL);
247
248             for (k = keys; *k; k++) {
249
250                 v = g_key_file_get_string(f, *g, *k, NULL);
251                 
252                 if (g_strcasecmp(*k, "enable-reflector") == 0)
253                     config->server_config.enable_reflector = is_yes(v);
254                 else if (g_strcasecmp(*k, "reflect-ipv") == 0)
255                     config->server_config.reflect_ipv = is_yes(v);
256                 else {
257                     fprintf(stderr, "Invalid configuration key \"%s\" in group \"%s\"\n", *k, *g);
258                     goto finish;
259                 }
260
261                 g_free(v);
262                 v = NULL;
263             }
264     
265             g_strfreev(keys);
266             keys = NULL;
267             
268         } else {
269             fprintf(stderr, "Invalid configuration file group \"%s\".\n", *g);
270             goto finish;
271         }
272     }
273
274     r = 0;
275
276 finish:
277
278     g_strfreev(groups);
279     g_strfreev(keys);
280     g_free(v);
281
282     if (err)
283         g_error_free (err);
284
285     if (f)
286         g_key_file_free(f);
287     
288     return r;
289 }
290
291 static void log_function(AvahiLogLevel level, const gchar *txt) {
292
293     static const int const log_level_map[] = {
294         LOG_ERR,
295         LOG_WARNING,
296         LOG_NOTICE,
297         LOG_INFO,
298         LOG_DEBUG
299     };
300     
301     g_assert(level < AVAHI_LOG_LEVEL_MAX);
302     g_assert(txt);
303
304     daemon_log(log_level_map[level], "%s", txt);
305 }
306
307 static gboolean signal_callback(GIOChannel *source, GIOCondition condition, gpointer data) {
308     gint sig;
309     g_assert(source);
310
311     if ((sig = daemon_signal_next()) <= 0) {
312         avahi_log_error("daemon_signal_next() failed");
313         return FALSE;
314     }
315
316     switch (sig) {
317         case SIGINT:
318         case SIGQUIT:
319         case SIGTERM:
320             avahi_log_info(
321                 "Got %s, quitting.",
322                 sig == SIGINT ? "SIGINT" :
323                 (sig == SIGQUIT ? "SIGQUIT" : "SIGTERM"));
324             g_main_loop_quit((GMainLoop*) data);
325             break;
326
327         case SIGHUP:
328             avahi_log_info("Got SIGHUP, reloading.");
329             static_service_load();
330             static_service_add_to_server();
331             break;
332
333         default:
334             avahi_log_warn("Got spurious signal, ignoring.");
335             break;
336     }
337
338     return TRUE;
339 }
340
341 static gint run_server(DaemonConfig *config) {
342     GMainLoop *loop = NULL;
343     gint r = -1;
344     GIOChannel *io = NULL;
345     guint watch_id = (guint) -1;
346
347     g_assert(config);
348     
349     loop = g_main_loop_new(NULL, FALSE);
350
351     if (daemon_signal_init(SIGINT, SIGQUIT, SIGHUP, SIGTERM, 0) < 0) {
352         avahi_log_error("Could not register signal handlers (%s).", strerror(errno));
353         goto finish;
354     }
355
356     if (!(io = g_io_channel_unix_new(daemon_signal_fd()))) {
357         avahi_log_error( "Failed to create signal io channel.");
358         goto finish;
359     }
360
361     g_io_channel_set_close_on_unref(io, FALSE);
362     g_io_add_watch(io, G_IO_IN, signal_callback, loop);
363     
364     if (simple_protocol_setup(NULL) < 0)
365         goto finish;
366     
367 #ifdef ENABLE_DBUS
368     if (config->enable_dbus)
369         if (dbus_protocol_setup(loop) < 0)
370             goto finish;
371 #endif
372     
373     if (!(avahi_server = avahi_server_new(NULL, &config->server_config, server_callback, NULL)))
374         goto finish;
375     
376     static_service_load();
377
378     if (config->daemonize) {
379         daemon_retval_send(0);
380         r = 0;
381     }
382
383     g_main_loop_run(loop);
384
385 finish:
386     
387     static_service_remove_from_server();
388     static_service_free_all();
389     
390     simple_protocol_shutdown();
391
392 #ifdef ENABLE_DBUS
393     if (config->enable_dbus)
394         dbus_protocol_shutdown();
395 #endif
396
397     if (avahi_server)
398         avahi_server_free(avahi_server);
399
400     daemon_signal_done();
401
402     if (watch_id != (guint) -1)
403         g_source_remove(watch_id);
404     
405     if (io)
406         g_io_channel_unref(io);
407
408         
409     if (loop)
410         g_main_loop_unref(loop);
411
412     if (r != 0 && config->daemonize)
413         daemon_retval_send(1);
414     
415     return r;
416 }
417
418 static gint drop_root(void) {
419     struct passwd *pw;
420     struct group * gr;
421     gint r;
422     
423     if (!(pw = getpwnam(AVAHI_USER))) {
424         avahi_log_error( "Failed to find user '"AVAHI_USER"'.");
425         return -1;
426     }
427
428     if (!(gr = getgrnam(AVAHI_GROUP))) {
429         avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
430         return -1;
431     }
432
433     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);
434
435     if (initgroups(AVAHI_USER, gr->gr_gid) != 0) {
436         avahi_log_error("Failed to change group list: %s", strerror(errno));
437         return -1;
438     }
439
440 #if defined(HAVE_SETRESGID)
441     r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
442 #elif defined(HAVE_SETREGID)
443     r = setregid(gr->gr_gid, gr->gr_gid);
444 #else
445     if ((r = setgid(gr->gr_gid)) >= 0)
446         r = setegid(gr->gr_gid);
447 #endif
448
449     if (r < 0) {
450         avahi_log_error("Failed to change GID: %s", strerror(errno));
451         return -1;
452     }
453
454 #if defined(HAVE_SETRESUID)
455     r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
456 #elif defined(HAVE_SETREUID)
457     r = setreuid(pw->pw_uid, pw->pw_uid);
458 #else
459     if ((r = setuid(pw->pw_uid)) >= 0)
460         r = seteuid(pw->pw_uid);
461 #endif
462
463     if (r < 0) {
464         avahi_log_error("Failed to change UID: %s", strerror(errno));
465         return -1;
466     }
467
468     g_setenv("USER", pw->pw_name, 1);
469     g_setenv("LOGNAME", pw->pw_name, 1);
470     g_setenv("HOME", pw->pw_dir, 1);
471     
472     avahi_log_info("Successfully dropped root privileges.");
473
474     return 0;
475 }
476
477 int main(int argc, char *argv[]) {
478     gint r = 255;
479     DaemonConfig config;
480     const gchar *argv0;
481     gboolean wrote_pid_file = FALSE;
482
483     avahi_set_log_function(log_function);
484     
485     avahi_server_config_init(&config.server_config);
486     config.command = DAEMON_RUN;
487     config.daemonize = FALSE;
488     config.config_file = NULL;
489     config.enable_dbus = TRUE;
490     config.drop_root = TRUE;
491
492     if ((argv0 = strrchr(argv[0], '/')))
493         argv0++;
494     else
495         argv0 = argv[0];
496
497     daemon_pid_file_ident = daemon_log_ident = (char *) argv0;
498     
499     if (parse_command_line(&config, argc, argv) < 0)
500         goto finish;
501
502     if (config.command == DAEMON_HELP) {
503         help(stdout, argv0);
504         r = 0;
505     } else if (config.command == DAEMON_VERSION) {
506         printf("%s "PACKAGE_VERSION"\n", argv0);
507
508     } else if (config.command == DAEMON_KILL) {
509         if (daemon_pid_file_kill_wait(SIGTERM, 5) < 0) {
510             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
511             goto finish;
512         }
513
514         r = 0;
515         
516     } else if (config.command == DAEMON_RELOAD) {
517         if (daemon_pid_file_kill(SIGHUP) < 0) {
518             avahi_log_warn("Failed to kill daemon: %s", strerror(errno));
519             goto finish;
520         }
521
522         r = 0;
523         
524     } else if (config.command == DAEMON_RUN) {
525         pid_t pid;
526
527         if (getuid() != 0) {
528             avahi_log_error("This program is intended to be run as root.");
529             goto finish;
530         }
531         
532         if ((pid = daemon_pid_file_is_running()) >= 0) {
533             avahi_log_error("Daemon already running on PID %u", pid);
534             goto finish;
535         }
536
537         if (load_config_file(&config) < 0)
538             goto finish;
539         
540         if (config.daemonize) {
541
542             daemon_retval_init();
543             
544             if ((pid = daemon_fork()) < 0)
545                 goto finish;
546             else if (pid != 0) {
547                 int ret;
548                 /** Parent **/
549
550                 if ((ret = daemon_retval_wait(20)) < 0) {
551                     avahi_log_error("Could not recieve return value from daemon process.");
552                     goto finish;
553                 }
554
555                 r = ret;
556                 goto finish;
557             }
558
559             /* Child */
560         }
561
562         chdir("/");
563
564         if (daemon_pid_file_create() < 0) {
565             avahi_log_error("Failed to create PID file: %s", strerror(errno));
566
567             if (config.daemonize)
568                 daemon_retval_send(1);
569             goto finish;
570         } else
571             wrote_pid_file = TRUE;
572
573         if (config.drop_root) {
574             if (drop_root() < 0)
575                 goto finish;
576         }
577
578         if (run_server(&config) == 0)
579             r = 0;
580     }
581         
582 finish:
583
584     if (config.daemonize)
585         daemon_retval_done();
586
587     avahi_server_config_free(&config.server_config);
588     g_free(config.config_file);
589
590     if (wrote_pid_file)
591         daemon_pid_file_remove();
592     
593     return r;
594 }