• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***
2   This file is part of PulseAudio.
3 
4   Copyright 2004-2006 Lennart Poettering
5   Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
6 
7   PulseAudio is free software; you can redistribute it and/or modify
8   it under the terms of the GNU Lesser General Public License as published
9   by the Free Software Foundation; either version 2.1 of the License,
10   or (at your option) any later version.
11 
12   PulseAudio is distributed in the hope that it will be useful, but
13   WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   General Public License for more details.
16 
17   You should have received a copy of the GNU Lesser General Public License
18   along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
19 ***/
20 
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24 
25 #include <unistd.h>
26 #include <errno.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <signal.h>
31 #include <stddef.h>
32 #include <ltdl.h>
33 #include <limits.h>
34 #include <unistd.h>
35 #include <locale.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 
39 #ifdef HAVE_SYS_MMAN_H
40 #include <sys/mman.h>
41 #endif
42 
43 #ifdef HAVE_PWD_H
44 #include <pwd.h>
45 #endif
46 #ifdef HAVE_GRP_H
47 #include <grp.h>
48 #endif
49 
50 #ifdef HAVE_LIBWRAP
51 #include <syslog.h>
52 #include <tcpd.h>
53 #endif
54 
55 #ifdef HAVE_DBUS
56 #include <dbus/dbus.h>
57 #endif
58 
59 #ifdef HAVE_SYSTEMD_DAEMON
60 #include <systemd/sd-daemon.h>
61 #endif
62 
63 #include <pulse/client-conf.h>
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/i18n.h>
70 #include <pulsecore/lock-autospawn.h>
71 #include <pulsecore/socket.h>
72 #include <pulsecore/core-error.h>
73 #include <pulsecore/core-rtclock.h>
74 #include <pulsecore/core-scache.h>
75 #include <pulsecore/core.h>
76 #include <pulsecore/module.h>
77 #include <pulsecore/cli-command.h>
78 #include <pulsecore/log.h>
79 #include <pulsecore/core-util.h>
80 #include <pulsecore/sioman.h>
81 #include <pulsecore/cli-text.h>
82 #include <pulsecore/pid.h>
83 #include <pulsecore/random.h>
84 #include <pulsecore/macro.h>
85 #include <pulsecore/shm.h>
86 #include <pulsecore/memtrap.h>
87 #include <pulsecore/strlist.h>
88 #ifdef HAVE_DBUS
89 #include <pulsecore/dbus-shared.h>
90 #endif
91 #include <pulsecore/cpu.h>
92 
93 #include "cmdline.h"
94 #include "cpulimit.h"
95 #include "daemon-conf.h"
96 #include "dumpmodules.h"
97 #include "caps.h"
98 #include "ltdl-bind-now.h"
99 #include "server-lookup.h"
100 
101 #ifdef DISABLE_LIBTOOL_PRELOAD
102 /* FIXME: work around a libtool bug by making sure we have 2 elements. Bug has
103  * been reported: https://debbugs.gnu.org/cgi/bugreport.cgi?bug=29576 */
104 const lt_dlsymlist lt_preloaded_symbols[] = {
105     { "@PROGRAM@", NULL },
106     { NULL, NULL }
107 };
108 #endif
109 
110 #ifdef HAVE_LIBWRAP
111 /* Only one instance of these variables */
112 int allow_severity = LOG_INFO;
113 int deny_severity = LOG_WARNING;
114 #endif
115 
116 #ifdef HAVE_OSS_WRAPPER
117 /* padsp looks for this symbol in the running process and disables
118  * itself if it finds it and it is set to 7 (which is actually a bit
119  * mask). For details see padsp. */
120 int __padsp_disabled__ = 7;
121 #endif
122 
signal_callback(pa_mainloop_api * m,pa_signal_event * e,int sig,void * userdata)123 static void signal_callback(pa_mainloop_api* m, pa_signal_event *e, int sig, void *userdata) {
124     pa_module *module = NULL;
125 
126     pa_log_info("Got signal %s.", pa_sig2str(sig));
127 
128     switch (sig) {
129 #ifdef SIGUSR1
130         case SIGUSR1:
131             pa_module_load(&module, userdata, "module-cli", NULL);
132             break;
133 #endif
134 
135 #ifdef SIGUSR2
136         case SIGUSR2:
137             pa_module_load(&module, userdata, "module-cli-protocol-unix", NULL);
138             break;
139 #endif
140 
141 #ifdef SIGHUP
142         case SIGHUP: {
143             char *c = pa_full_status_string(userdata);
144             pa_log_notice("%s", c);
145             pa_xfree(c);
146             return;
147         }
148 #endif
149 
150         case SIGINT:
151         case SIGTERM:
152         default:
153             pa_log_info("Exiting.");
154             m->quit(m, 0);
155             break;
156     }
157 }
158 
159 #if defined(HAVE_PWD_H) && defined(HAVE_GRP_H)
160 
change_user(void)161 static int change_user(void) {
162     struct passwd *pw;
163     struct group * gr;
164     int r;
165 
166     /* This function is called only in system-wide mode. It creates a
167      * runtime dir in /var/run/ with proper UID/GID and drops privs
168      * afterwards. */
169 
170     if (!(pw = getpwnam(PA_SYSTEM_USER))) {
171         pa_log(_("Failed to find user '%s'."), PA_SYSTEM_USER);
172         return -1;
173     }
174 
175     if (!(gr = getgrnam(PA_SYSTEM_GROUP))) {
176         pa_log(_("Failed to find group '%s'."), PA_SYSTEM_GROUP);
177         return -1;
178     }
179 
180     pa_log_info("Found user '%s' (UID %lu) and group '%s' (GID %lu).",
181                 PA_SYSTEM_USER, (unsigned long) pw->pw_uid,
182                 PA_SYSTEM_GROUP, (unsigned long) gr->gr_gid);
183 
184     if (pw->pw_gid != gr->gr_gid) {
185         pa_log(_("GID of user '%s' and of group '%s' don't match."), PA_SYSTEM_USER, PA_SYSTEM_GROUP);
186         return -1;
187     }
188 
189     if (!pa_streq(pw->pw_dir, PA_SYSTEM_RUNTIME_PATH))
190         pa_log_warn(_("Home directory of user '%s' is not '%s', ignoring."), PA_SYSTEM_USER, PA_SYSTEM_RUNTIME_PATH);
191 
192     if (pa_make_secure_dir(PA_SYSTEM_RUNTIME_PATH, 0755, pw->pw_uid, gr->gr_gid, true) < 0) {
193         pa_log(_("Failed to create '%s': %s"), PA_SYSTEM_RUNTIME_PATH, pa_cstrerror(errno));
194         return -1;
195     }
196 
197     if (pa_make_secure_dir(PA_SYSTEM_STATE_PATH, 0700, pw->pw_uid, gr->gr_gid, true) < 0) {
198         pa_log(_("Failed to create '%s': %s"), PA_SYSTEM_STATE_PATH, pa_cstrerror(errno));
199         return -1;
200     }
201 
202     /* We don't create the config dir here, because we don't need to write to it */
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 privileges"
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 privileges"
234 #endif
235 
236     if (r < 0) {
237         pa_log(_("Failed to change UID: %s"), pa_cstrerror(errno));
238         return -1;
239     }
240 
241     pa_drop_caps();
242 
243     pa_set_env("USER", PA_SYSTEM_USER);
244     pa_set_env("USERNAME", PA_SYSTEM_USER);
245     pa_set_env("LOGNAME", PA_SYSTEM_USER);
246     pa_set_env("HOME", PA_SYSTEM_RUNTIME_PATH);
247 
248     /* Relevant for pa_runtime_path() */
249     if (!getenv("PULSE_RUNTIME_PATH"))
250         pa_set_env("PULSE_RUNTIME_PATH", PA_SYSTEM_RUNTIME_PATH);
251 
252     if (!getenv("PULSE_CONFIG_PATH"))
253         pa_set_env("PULSE_CONFIG_PATH", PA_SYSTEM_CONFIG_PATH);
254 
255     if (!getenv("PULSE_STATE_PATH"))
256         pa_set_env("PULSE_STATE_PATH", PA_SYSTEM_STATE_PATH);
257 
258     pa_log_info("Successfully changed user to \"" PA_SYSTEM_USER "\".");
259 
260     return 0;
261 }
262 
263 #else /* HAVE_PWD_H && HAVE_GRP_H */
264 
change_user(void)265 static int change_user(void) {
266     pa_log(_("System wide mode unsupported on this platform."));
267     return -1;
268 }
269 
270 #endif /* HAVE_PWD_H && HAVE_GRP_H */
271 
272 #ifdef HAVE_SYS_RESOURCE_H
273 
set_one_rlimit(const pa_rlimit * r,int resource,const char * name)274 static int set_one_rlimit(const pa_rlimit *r, int resource, const char *name) {
275     struct rlimit rl;
276     pa_assert(r);
277 
278     if (!r->is_set)
279         return 0;
280 
281     rl.rlim_cur = rl.rlim_max = r->value;
282 
283     if (setrlimit(resource, &rl) < 0) {
284         pa_log_info("setrlimit(%s, (%u, %u)) failed: %s", name, (unsigned) r->value, (unsigned) r->value, pa_cstrerror(errno));
285         return -1;
286     }
287 
288     return 0;
289 }
290 
set_all_rlimits(const pa_daemon_conf * conf)291 static void set_all_rlimits(const pa_daemon_conf *conf) {
292     set_one_rlimit(&conf->rlimit_fsize, RLIMIT_FSIZE, "RLIMIT_FSIZE");
293     set_one_rlimit(&conf->rlimit_data, RLIMIT_DATA, "RLIMIT_DATA");
294     set_one_rlimit(&conf->rlimit_stack, RLIMIT_STACK, "RLIMIT_STACK");
295     set_one_rlimit(&conf->rlimit_core, RLIMIT_CORE, "RLIMIT_CORE");
296 #ifdef RLIMIT_RSS
297     set_one_rlimit(&conf->rlimit_rss, RLIMIT_RSS, "RLIMIT_RSS");
298 #endif
299 #ifdef RLIMIT_NPROC
300     set_one_rlimit(&conf->rlimit_nproc, RLIMIT_NPROC, "RLIMIT_NPROC");
301 #endif
302 #ifdef RLIMIT_NOFILE
303     set_one_rlimit(&conf->rlimit_nofile, RLIMIT_NOFILE, "RLIMIT_NOFILE");
304 #endif
305 #ifdef RLIMIT_MEMLOCK
306     set_one_rlimit(&conf->rlimit_memlock, RLIMIT_MEMLOCK, "RLIMIT_MEMLOCK");
307 #endif
308 #ifdef RLIMIT_AS
309     set_one_rlimit(&conf->rlimit_as, RLIMIT_AS, "RLIMIT_AS");
310 #endif
311 #ifdef RLIMIT_LOCKS
312     set_one_rlimit(&conf->rlimit_locks, RLIMIT_LOCKS, "RLIMIT_LOCKS");
313 #endif
314 #ifdef RLIMIT_SIGPENDING
315     set_one_rlimit(&conf->rlimit_sigpending, RLIMIT_SIGPENDING, "RLIMIT_SIGPENDING");
316 #endif
317 #ifdef RLIMIT_MSGQUEUE
318     set_one_rlimit(&conf->rlimit_msgqueue, RLIMIT_MSGQUEUE, "RLIMIT_MSGQUEUE");
319 #endif
320 #ifdef RLIMIT_NICE
321     set_one_rlimit(&conf->rlimit_nice, RLIMIT_NICE, "RLIMIT_NICE");
322 #endif
323 #ifdef RLIMIT_RTPRIO
324     set_one_rlimit(&conf->rlimit_rtprio, RLIMIT_RTPRIO, "RLIMIT_RTPRIO");
325 #endif
326 #ifdef RLIMIT_RTTIME
327     set_one_rlimit(&conf->rlimit_rttime, RLIMIT_RTTIME, "RLIMIT_RTTIME");
328 #endif
329 }
330 #endif
331 
check_configured_address(void)332 static char *check_configured_address(void) {
333     char *default_server = NULL;
334     pa_client_conf *c = pa_client_conf_new();
335 
336     pa_client_conf_load(c, true, true);
337 
338     if (c->default_server && *c->default_server)
339         default_server = pa_xstrdup(c->default_server);
340 
341     pa_client_conf_free(c);
342 
343     return default_server;
344 }
345 
346 #ifdef HAVE_DBUS
register_dbus_name(pa_core * c,DBusBusType bus,const char * name)347 static pa_dbus_connection *register_dbus_name(pa_core *c, DBusBusType bus, const char* name) {
348     DBusError error;
349     pa_dbus_connection *conn;
350 
351     dbus_error_init(&error);
352 
353     if (!(conn = pa_dbus_bus_get(c, bus, &error)) || dbus_error_is_set(&error)) {
354         pa_log_warn("Unable to contact D-Bus: %s: %s", error.name, error.message);
355         goto fail;
356     }
357 
358     if (dbus_bus_request_name(pa_dbus_connection_get(conn), name, DBUS_NAME_FLAG_DO_NOT_QUEUE, &error) == DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
359         pa_log_debug("Got %s!", name);
360         return conn;
361     }
362 
363     if (dbus_error_is_set(&error))
364         pa_log_error("Failed to acquire %s: %s: %s", name, error.name, error.message);
365     else
366         pa_log_error("D-Bus name %s already taken.", name);
367 
368     /* PA cannot be started twice by the same user and hence we can
369      * ignore mostly the case that a name is already taken. */
370 
371 fail:
372     if (conn)
373         pa_dbus_connection_unref(conn);
374 
375     dbus_error_free(&error);
376     return NULL;
377 }
378 #endif
379 
main(int argc,char * argv[])380 int main(int argc, char *argv[]) {
381     pa_core *c = NULL;
382     pa_strbuf *buf = NULL;
383     pa_daemon_conf *conf = NULL;
384     pa_mainloop *mainloop = NULL;
385     char *s;
386     char *configured_address;
387     int r = 0, retval = 1, d = 0;
388     bool valid_pid_file = false;
389     bool ltdl_init = false;
390     int n_fds = 0, *passed_fds = NULL;
391     const char *e;
392 #ifdef HAVE_FORK
393     int daemon_pipe[2] = { -1, -1 };
394     int daemon_pipe2[2] = { -1, -1 };
395 #endif
396     int autospawn_fd = -1;
397     bool autospawn_locked = false;
398 #ifdef HAVE_DBUS
399     pa_dbusobj_server_lookup *server_lookup = NULL; /* /org/pulseaudio/server_lookup */
400     pa_dbus_connection *lookup_service_bus = NULL; /* Always the user bus. */
401     pa_dbus_connection *server_bus = NULL; /* The bus where we reserve org.pulseaudio.Server, either the user or the system bus. */
402     bool start_server;
403 #endif
404 
405     pa_log_set_ident("pulseaudio");
406     pa_log_set_level(PA_LOG_NOTICE);
407     pa_log_set_flags(PA_LOG_COLORS|PA_LOG_PRINT_FILE|PA_LOG_PRINT_LEVEL, PA_LOG_RESET);
408 
409 #if !defined(HAVE_BIND_NOW) && defined(__linux__) && defined(__OPTIMIZE__)
410     /*
411        Disable lazy relocations to make usage of external libraries
412        more deterministic for our RT threads. We abuse __OPTIMIZE__ as
413        a check whether we are a debug build or not. This all is
414        admittedly a bit snake-oilish.
415     */
416 
417     if (!getenv("LD_BIND_NOW")) {
418         char *rp;
419         char *canonical_rp;
420 
421         /* We have to execute ourselves, because the libc caches the
422          * value of $LD_BIND_NOW on initialization. */
423 
424         pa_set_env("LD_BIND_NOW", "1");
425 
426         if ((canonical_rp = pa_realpath(PA_BINARY))) {
427 
428             if ((rp = pa_readlink("/proc/self/exe"))) {
429 
430                 if (pa_streq(rp, canonical_rp))
431                     pa_assert_se(execv(rp, argv) == 0);
432                 else
433                     pa_log_warn("/proc/self/exe does not point to %s, cannot self execute. Are you playing games?", canonical_rp);
434 
435                 pa_xfree(rp);
436 
437             } else
438                 pa_log_warn("Couldn't read /proc/self/exe, cannot self execute. Running in a chroot()?");
439 
440             pa_xfree(canonical_rp);
441 
442         } else
443             pa_log_warn("Couldn't canonicalize binary path, cannot self execute.");
444     }
445 #endif
446 
447 #ifdef HAVE_SYSTEMD_DAEMON
448     n_fds = sd_listen_fds(0);
449     if (n_fds > 0) {
450         int i = n_fds;
451 
452         passed_fds = pa_xnew(int, n_fds+2);
453         passed_fds[n_fds] = passed_fds[n_fds+1] = -1;
454         while (i--)
455             passed_fds[i] = SD_LISTEN_FDS_START + i;
456     }
457 #endif
458 
459     if (!passed_fds) {
460         n_fds = 0;
461         passed_fds = pa_xnew(int, 2);
462         passed_fds[0] = passed_fds[1] = -1;
463     }
464 
465     if ((e = getenv("PULSE_PASSED_FD"))) {
466         int passed_fd = atoi(e);
467         if (passed_fd > 2)
468             passed_fds[n_fds] = passed_fd;
469     }
470 
471     /* We might be autospawned, in which case have no idea in which
472      * context we have been started. Let's cleanup our execution
473      * context as good as possible */
474 
475     pa_reset_personality();
476     pa_drop_root();
477     pa_close_allv(passed_fds);
478     pa_xfree(passed_fds);
479     pa_reset_sigs(-1);
480     pa_unblock_sigs(-1);
481     pa_reset_priority();
482 
483     setlocale(LC_ALL, "");
484     pa_init_i18n();
485 
486     conf = pa_daemon_conf_new();
487 
488     if (pa_daemon_conf_load(conf, NULL) < 0)
489         goto finish;
490 
491     if (pa_daemon_conf_env(conf) < 0)
492         goto finish;
493 
494     if (pa_cmdline_parse(conf, argc, argv, &d) < 0) {
495         pa_log(_("Failed to parse command line."));
496         goto finish;
497     }
498 
499     if (conf->log_target)
500         pa_log_set_target(conf->log_target);
501     else {
502         pa_log_target target = { .type = PA_LOG_STDERR, .file = NULL };
503         pa_log_set_target(&target);
504     }
505 
506     pa_log_set_level(conf->log_level);
507     if (conf->log_meta)
508         pa_log_set_flags(PA_LOG_PRINT_META, PA_LOG_SET);
509     if (conf->log_time)
510         pa_log_set_flags(PA_LOG_PRINT_TIME, PA_LOG_SET);
511     pa_log_set_show_backtrace(conf->log_backtrace);
512 
513 #ifdef HAVE_DBUS
514     /* conf->system_instance and conf->local_server_type control almost the
515      * same thing; make them agree about what is requested. */
516     switch (conf->local_server_type) {
517         case PA_SERVER_TYPE_UNSET:
518             conf->local_server_type = conf->system_instance ? PA_SERVER_TYPE_SYSTEM : PA_SERVER_TYPE_USER;
519             break;
520         case PA_SERVER_TYPE_USER:
521         case PA_SERVER_TYPE_NONE:
522             conf->system_instance = false;
523             break;
524         case PA_SERVER_TYPE_SYSTEM:
525             conf->system_instance = true;
526             break;
527         default:
528             pa_assert_not_reached();
529     }
530 
531     start_server = conf->local_server_type == PA_SERVER_TYPE_USER || (getuid() == 0 && conf->local_server_type == PA_SERVER_TYPE_SYSTEM);
532 
533     if (!start_server && conf->local_server_type == PA_SERVER_TYPE_SYSTEM) {
534         pa_log_notice(_("System mode refused for non-root user. Only starting the D-Bus server lookup service."));
535         conf->system_instance = false;
536     }
537 #endif
538 
539     LTDL_SET_PRELOADED_SYMBOLS();
540     pa_ltdl_init();
541     ltdl_init = true;
542 
543     if (conf->dl_search_path)
544         lt_dlsetsearchpath(conf->dl_search_path);
545 
546 #ifdef OS_IS_WIN32
547     {
548         WSADATA data;
549         WSAStartup(MAKEWORD(2, 0), &data);
550     }
551 #endif
552 
553     pa_random_seed();
554 
555     switch (conf->cmd) {
556         case PA_CMD_DUMP_MODULES:
557             pa_dump_modules(conf, argc-d, argv+d);
558             retval = 0;
559             goto finish;
560 
561         case PA_CMD_DUMP_CONF: {
562 
563             if (d < argc) {
564                 pa_log("Too many arguments.");
565                 goto finish;
566             }
567 
568             s = pa_daemon_conf_dump(conf);
569             fputs(s, stdout);
570             pa_xfree(s);
571             retval = 0;
572             goto finish;
573         }
574 
575         case PA_CMD_DUMP_RESAMPLE_METHODS: {
576             int i;
577 
578             if (d < argc) {
579                 pa_log("Too many arguments.");
580                 goto finish;
581             }
582 
583             for (i = 0; i < PA_RESAMPLER_MAX; i++)
584                 if (pa_resample_method_supported(i))
585                     printf("%s\n", pa_resample_method_to_string(i));
586 
587             retval = 0;
588             goto finish;
589         }
590 
591         case PA_CMD_HELP :
592             pa_cmdline_help(argv[0]);
593             retval = 0;
594             goto finish;
595 
596         case PA_CMD_VERSION :
597 
598             if (d < argc) {
599                 pa_log("Too many arguments.");
600                 goto finish;
601             }
602 
603             printf(PACKAGE_NAME" "PACKAGE_VERSION"\n");
604             retval = 0;
605             goto finish;
606 
607         case PA_CMD_CHECK: {
608             pid_t pid;
609 
610             if (d < argc) {
611                 pa_log("Too many arguments.");
612                 goto finish;
613             }
614 
615             if (pa_pid_file_check_running(&pid, "pulseaudio") < 0)
616                 pa_log_info("Daemon not running");
617             else {
618                 pa_log_info("Daemon running as PID %u", pid);
619                 retval = 0;
620             }
621 
622             goto finish;
623 
624         }
625         case PA_CMD_KILL:
626 
627             if (d < argc) {
628                 pa_log("Too many arguments.");
629                 goto finish;
630             }
631 
632             if (pa_pid_file_kill(SIGINT, NULL, "pulseaudio") < 0)
633                 pa_log(_("Failed to kill daemon: %s"), pa_cstrerror(errno));
634             else
635                 retval = 0;
636 
637             goto finish;
638 
639         case PA_CMD_CLEANUP_SHM:
640 
641             if (d < argc) {
642                 pa_log("Too many arguments.");
643                 goto finish;
644             }
645 
646             if (pa_shm_cleanup() >= 0)
647                 retval = 0;
648 
649             goto finish;
650 
651         default:
652             pa_assert(conf->cmd == PA_CMD_DAEMON || conf->cmd == PA_CMD_START);
653     }
654 
655     if (d < argc) {
656         pa_log("Too many arguments.");
657         goto finish;
658     }
659 
660 #ifdef HAVE_GETUID
661     if (getuid() == 0 && !conf->system_instance)
662         pa_log_warn(_("This program is not intended to be run as root (unless --system is specified)."));
663 #ifndef HAVE_DBUS /* A similar, only a notice worthy check was done earlier, if D-Bus is enabled. */
664     else if (getuid() != 0 && conf->system_instance) {
665         pa_log(_("Root privileges required."));
666         goto finish;
667     }
668 #endif
669 #endif  /* HAVE_GETUID */
670 
671     if (conf->cmd == PA_CMD_START && conf->system_instance) {
672         pa_log(_("--start not supported for system instances."));
673         goto finish;
674     }
675 
676     if (conf->cmd == PA_CMD_START && (configured_address = check_configured_address())) {
677         /* There is an server address in our config, but where did it come from?
678          * By default a standard X11 login will load module-x11-publish which will
679          * inject PULSE_SERVER X11 property. If the PA daemon crashes, we will end
680          * up hitting this code path. So we have to check to see if our configured_address
681          * is the same as the value that would go into this property so that we can
682          * recover (i.e. autospawn) from a crash.
683          */
684         char *ufn;
685         bool start_anyway = false;
686 
687         if ((ufn = pa_runtime_path(PA_NATIVE_DEFAULT_UNIX_SOCKET))) {
688             char *id;
689 
690             if ((id = pa_machine_id())) {
691                 pa_strlist *server_list;
692                 char formatted_ufn[256];
693 
694                 pa_snprintf(formatted_ufn, sizeof(formatted_ufn), "{%s}unix:%s", id, ufn);
695                 pa_xfree(id);
696 
697                 if ((server_list = pa_strlist_parse(configured_address))) {
698                     char *u = NULL;
699 
700                     /* We only need to check the first server */
701                     server_list = pa_strlist_pop(server_list, &u);
702                     pa_strlist_free(server_list);
703 
704                     start_anyway = (u && pa_streq(formatted_ufn, u));
705                     pa_xfree(u);
706                 }
707             }
708             pa_xfree(ufn);
709         }
710 
711         if (!start_anyway) {
712             pa_log_notice(_("User-configured server at %s, refusing to start/autospawn."), configured_address);
713             pa_xfree(configured_address);
714             retval = 0;
715             goto finish;
716         }
717 
718         pa_log_notice(_("User-configured server at %s, which appears to be local. Probing deeper."), configured_address);
719         pa_xfree(configured_address);
720     }
721 
722     if (conf->system_instance && !conf->disallow_exit)
723         pa_log_warn(_("Running in system mode, but --disallow-exit not set."));
724 
725     if (conf->system_instance && !conf->disallow_module_loading)
726         pa_log_warn(_("Running in system mode, but --disallow-module-loading not set."));
727 
728     if (conf->system_instance && !conf->disable_shm) {
729         pa_log_notice(_("Running in system mode, forcibly disabling SHM mode."));
730         conf->disable_shm = true;
731     }
732 
733     if (conf->system_instance && conf->exit_idle_time >= 0) {
734         pa_log_notice(_("Running in system mode, forcibly disabling exit idle time."));
735         conf->exit_idle_time = -1;
736     }
737 
738     if (conf->cmd == PA_CMD_START) {
739         /* If we shall start PA only when it is not running yet, we
740          * first take the autospawn lock to make things
741          * synchronous. */
742 
743         /* This locking and thread synchronisation code doesn't work reliably
744          * on kFreeBSD (Debian bug #705435), or in upstream FreeBSD ports
745          * (bug reference: ports/128947, patched in SVN r231972). */
746 #if !defined(__FreeBSD__) && !defined(__FreeBSD_kernel__)
747         if ((autospawn_fd = pa_autospawn_lock_init()) < 0) {
748             pa_log("Failed to initialize autospawn lock");
749             goto finish;
750         }
751 
752         if ((pa_autospawn_lock_acquire(true) < 0)) {
753             pa_log("Failed to acquire autospawn lock");
754             goto finish;
755         }
756 
757         autospawn_locked = true;
758 #endif
759     }
760 
761     if (conf->daemonize) {
762 #ifdef HAVE_FORK
763         pid_t child;
764 #endif
765 
766         if (pa_stdio_acquire() < 0) {
767             pa_log(_("Failed to acquire stdio."));
768             goto finish;
769         }
770 
771 #ifdef HAVE_FORK
772         if (pipe(daemon_pipe) < 0) {
773             pa_log(_("pipe() failed: %s"), pa_cstrerror(errno));
774             goto finish;
775         }
776 
777         if ((child = fork()) < 0) {
778             pa_log(_("fork() failed: %s"), pa_cstrerror(errno));
779             pa_close_pipe(daemon_pipe);
780             goto finish;
781         }
782 
783         if (child != 0) {
784             ssize_t n;
785             /* Father */
786 
787             pa_assert_se(pa_close(daemon_pipe[1]) == 0);
788             daemon_pipe[1] = -1;
789 
790             if ((n = pa_loop_read(daemon_pipe[0], &retval, sizeof(retval), NULL)) != sizeof(retval)) {
791 
792                 if (n < 0)
793                     pa_log(_("read() failed: %s"), pa_cstrerror(errno));
794 
795                 retval = 1;
796             }
797 
798             if (retval)
799                 pa_log(_("Daemon startup failed."));
800             else
801                 pa_log_info("Daemon startup successful.");
802 
803             goto finish;
804         }
805 
806         if (autospawn_fd >= 0) {
807             /* The lock file is unlocked from the parent, so we need
808              * to close it in the child */
809 
810             pa_autospawn_lock_release();
811             pa_autospawn_lock_done(true);
812 
813             autospawn_locked = false;
814             autospawn_fd = -1;
815         }
816 
817         pa_assert_se(pa_close(daemon_pipe[0]) == 0);
818         daemon_pipe[0] = -1;
819 #endif
820 
821         if (!conf->log_target) {
822 #ifdef HAVE_SYSTEMD_JOURNAL
823             pa_log_target target = { .type = PA_LOG_JOURNAL, .file = NULL };
824 #else
825             pa_log_target target = { .type = PA_LOG_SYSLOG, .file = NULL };
826 #endif
827             pa_log_set_target(&target);
828         }
829 
830 #ifdef HAVE_SETSID
831         if (setsid() < 0) {
832             pa_log(_("setsid() failed: %s"), pa_cstrerror(errno));
833             goto finish;
834         }
835 #endif
836 
837 #ifdef HAVE_FORK
838         /* We now are a session and process group leader. Let's fork
839          * again and let the father die, so that we'll become a
840          * process that can never acquire a TTY again, in a session and
841          * process group without leader */
842 
843         if (pipe(daemon_pipe2) < 0) {
844             pa_log(_("pipe() failed: %s"), pa_cstrerror(errno));
845             goto finish;
846         }
847 
848         if ((child = fork()) < 0) {
849             pa_log(_("fork() failed: %s"), pa_cstrerror(errno));
850             pa_close_pipe(daemon_pipe2);
851             goto finish;
852         }
853 
854         if (child != 0) {
855             ssize_t n;
856             /* Father */
857 
858             pa_assert_se(pa_close(daemon_pipe2[1]) == 0);
859             daemon_pipe2[1] = -1;
860 
861             if ((n = pa_loop_read(daemon_pipe2[0], &retval, sizeof(retval), NULL)) != sizeof(retval)) {
862 
863                 if (n < 0)
864                     pa_log(_("read() failed: %s"), pa_cstrerror(errno));
865 
866                 retval = 1;
867             }
868 
869             /* We now have to take care of signalling the first fork with
870              * the return value we've received from this fork... */
871             pa_assert(daemon_pipe[1] >= 0);
872 
873             pa_loop_write(daemon_pipe[1], &retval, sizeof(retval), NULL);
874             pa_close(daemon_pipe[1]);
875             daemon_pipe[1] = -1;
876 
877             goto finish;
878         }
879 
880         pa_assert_se(pa_close(daemon_pipe2[0]) == 0);
881         daemon_pipe2[0] = -1;
882 
883         /* We no longer need the (first) daemon_pipe as it's handled in our child above */
884         pa_close_pipe(daemon_pipe);
885 #endif
886 
887 #ifdef SIGTTOU
888         signal(SIGTTOU, SIG_IGN);
889 #endif
890 #ifdef SIGTTIN
891         signal(SIGTTIN, SIG_IGN);
892 #endif
893 #ifdef SIGTSTP
894         signal(SIGTSTP, SIG_IGN);
895 #endif
896 
897         pa_nullify_stdfds();
898     }
899 
900     pa_set_env_and_record("PULSE_INTERNAL", "1");
901     pa_assert_se(chdir("/") == 0);
902     umask(0077);
903 
904 #ifdef HAVE_SYS_RESOURCE_H
905     set_all_rlimits(conf);
906 #endif
907     pa_rtclock_hrtimer_enable();
908 
909     if (conf->high_priority)
910         pa_raise_priority(conf->nice_level);
911 
912     if (conf->system_instance)
913         if (change_user() < 0)
914             goto finish;
915 
916     pa_set_env_and_record("PULSE_SYSTEM", conf->system_instance ? "1" : "0");
917 
918     pa_log_info("This is PulseAudio %s", PACKAGE_VERSION);
919     pa_log_debug("Compilation CFLAGS: %s", PA_CFLAGS);
920 
921 #ifdef HAVE_LIBSAMPLERATE
922     pa_log_warn("Compiled with DEPRECATED libsamplerate support!");
923 #endif
924 
925     s = pa_uname_string();
926     pa_log_debug("Running on host: %s", s);
927     pa_xfree(s);
928 
929     pa_log_debug("Found %u CPUs.", pa_ncpus());
930 
931     pa_log_info("Page size is %zu bytes", pa_page_size());
932 
933 #ifdef HAVE_VALGRIND_MEMCHECK_H
934     pa_log_debug("Compiled with Valgrind support: yes");
935 #else
936     pa_log_debug("Compiled with Valgrind support: no");
937 #endif
938 
939     pa_log_debug("Running in valgrind mode: %s", pa_yes_no(pa_in_valgrind()));
940 
941     pa_log_debug("Running in VM: %s", pa_yes_no(pa_running_in_vm()));
942 
943 #ifdef HAVE_RUNNING_FROM_BUILD_TREE
944     pa_log_debug("Running from build tree: %s", pa_yes_no(pa_run_from_build_tree()));
945 #else
946     pa_log_debug("Running from build tree: no");
947 #endif
948 
949 #ifdef __OPTIMIZE__
950     pa_log_debug("Optimized build: yes");
951 #else
952     pa_log_debug("Optimized build: no");
953 #endif
954 
955 #ifdef NDEBUG
956     pa_log_debug("NDEBUG defined, all asserts disabled.");
957 #elif defined(FASTPATH)
958     pa_log_debug("FASTPATH defined, only fast path asserts disabled.");
959 #else
960     pa_log_debug("All asserts enabled.");
961 #endif
962 
963     if (!(s = pa_machine_id())) {
964         pa_log(_("Failed to get machine ID"));
965         goto finish;
966     }
967     pa_log_info("Machine ID is %s.", s);
968     pa_xfree(s);
969 
970     if ((s = pa_session_id())) {
971         pa_log_info("Session ID is %s.", s);
972         pa_xfree(s);
973     }
974 
975     if (!(s = pa_get_runtime_dir()))
976         goto finish;
977     pa_log_info("Using runtime directory %s.", s);
978     pa_xfree(s);
979 
980     if (!(s = pa_get_state_dir()))
981         goto finish;
982     pa_log_info("Using state directory %s.", s);
983     pa_xfree(s);
984 
985     pa_log_info("Using modules directory %s.", conf->dl_search_path);
986 
987     pa_log_info("Running in system mode: %s", pa_yes_no(pa_in_system_mode()));
988 
989     if (pa_in_system_mode())
990         pa_log_warn(_("OK, so you are running PA in system mode. Please make sure that you actually do want to do that.\n"
991                       "Please read http://www.freedesktop.org/wiki/Software/PulseAudio/Documentation/User/WhatIsWrongWithSystemWide/ for an explanation why system mode is usually a bad idea."));
992 
993     if (conf->use_pid_file) {
994         int z;
995 
996         if ((z = pa_pid_file_create("pulseaudio")) != 0) {
997 
998             if (conf->cmd == PA_CMD_START && z > 0) {
999                 /* If we are already running and with are run in
1000                  * --start mode, then let's return this as success. */
1001 
1002                 retval = 0;
1003                 goto finish;
1004             }
1005 
1006             pa_log(_("pa_pid_file_create() failed."));
1007             goto finish;
1008         }
1009 
1010         valid_pid_file = true;
1011     }
1012 
1013     pa_disable_sigpipe();
1014 
1015     if (pa_rtclock_hrtimer())
1016         pa_log_info("System supports high resolution timers");
1017     else
1018         pa_log_info("System appears to not support high resolution timers");
1019 
1020     if (conf->lock_memory) {
1021 #if defined(HAVE_SYS_MMAN_H) && !defined(__ANDROID__)
1022         if (mlockall(MCL_FUTURE) < 0)
1023             pa_log_warn("mlockall() failed: %s", pa_cstrerror(errno));
1024         else
1025             pa_log_info("Successfully locked process into memory.");
1026 #else
1027         pa_log_warn("Memory locking requested but not supported on platform.");
1028 #endif
1029     }
1030 
1031     pa_memtrap_install();
1032 
1033     pa_assert_se(mainloop = pa_mainloop_new());
1034 
1035     if (!(c = pa_core_new(pa_mainloop_get_api(mainloop), !conf->disable_shm,
1036                           !conf->disable_shm && !conf->disable_memfd && pa_memfd_is_locally_supported(),
1037                           conf->shm_size))) {
1038         pa_log(_("pa_core_new() failed."));
1039         goto finish;
1040     }
1041 
1042     c->default_sample_spec = conf->default_sample_spec;
1043     c->alternate_sample_rate = conf->alternate_sample_rate;
1044     c->default_channel_map = conf->default_channel_map;
1045     c->default_n_fragments = conf->default_n_fragments;
1046     c->default_fragment_size_msec = conf->default_fragment_size_msec;
1047     c->deferred_volume_safety_margin_usec = conf->deferred_volume_safety_margin_usec;
1048     c->deferred_volume_extra_delay_usec = conf->deferred_volume_extra_delay_usec;
1049     c->lfe_crossover_freq = conf->lfe_crossover_freq;
1050     c->exit_idle_time = conf->exit_idle_time;
1051     c->scache_idle_time = conf->scache_idle_time;
1052     c->resample_method = conf->resample_method;
1053     c->realtime_priority = conf->realtime_priority;
1054     c->realtime_scheduling = conf->realtime_scheduling;
1055     c->avoid_resampling = conf->avoid_resampling;
1056     c->disable_remixing = conf->disable_remixing;
1057     c->remixing_use_all_sink_channels = conf->remixing_use_all_sink_channels;
1058     c->remixing_produce_lfe = conf->remixing_produce_lfe;
1059     c->remixing_consume_lfe = conf->remixing_consume_lfe;
1060     c->deferred_volume = conf->deferred_volume;
1061     c->running_as_daemon = conf->daemonize;
1062     c->disallow_exit = conf->disallow_exit;
1063     c->flat_volumes = conf->flat_volumes;
1064     c->rescue_streams = conf->rescue_streams;
1065 #ifdef HAVE_DBUS
1066     c->server_type = conf->local_server_type;
1067 #endif
1068 
1069     pa_core_check_idle(c);
1070 
1071     c->state = PA_CORE_RUNNING;
1072 
1073     pa_cpu_init(&c->cpu_info);
1074 
1075     pa_assert_se(pa_signal_init(pa_mainloop_get_api(mainloop)) == 0);
1076     pa_signal_new(SIGINT, signal_callback, c);
1077     pa_signal_new(SIGTERM, signal_callback, c);
1078 #ifdef SIGUSR1
1079     pa_signal_new(SIGUSR1, signal_callback, c);
1080 #endif
1081 #ifdef SIGUSR2
1082     pa_signal_new(SIGUSR2, signal_callback, c);
1083 #endif
1084 #ifdef SIGHUP
1085     pa_signal_new(SIGHUP, signal_callback, c);
1086 #endif
1087 
1088     if (!conf->no_cpu_limit)
1089         pa_assert_se(pa_cpu_limit_init(pa_mainloop_get_api(mainloop)) == 0);
1090 
1091     buf = pa_strbuf_new();
1092 
1093 #ifdef HAVE_DBUS
1094     pa_assert_se(dbus_threads_init_default());
1095 
1096     if (start_server)
1097 #endif
1098     {
1099         const char *command_source = NULL;
1100 
1101         if (conf->load_default_script_file) {
1102             FILE *f;
1103 
1104             if ((f = pa_daemon_conf_open_default_script_file(conf))) {
1105                 r = pa_cli_command_execute_file_stream(c, f, buf, &conf->fail);
1106                 fclose(f);
1107                 command_source = pa_daemon_conf_get_default_script_file(conf);
1108             }
1109         }
1110 
1111         if (r >= 0) {
1112             r = pa_cli_command_execute(c, conf->script_commands, buf, &conf->fail);
1113             command_source = _("command line arguments");
1114         }
1115 
1116         pa_log_error("%s", s = pa_strbuf_to_string_free(buf));
1117         pa_xfree(s);
1118 
1119         if (r < 0 && conf->fail) {
1120             pa_log(_("Failed to initialize daemon due to errors while executing startup commands. Source of commands: %s"), command_source);
1121             goto finish;
1122         }
1123 
1124         if (!c->modules || pa_idxset_size(c->modules) == 0) {
1125             pa_log(_("Daemon startup without any loaded modules, refusing to work."));
1126             goto finish;
1127         }
1128 #ifdef HAVE_DBUS
1129     } else {
1130         /* When we just provide the D-Bus server lookup service, we don't want
1131          * any modules to be loaded. We haven't loaded any so far, so one might
1132          * think there's no way to contact the server, but receiving certain
1133          * signals could still cause modules to load. */
1134         conf->disallow_module_loading = true;
1135 #endif
1136     }
1137 
1138     /* We completed the initial module loading, so let's disable it
1139      * from now on, if requested */
1140     c->disallow_module_loading = conf->disallow_module_loading;
1141 
1142 #ifdef HAVE_DBUS
1143     if (!conf->system_instance) {
1144         if ((server_lookup = pa_dbusobj_server_lookup_new(c))) {
1145             if (!(lookup_service_bus = register_dbus_name(c, DBUS_BUS_SESSION, "org.PulseAudio1")))
1146                 goto finish;
1147         }
1148     }
1149 
1150     if (start_server)
1151         server_bus = register_dbus_name(c, conf->system_instance ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, "org.pulseaudio.Server");
1152 #endif
1153 
1154 #ifdef HAVE_FORK
1155     if (daemon_pipe2[1] >= 0) {
1156         int ok = 0;
1157         pa_loop_write(daemon_pipe2[1], &ok, sizeof(ok), NULL);
1158         pa_close(daemon_pipe2[1]);
1159         daemon_pipe2[1] = -1;
1160     }
1161 #endif
1162 
1163     pa_log_info("Daemon startup complete.");
1164 
1165 #ifdef HAVE_SYSTEMD_DAEMON
1166     sd_notify(0, "READY=1");
1167 #endif
1168 
1169     retval = 0;
1170     if (pa_mainloop_run(mainloop, &retval) < 0)
1171         goto finish;
1172 
1173     pa_log_info("Daemon shutdown initiated.");
1174 
1175 #ifdef HAVE_SYSTEMD_DAEMON
1176     sd_notify(0, "STOPPING=1");
1177 #endif
1178 
1179 finish:
1180 #ifdef HAVE_DBUS
1181     if (server_bus)
1182         pa_dbus_connection_unref(server_bus);
1183     if (lookup_service_bus)
1184         pa_dbus_connection_unref(lookup_service_bus);
1185     if (server_lookup)
1186         pa_dbusobj_server_lookup_free(server_lookup);
1187 #endif
1188 
1189     if (autospawn_fd >= 0) {
1190         if (autospawn_locked)
1191             pa_autospawn_lock_release();
1192 
1193         pa_autospawn_lock_done(false);
1194     }
1195 
1196     if (c) {
1197         /* Ensure all the modules/samples are unloaded when the core is still ref'ed,
1198          * as unlink callback hooks in modules may need the core to be ref'ed */
1199         pa_module_unload_all(c);
1200         pa_scache_free_all(c);
1201 
1202         pa_core_unref(c);
1203         pa_log_info("Daemon terminated.");
1204     }
1205 
1206     if (!conf->no_cpu_limit)
1207         pa_cpu_limit_done();
1208 
1209     pa_signal_done();
1210 
1211 #ifdef HAVE_FORK
1212     /* If we have daemon_pipe[1] still open, this means we've failed after
1213      * the first fork, but before the second. Therefore just write to it. */
1214     if (daemon_pipe[1] >= 0)
1215         pa_loop_write(daemon_pipe[1], &retval, sizeof(retval), NULL);
1216     else if (daemon_pipe2[1] >= 0)
1217         pa_loop_write(daemon_pipe2[1], &retval, sizeof(retval), NULL);
1218 
1219     pa_close_pipe(daemon_pipe2);
1220     pa_close_pipe(daemon_pipe);
1221 #endif
1222 
1223     if (mainloop)
1224         pa_mainloop_free(mainloop);
1225 
1226     if (conf)
1227         pa_daemon_conf_free(conf);
1228 
1229     if (valid_pid_file)
1230         pa_pid_file_remove();
1231 
1232     /* This has no real purpose except making things valgrind-clean */
1233     pa_unset_env_recorded();
1234 
1235 #ifdef OS_IS_WIN32
1236     WSACleanup();
1237 #endif
1238 
1239     if (ltdl_init)
1240         pa_ltdl_done();
1241 
1242 #ifdef HAVE_DBUS
1243     dbus_shutdown();
1244 #endif
1245 
1246     return retval;
1247 }
1248