Add copyright notices to all relevant files. (based on svn log)
[profile/ivi/pulseaudio.git] / src / daemon / main.c
1 /* $Id$ */
2
3 /***
4   This file is part of PulseAudio.
5
6   Copyright 2004-2006 Lennart Poettering
7   Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
8
9   PulseAudio is free software; you can redistribute it and/or modify
10   it under the terms of the GNU Lesser General Public License as published
11   by the Free Software Foundation; either version 2 of the License,
12   or (at your option) any later version.
13
14   PulseAudio is distributed in the hope that it will be useful, but
15   WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17   General Public License for more details.
18
19   You should have received a copy of the GNU Lesser General Public License
20   along with PulseAudio; if not, write to the Free Software
21   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
22   USA.
23 ***/
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #include <unistd.h>
30 #include <errno.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <signal.h>
35 #include <stddef.h>
36 #include <assert.h>
37 #include <ltdl.h>
38 #include <limits.h>
39 #include <fcntl.h>
40 #include <unistd.h>
41 #include <locale.h>
42 #include <sys/types.h>
43
44 #include <liboil/liboil.h>
45
46 #ifdef HAVE_SYS_IOCTL_H
47 #include <sys/ioctl.h>
48 #endif
49
50 #ifdef HAVE_PWD_H
51 #include <pwd.h>
52 #endif
53 #ifdef HAVE_GRP_H
54 #include <grp.h>
55 #endif
56
57 #ifdef HAVE_LIBWRAP
58 #include <syslog.h>
59 #include <tcpd.h>
60 #endif
61
62 #include "../pulsecore/winsock.h"
63
64 #include <pulse/mainloop.h>
65 #include <pulse/mainloop-signal.h>
66 #include <pulse/timeval.h>
67 #include <pulse/xmalloc.h>
68
69 #include <pulsecore/core-error.h>
70 #include <pulsecore/core.h>
71 #include <pulsecore/memblock.h>
72 #include <pulsecore/module.h>
73 #include <pulsecore/cli-command.h>
74 #include <pulsecore/log.h>
75 #include <pulsecore/core-util.h>
76 #include <pulsecore/sioman.h>
77 #include <pulsecore/cli-text.h>
78 #include <pulsecore/pid.h>
79 #include <pulsecore/namereg.h>
80 #include <pulsecore/random.h>
81
82 #include "cmdline.h"
83 #include "cpulimit.h"
84 #include "daemon-conf.h"
85 #include "dumpmodules.h"
86 #include "caps.h"
87
88 #ifdef HAVE_LIBWRAP
89 /* Only one instance of these variables */
90 int allow_severity = LOG_INFO;
91 int deny_severity = LOG_WARNING;
92 #endif
93
94 #ifdef HAVE_OSS
95 /* padsp looks for this symbol in the running process and disables
96  * itself if it finds it and it is set to 7 (which is actually a bit
97  * mask). For details see padsp. */
98 int __padsp_disabled__ = 7;
99 #endif
100
101 #ifdef OS_IS_WIN32
102
103 static void message_cb(pa_mainloop_api*a, pa_time_event*e, PA_GCC_UNUSED const struct timeval *tv, void *userdata) {
104     MSG msg;
105     struct timeval tvnext;
106
107     while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
108         if (msg.message == WM_QUIT)
109             raise(SIGTERM);
110         else {
111             TranslateMessage(&msg);
112             DispatchMessage(&msg);
113         }
114     }
115
116     pa_timeval_add(pa_gettimeofday(&tvnext), 100000);
117     a->time_restart(e, &tvnext);
118 }
119
120 #endif
121
122 static void signal_callback(pa_mainloop_api*m, PA_GCC_UNUSED pa_signal_event *e, int sig, void *userdata) {
123     pa_log_info("Got signal %s.", pa_strsignal(sig));
124
125     switch (sig) {
126 #ifdef SIGUSR1
127         case SIGUSR1:
128             pa_module_load(userdata, "module-cli", NULL);
129             break;
130 #endif
131
132 #ifdef SIGUSR2
133         case SIGUSR2:
134             pa_module_load(userdata, "module-cli-protocol-unix", NULL);
135             break;
136 #endif
137
138 #ifdef SIGHUP
139         case SIGHUP: {
140             char *c = pa_full_status_string(userdata);
141             pa_log_notice("%s", c);
142             pa_xfree(c);
143             return;
144         }
145 #endif
146
147         case SIGINT:
148         case SIGTERM:
149         default:
150             pa_log_info("Exiting.");
151             m->quit(m, 1);
152             break;
153     }
154 }
155
156 static void close_pipe(int p[2]) {
157     if (p[0] != -1)
158         close(p[0]);
159     if (p[1] != -1)
160         close(p[1]);
161     p[0] = p[1] = -1;
162 }
163
164 #define set_env(key, value) putenv(pa_sprintf_malloc("%s=%s", (key), (value)))
165
166 #if defined(HAVE_PWD_H) && defined(HAVE_GRP_H)
167
168 static int change_user(void) {
169     struct passwd *pw;
170     struct group * gr;
171     int r;
172
173     /* This function is called only in system-wide mode. It creates a
174      * runtime dir in /var/run/ with proper UID/GID and drops privs
175      * afterwards. */
176
177     if (!(pw = getpwnam(PA_SYSTEM_USER))) {
178         pa_log("Failed to find user '%s'.", PA_SYSTEM_USER);
179         return -1;
180     }
181
182     if (!(gr = getgrnam(PA_SYSTEM_GROUP))) {
183         pa_log("Failed to find group '%s'.", PA_SYSTEM_GROUP);
184         return -1;
185     }
186
187     pa_log_info("Found user '%s' (UID %lu) and group '%s' (GID %lu).",
188                 PA_SYSTEM_USER, (unsigned long) pw->pw_uid,
189                 PA_SYSTEM_GROUP, (unsigned long) gr->gr_gid);
190
191     if (pw->pw_gid != gr->gr_gid) {
192         pa_log("GID of user '%s' and of group '%s' don't match.", PA_SYSTEM_USER, PA_SYSTEM_GROUP);
193         return -1;
194     }
195
196     if (strcmp(pw->pw_dir, PA_SYSTEM_RUNTIME_PATH) != 0)
197         pa_log_warn("Warning: home directory of user '%s' is not '%s', ignoring.", PA_SYSTEM_USER, PA_SYSTEM_RUNTIME_PATH);
198
199     if (pa_make_secure_dir(PA_SYSTEM_RUNTIME_PATH, 0755, pw->pw_uid, gr->gr_gid) < 0) {
200         pa_log("Failed to create '%s': %s", PA_SYSTEM_RUNTIME_PATH, pa_cstrerror(errno));
201         return -1;
202     }
203
204     if (initgroups(PA_SYSTEM_USER, gr->gr_gid) != 0) {
205         pa_log("Failed to change group list: %s", pa_cstrerror(errno));
206         return -1;
207     }
208
209 #if defined(HAVE_SETRESGID)
210     r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
211 #elif defined(HAVE_SETEGID)
212     if ((r = setgid(gr->gr_gid)) >= 0)
213         r = setegid(gr->gr_gid);
214 #elif defined(HAVE_SETREGID)
215     r = setregid(gr->gr_gid, gr->gr_gid);
216 #else
217 #error "No API to drop priviliges"
218 #endif
219
220     if (r < 0) {
221         pa_log("Failed to change GID: %s", pa_cstrerror(errno));
222         return -1;
223     }
224
225 #if defined(HAVE_SETRESUID)
226     r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
227 #elif defined(HAVE_SETEUID)
228     if ((r = setuid(pw->pw_uid)) >= 0)
229         r = seteuid(pw->pw_uid);
230 #elif defined(HAVE_SETREUID)
231     r = setreuid(pw->pw_uid, pw->pw_uid);
232 #else
233 #error "No API to drop priviliges"
234 #endif
235
236     if (r < 0) {
237         pa_log("Failed to change UID: %s", pa_cstrerror(errno));
238         return -1;
239     }
240
241     set_env("USER", PA_SYSTEM_USER);
242     set_env("LOGNAME", PA_SYSTEM_GROUP);
243     set_env("HOME", PA_SYSTEM_RUNTIME_PATH);
244
245     /* Relevant for pa_runtime_path() */
246     set_env("PULSE_RUNTIME_PATH", PA_SYSTEM_RUNTIME_PATH);
247     set_env("PULSE_CONFIG_PATH", PA_SYSTEM_RUNTIME_PATH);
248
249     pa_log_info("Successfully dropped root privileges.");
250
251     return 0;
252 }
253
254 #else /* HAVE_PWD_H && HAVE_GRP_H */
255
256 static int change_user(void) {
257     pa_log("System wide mode unsupported on this platform.");
258     return -1;
259 }
260
261 #endif /* HAVE_PWD_H && HAVE_GRP_H */
262
263 static int create_runtime_dir(void) {
264     char fn[PATH_MAX];
265
266     pa_runtime_path(NULL, fn, sizeof(fn));
267
268     /* This function is called only when the daemon is started in
269      * per-user mode. We create the runtime directory somewhere in
270      * /tmp/ with the current UID/GID */
271
272     if (pa_make_secure_dir(fn, 0700, (uid_t)-1, (gid_t)-1) < 0) {
273         pa_log("Failed to create '%s': %s", fn, pa_cstrerror(errno));
274         return -1;
275     }
276
277     return 0;
278 }
279
280 #ifdef HAVE_SYS_RESOURCE_H
281
282 static void set_one_rlimit(const pa_rlimit *r, int resource, const char *name) {
283     struct rlimit rl;
284     assert(r);
285
286     if (!r->is_set)
287         return;
288
289     rl.rlim_cur = rl.rlim_max = r->value;
290
291     if (setrlimit(resource, &rl) < 0)
292         pa_log_warn("setrlimit(%s, (%u, %u)) failed: %s", name, (unsigned) r->value, (unsigned) r->value, pa_cstrerror(errno));
293 }
294
295 static void set_all_rlimits(const pa_daemon_conf *conf) {
296     set_one_rlimit(&conf->rlimit_as, RLIMIT_AS, "RLIMIT_AS");
297     set_one_rlimit(&conf->rlimit_core, RLIMIT_CORE, "RLIMIT_CORE");
298     set_one_rlimit(&conf->rlimit_data, RLIMIT_DATA, "RLIMIT_DATA");
299     set_one_rlimit(&conf->rlimit_fsize, RLIMIT_FSIZE, "RLIMIT_FSIZE");
300     set_one_rlimit(&conf->rlimit_nofile, RLIMIT_NOFILE, "RLIMIT_NOFILE");
301     set_one_rlimit(&conf->rlimit_stack, RLIMIT_STACK, "RLIMIT_STACK");
302 #ifdef RLIMIT_NPROC
303     set_one_rlimit(&conf->rlimit_nproc, RLIMIT_NPROC, "RLIMIT_NPROC");
304 #endif
305 #ifdef RLIMIT_MEMLOCK
306     set_one_rlimit(&conf->rlimit_memlock, RLIMIT_MEMLOCK, "RLIMIT_MEMLOCK");
307 #endif
308 }
309 #endif
310
311 int main(int argc, char *argv[]) {
312     pa_core *c = NULL;
313     pa_strbuf *buf = NULL;
314     pa_daemon_conf *conf = NULL;
315     pa_mainloop *mainloop = NULL;
316
317     char *s;
318     int r, retval = 1, d = 0;
319     int daemon_pipe[2] = { -1, -1 };
320     int suid_root, real_root;
321     int valid_pid_file = 0;
322
323 #ifdef HAVE_GETUID
324     gid_t gid = (gid_t) -1;
325 #endif
326
327 #ifdef OS_IS_WIN32
328     pa_time_event *timer;
329     struct timeval tv;
330 #endif
331
332     setlocale(LC_ALL, "");
333
334     pa_limit_caps();
335
336 #ifdef HAVE_GETUID
337     real_root = getuid() == 0;
338     suid_root = !real_root && geteuid() == 0;
339
340     if (suid_root && (pa_own_uid_in_group(PA_REALTIME_GROUP, &gid) <= 0 || gid >= 1000)) {
341         pa_log_warn("WARNING: called SUID root, but not in group '"PA_REALTIME_GROUP"'.");
342         pa_drop_root();
343     }
344 #else
345     real_root = 0;
346     suid_root = 0;
347 #endif
348
349     LTDL_SET_PRELOADED_SYMBOLS();
350
351     r = lt_dlinit();
352     assert(r == 0);
353
354 #ifdef OS_IS_WIN32
355     {
356         WSADATA data;
357         WSAStartup(MAKEWORD(2, 0), &data);
358     }
359 #endif
360
361     pa_random_seed();
362
363     pa_log_set_ident("pulseaudio");
364
365     conf = pa_daemon_conf_new();
366
367     if (pa_daemon_conf_load(conf, NULL) < 0)
368         goto finish;
369
370     if (pa_daemon_conf_env(conf) < 0)
371         goto finish;
372
373     if (pa_cmdline_parse(conf, argc, argv, &d) < 0) {
374         pa_log("failed to parse command line.");
375         goto finish;
376     }
377
378     pa_log_set_maximal_level(conf->log_level);
379     pa_log_set_target(conf->auto_log_target ? PA_LOG_STDERR : conf->log_target, NULL);
380
381     if (conf->high_priority && conf->cmd == PA_CMD_DAEMON)
382         pa_raise_priority();
383
384     pa_drop_caps();
385
386     if (suid_root)
387         pa_drop_root();
388
389     if (conf->dl_search_path)
390         lt_dlsetsearchpath(conf->dl_search_path);
391
392     switch (conf->cmd) {
393         case PA_CMD_DUMP_MODULES:
394             pa_dump_modules(conf, argc-d, argv+d);
395             retval = 0;
396             goto finish;
397
398         case PA_CMD_DUMP_CONF: {
399             s = pa_daemon_conf_dump(conf);
400             fputs(s, stdout);
401             pa_xfree(s);
402             retval = 0;
403             goto finish;
404         }
405
406         case PA_CMD_HELP :
407             pa_cmdline_help(argv[0]);
408             retval = 0;
409             goto finish;
410
411         case PA_CMD_VERSION :
412             printf(PACKAGE_NAME" "PACKAGE_VERSION"\n");
413             retval = 0;
414             goto finish;
415
416         case PA_CMD_CHECK: {
417             pid_t pid;
418
419             if (pa_pid_file_check_running(&pid) < 0) {
420                 pa_log_info("daemon not running");
421             } else {
422                 pa_log_info("daemon running as PID %u", pid);
423                 retval = 0;
424             }
425
426             goto finish;
427
428         }
429         case PA_CMD_KILL:
430
431             if (pa_pid_file_kill(SIGINT, NULL) < 0)
432                 pa_log("failed to kill daemon.");
433             else
434                 retval = 0;
435
436             goto finish;
437
438         default:
439             assert(conf->cmd == PA_CMD_DAEMON);
440     }
441
442     if (real_root && !conf->system_instance) {
443         pa_log_warn("This program is not intended to be run as root (unless --system is specified).");
444     } else if (!real_root && conf->system_instance) {
445         pa_log("Root priviliges required.");
446         goto finish;
447     }
448
449     if (conf->daemonize) {
450         pid_t child;
451         int tty_fd;
452
453         if (pa_stdio_acquire() < 0) {
454             pa_log("failed to acquire stdio.");
455             goto finish;
456         }
457
458 #ifdef HAVE_FORK
459         if (pipe(daemon_pipe) < 0) {
460             pa_log("failed to create pipe.");
461             goto finish;
462         }
463
464         if ((child = fork()) < 0) {
465             pa_log("fork() failed: %s", pa_cstrerror(errno));
466             goto finish;
467         }
468
469         if (child != 0) {
470             /* Father */
471
472             close(daemon_pipe[1]);
473             daemon_pipe[1] = -1;
474
475             if (pa_loop_read(daemon_pipe[0], &retval, sizeof(retval), NULL) != sizeof(retval)) {
476                 pa_log("read() failed: %s", pa_cstrerror(errno));
477                 retval = 1;
478             }
479
480             if (retval)
481                 pa_log("daemon startup failed.");
482             else
483                 pa_log_info("daemon startup successful.");
484
485             goto finish;
486         }
487
488         close(daemon_pipe[0]);
489         daemon_pipe[0] = -1;
490 #endif
491
492         if (conf->auto_log_target)
493             pa_log_set_target(PA_LOG_SYSLOG, NULL);
494
495 #ifdef HAVE_SETSID
496         setsid();
497 #endif
498 #ifdef HAVE_SETPGID
499         setpgid(0,0);
500 #endif
501
502 #ifndef OS_IS_WIN32
503         close(0);
504         close(1);
505         close(2);
506
507         open("/dev/null", O_RDONLY);
508         open("/dev/null", O_WRONLY);
509         open("/dev/null", O_WRONLY);
510 #else
511         FreeConsole();
512 #endif
513
514 #ifdef SIGTTOU
515         signal(SIGTTOU, SIG_IGN);
516 #endif
517 #ifdef SIGTTIN
518         signal(SIGTTIN, SIG_IGN);
519 #endif
520 #ifdef SIGTSTP
521         signal(SIGTSTP, SIG_IGN);
522 #endif
523
524 #ifdef TIOCNOTTY
525         if ((tty_fd = open("/dev/tty", O_RDWR)) >= 0) {
526             ioctl(tty_fd, TIOCNOTTY, (char*) 0);
527             close(tty_fd);
528         }
529 #endif
530     }
531
532     chdir("/");
533     umask(0022);
534
535     if (conf->system_instance) {
536         if (change_user() < 0)
537             goto finish;
538     } else if (create_runtime_dir() < 0)
539         goto finish;
540
541     if (conf->use_pid_file) {
542         if (pa_pid_file_create() < 0) {
543             pa_log("pa_pid_file_create() failed.");
544 #ifdef HAVE_FORK
545             if (conf->daemonize)
546                 pa_loop_write(daemon_pipe[1], &retval, sizeof(retval), NULL);
547 #endif
548             goto finish;
549         }
550
551         valid_pid_file = 1;
552     }
553
554 #ifdef HAVE_SYS_RESOURCE_H
555     set_all_rlimits(conf);
556 #endif
557
558 #ifdef SIGPIPE
559     signal(SIGPIPE, SIG_IGN);
560 #endif
561
562     mainloop = pa_mainloop_new();
563     assert(mainloop);
564
565     if (!(c = pa_core_new(pa_mainloop_get_api(mainloop), !conf->disable_shm))) {
566         pa_log("pa_core_new() failed.");
567         goto finish;
568     }
569
570     c->is_system_instance = !!conf->system_instance;
571
572     r = pa_signal_init(pa_mainloop_get_api(mainloop));
573     assert(r == 0);
574     pa_signal_new(SIGINT, signal_callback, c);
575     pa_signal_new(SIGTERM, signal_callback, c);
576
577 #ifdef SIGUSR1
578     pa_signal_new(SIGUSR1, signal_callback, c);
579 #endif
580 #ifdef SIGUSR2
581     pa_signal_new(SIGUSR2, signal_callback, c);
582 #endif
583 #ifdef SIGHUP
584     pa_signal_new(SIGHUP, signal_callback, c);
585 #endif
586
587 #ifdef OS_IS_WIN32
588     timer = pa_mainloop_get_api(mainloop)->time_new(
589         pa_mainloop_get_api(mainloop), pa_gettimeofday(&tv), message_cb, NULL);
590     assert(timer);
591 #endif
592
593     if (conf->daemonize)
594         c->running_as_daemon = 1;
595
596     oil_init();
597
598     if (!conf->no_cpu_limit) {
599         r = pa_cpu_limit_init(pa_mainloop_get_api(mainloop));
600         assert(r == 0);
601     }
602
603     buf = pa_strbuf_new();
604     if (conf->default_script_file)
605         r = pa_cli_command_execute_file(c, conf->default_script_file, buf, &conf->fail);
606
607     if (r >= 0)
608         r = pa_cli_command_execute(c, conf->script_commands, buf, &conf->fail);
609     pa_log_error("%s", s = pa_strbuf_tostring_free(buf));
610     pa_xfree(s);
611
612     if (r < 0 && conf->fail) {
613         pa_log("failed to initialize daemon.");
614 #ifdef HAVE_FORK
615         if (conf->daemonize)
616             pa_loop_write(daemon_pipe[1], &retval, sizeof(retval), NULL);
617 #endif
618     } else if (!c->modules || pa_idxset_size(c->modules) == 0) {
619         pa_log("daemon startup without any loaded modules, refusing to work.");
620 #ifdef HAVE_FORK
621         if (conf->daemonize)
622             pa_loop_write(daemon_pipe[1], &retval, sizeof(retval), NULL);
623 #endif
624     } else {
625
626         retval = 0;
627 #ifdef HAVE_FORK
628         if (conf->daemonize)
629             pa_loop_write(daemon_pipe[1], &retval, sizeof(retval), NULL);
630 #endif
631
632         c->disallow_module_loading = conf->disallow_module_loading;
633         c->exit_idle_time = conf->exit_idle_time;
634         c->module_idle_time = conf->module_idle_time;
635         c->scache_idle_time = conf->scache_idle_time;
636         c->resample_method = conf->resample_method;
637
638         if (c->default_sink_name &&
639             pa_namereg_get(c, c->default_sink_name, PA_NAMEREG_SINK, 1) == NULL) {
640             pa_log_error("%s : Fatal error. Default sink name (%s) does not exist in name register.", __FILE__, c->default_sink_name);
641             retval = 1;
642         } else {
643             pa_log_info("Daemon startup complete.");
644             if (pa_mainloop_run(mainloop, &retval) < 0)
645                 retval = 1;
646             pa_log_info("Daemon shutdown initiated.");
647         }
648     }
649
650 #ifdef OS_IS_WIN32
651     pa_mainloop_get_api(mainloop)->time_free(timer);
652 #endif
653
654     pa_core_free(c);
655
656     if (!conf->no_cpu_limit)
657         pa_cpu_limit_done();
658
659     pa_signal_done();
660
661     pa_log_info("Daemon terminated.");
662
663 finish:
664
665     if (mainloop)
666         pa_mainloop_free(mainloop);
667
668     if (conf)
669         pa_daemon_conf_free(conf);
670
671     if (valid_pid_file)
672         pa_pid_file_remove();
673
674     close_pipe(daemon_pipe);
675
676 #ifdef OS_IS_WIN32
677     WSACleanup();
678 #endif
679
680     lt_dlexit();
681
682     return retval;
683 }