xref: /third_party/pulseaudio/src/daemon/main.c (revision 53a5a1b3)
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#ifdef HAVE_WINDOWS_H
64#include <windows.h>
65#include <aclapi.h>
66#include <sddl.h>
67#endif
68
69#include <pulse/client-conf.h>
70#include <pulse/mainloop.h>
71#include <pulse/mainloop-signal.h>
72#include <pulse/timeval.h>
73#include <pulse/xmalloc.h>
74
75#include <pulsecore/i18n.h>
76#include <pulsecore/lock-autospawn.h>
77#include <pulsecore/socket.h>
78#include <pulsecore/core-error.h>
79#include <pulsecore/core-rtclock.h>
80#include <pulsecore/core-scache.h>
81#include <pulsecore/core.h>
82#include <pulsecore/module.h>
83#include <pulsecore/cli-command.h>
84#include <pulsecore/log.h>
85#include <pulsecore/core-util.h>
86#include <pulsecore/sioman.h>
87#include <pulsecore/cli-text.h>
88#include <pulsecore/pid.h>
89#include <pulsecore/random.h>
90#include <pulsecore/macro.h>
91#include <pulsecore/shm.h>
92#include <pulsecore/memtrap.h>
93#include <pulsecore/strlist.h>
94#ifdef HAVE_DBUS
95#include <pulsecore/dbus-shared.h>
96#endif
97#include <pulsecore/cpu.h>
98
99#include "cmdline.h"
100#include "cpulimit.h"
101#include "daemon-conf.h"
102#include "dumpmodules.h"
103#include "caps.h"
104#include "ltdl-bind-now.h"
105#include "server-lookup.h"
106
107#ifdef DISABLE_LIBTOOL_PRELOAD
108/* FIXME: work around a libtool bug by making sure we have 2 elements. Bug has
109 * been reported: https://debbugs.gnu.org/cgi/bugreport.cgi?bug=29576 */
110LT_DLSYM_CONST lt_dlsymlist lt_preloaded_symbols[] = {
111    { "@PROGRAM@", NULL },
112    { NULL, NULL }
113};
114#endif
115
116#ifdef HAVE_LIBWRAP
117/* Only one instance of these variables */
118int allow_severity = LOG_INFO;
119int deny_severity = LOG_WARNING;
120#endif
121
122#ifdef HAVE_OSS_WRAPPER
123/* padsp looks for this symbol in the running process and disables
124 * itself if it finds it and it is set to 7 (which is actually a bit
125 * mask). For details see padsp. */
126int __padsp_disabled__ = 7;
127#endif
128
129static void signal_callback(pa_mainloop_api* m, pa_signal_event *e, int sig, void *userdata) {
130    pa_module *module = NULL;
131
132    pa_log_info("Got signal %s.", pa_sig2str(sig));
133
134    switch (sig) {
135#ifdef SIGUSR1
136        case SIGUSR1:
137            pa_module_load(&module, userdata, "module-cli", NULL);
138            break;
139#endif
140
141#ifdef SIGUSR2
142        case SIGUSR2:
143            pa_module_load(&module, userdata, "module-cli-protocol-unix", NULL);
144            break;
145#endif
146
147#ifdef SIGHUP
148        case SIGHUP: {
149            char *c = pa_full_status_string(userdata);
150            pa_log_notice("%s", c);
151            pa_xfree(c);
152            return;
153        }
154#endif
155
156        case SIGINT:
157        case SIGTERM:
158        default:
159            pa_log_info("Exiting.");
160            m->quit(m, 0);
161            break;
162    }
163}
164
165
166#if defined(OS_IS_WIN32)
167
168static int change_user(void) {
169    pa_log_info("Overriding system runtime/config base dir to '%s'.", pa_win32_get_system_appdata());
170
171    /* On other platforms, these paths are compiled into PulseAudio. This isn't
172     * suitable on Windows. Firstly, Windows doesn't follow the FHS or use Unix
173     * paths and the build system can't handle Windows-style paths properly.
174     * Secondly, the idiomatic location for a service's state and shared data is
175     * ProgramData, and the location of special folders is dynamic on Windows.
176     * Also, this method of handling paths is consistent with how they are
177     * handled on Windows in other parts of PA. Note that this is only needed
178     * in system-wide mode since paths in user instances are already handled
179     * properly.
180     */
181
182    char *run_path = pa_sprintf_malloc("%s" PA_PATH_SEP "run", pa_win32_get_system_appdata());
183    char *lib_path = pa_sprintf_malloc("%s" PA_PATH_SEP "lib", pa_win32_get_system_appdata());
184
185    /* https://docs.microsoft.com/en-us/windows/win32/secauthz/ace-strings */
186    /* https://docs.microsoft.com/en-us/windows/win32/secauthz/modifying-the-acls-of-an-object-in-c-- */
187    /* https://docs.microsoft.com/en-us/windows/win32/api/sddl/nf-sddl-convertstringsecuritydescriptortosecuritydescriptora */
188    {
189        mkdir(run_path);
190        PSECURITY_DESCRIPTOR sd;
191        if (ConvertStringSecurityDescriptorToSecurityDescriptorA(
192            "D:PAI"                   /* DACL, disable inheritance from parent, enable propagation to children */
193            "(A;OICI;FA;;;SY)"        /* give system full access */
194            "(A;OICI;FA;;;CO)"        /* give owner full access */
195            "(A;OICI;FA;;;BA)"        /* give administrators full access */
196            "(A;OICI;0x1200a9;;;WD)", /* give everyone read/write/execute access */
197            SDDL_REVISION_1, &sd, NULL
198        )) {
199            PACL acl;
200            BOOL acl_present, acl_default;
201            if (GetSecurityDescriptorDacl(sd, &acl_present, &acl, &acl_default)) {
202                if (SetNamedSecurityInfo(run_path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, NULL, NULL, acl, NULL) != ERROR_SUCCESS) {
203                    pa_log_warn("Failed to set DACL for runtime dir: failed to apply DACL: error %lu.", GetLastError());
204                }
205                LocalFree(acl);
206            } else {
207                pa_log_warn("Failed to set DACL for runtime dir: failed to get security descriptor DACL: error %lu.", GetLastError());
208            }
209        } else {
210            pa_log_warn("Failed to set DACL for runtime dir: failed to parse security descriptor: error %lu.", GetLastError());
211        }
212    }
213    {
214        mkdir(lib_path);
215        PSECURITY_DESCRIPTOR sd;
216        if (ConvertStringSecurityDescriptorToSecurityDescriptorA(
217            "D:PAI"             /* DACL, disable inheritance from parent, enable propagation to children */
218            "(A;OICI;FA;;;SY)"  /* give system full access */
219            "(A;OICI;FA;;;CO)"  /* give owner full access */
220            "(A;OICI;FA;;;BA)", /* give administrators full access */
221            SDDL_REVISION_1, &sd, NULL
222        )) {
223            PACL acl;
224            BOOL acl_present, acl_default;
225            if (GetSecurityDescriptorDacl(sd, &acl_present, &acl, &acl_default)) {
226                if (SetNamedSecurityInfo(lib_path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, NULL, NULL, acl, NULL) != ERROR_SUCCESS) {
227                    pa_log_warn("Failed to set DACL for lib dir: failed to apply DACL: error %lu.", GetLastError());
228                }
229                LocalFree(acl);
230            } else {
231                pa_log_warn("Failed to set DACL for lib dir: failed to get security descriptor DACL: error %lu.", GetLastError());
232            }
233        } else {
234            pa_log_warn("Failed to set DACL for lib dir: failed to parse security descriptor: error %lu.", GetLastError());
235        }
236    }
237
238    pa_set_env("HOME", run_path);
239    if (!getenv("PULSE_RUNTIME_PATH"))
240        pa_set_env("PULSE_RUNTIME_PATH", run_path);
241    if (!getenv("PULSE_CONFIG_PATH"))
242        pa_set_env("PULSE_CONFIG_PATH", lib_path);
243    if (!getenv("PULSE_STATE_PATH"))
244        pa_set_env("PULSE_STATE_PATH", lib_path);
245
246    pa_xfree(run_path);
247    pa_xfree(lib_path);
248
249    pa_log_info("Not changing user for system instance on Windows.");
250    return 0;
251}
252
253#elif defined(HAVE_PWD_H) && defined(HAVE_GRP_H)
254
255static int change_user(void) {
256    struct passwd *pw;
257    struct group * gr;
258    int r;
259
260    /* This function is called only in system-wide mode. It creates a
261     * runtime dir in /var/run/ with proper UID/GID and drops privs
262     * afterwards. */
263
264    if (!(pw = getpwnam(PA_SYSTEM_USER))) {
265        pa_log(_("Failed to find user '%s'."), PA_SYSTEM_USER);
266        return -1;
267    }
268
269    if (!(gr = getgrnam(PA_SYSTEM_GROUP))) {
270        pa_log(_("Failed to find group '%s'."), PA_SYSTEM_GROUP);
271        return -1;
272    }
273
274    pa_log_info("Found user '%s' (UID %lu) and group '%s' (GID %lu).",
275                PA_SYSTEM_USER, (unsigned long) pw->pw_uid,
276                PA_SYSTEM_GROUP, (unsigned long) gr->gr_gid);
277
278    if (pw->pw_gid != gr->gr_gid) {
279        pa_log(_("GID of user '%s' and of group '%s' don't match."), PA_SYSTEM_USER, PA_SYSTEM_GROUP);
280        return -1;
281    }
282
283    if (!pa_streq(pw->pw_dir, PA_SYSTEM_RUNTIME_PATH))
284        pa_log_warn(_("Home directory of user '%s' is not '%s', ignoring."), PA_SYSTEM_USER, PA_SYSTEM_RUNTIME_PATH);
285
286    if (pa_make_secure_dir(PA_SYSTEM_RUNTIME_PATH, 0755, pw->pw_uid, gr->gr_gid, true) < 0) {
287        pa_log(_("Failed to create '%s': %s"), PA_SYSTEM_RUNTIME_PATH, pa_cstrerror(errno));
288        return -1;
289    }
290
291    if (pa_make_secure_dir(PA_SYSTEM_STATE_PATH, 0700, pw->pw_uid, gr->gr_gid, true) < 0) {
292        pa_log(_("Failed to create '%s': %s"), PA_SYSTEM_STATE_PATH, pa_cstrerror(errno));
293        return -1;
294    }
295
296    /* We don't create the config dir here, because we don't need to write to it */
297
298    if (initgroups(PA_SYSTEM_USER, gr->gr_gid) != 0) {
299        pa_log(_("Failed to change group list: %s"), pa_cstrerror(errno));
300        return -1;
301    }
302
303#if defined(HAVE_SETRESGID)
304    r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
305#elif defined(HAVE_SETEGID)
306    if ((r = setgid(gr->gr_gid)) >= 0)
307        r = setegid(gr->gr_gid);
308#elif defined(HAVE_SETREGID)
309    r = setregid(gr->gr_gid, gr->gr_gid);
310#else
311#error "No API to drop privileges"
312#endif
313
314    if (r < 0) {
315        pa_log(_("Failed to change GID: %s"), pa_cstrerror(errno));
316        return -1;
317    }
318
319#if defined(HAVE_SETRESUID)
320    r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
321#elif defined(HAVE_SETEUID)
322    if ((r = setuid(pw->pw_uid)) >= 0)
323        r = seteuid(pw->pw_uid);
324#elif defined(HAVE_SETREUID)
325    r = setreuid(pw->pw_uid, pw->pw_uid);
326#else
327#error "No API to drop privileges"
328#endif
329
330    if (r < 0) {
331        pa_log(_("Failed to change UID: %s"), pa_cstrerror(errno));
332        return -1;
333    }
334
335    pa_drop_caps();
336
337    pa_set_env("USER", PA_SYSTEM_USER);
338    pa_set_env("USERNAME", PA_SYSTEM_USER);
339    pa_set_env("LOGNAME", PA_SYSTEM_USER);
340    pa_set_env("HOME", PA_SYSTEM_RUNTIME_PATH);
341
342    /* Relevant for pa_runtime_path() */
343    if (!getenv("PULSE_RUNTIME_PATH"))
344        pa_set_env("PULSE_RUNTIME_PATH", PA_SYSTEM_RUNTIME_PATH);
345
346    if (!getenv("PULSE_CONFIG_PATH"))
347        pa_set_env("PULSE_CONFIG_PATH", PA_SYSTEM_CONFIG_PATH);
348
349    if (!getenv("PULSE_STATE_PATH"))
350        pa_set_env("PULSE_STATE_PATH", PA_SYSTEM_STATE_PATH);
351
352    pa_log_info("Successfully changed user to \"" PA_SYSTEM_USER "\".");
353
354    return 0;
355}
356
357#else /* HAVE_PWD_H && HAVE_GRP_H */
358
359static int change_user(void) {
360    pa_log(_("System wide mode unsupported on this platform."));
361    return -1;
362}
363
364#endif /* HAVE_PWD_H && HAVE_GRP_H */
365
366#ifdef HAVE_SYS_RESOURCE_H
367
368static int set_one_rlimit(const pa_rlimit *r, int resource, const char *name) {
369    struct rlimit rl;
370    pa_assert(r);
371
372    if (!r->is_set)
373        return 0;
374
375    rl.rlim_cur = rl.rlim_max = r->value;
376
377    if (setrlimit(resource, &rl) < 0) {
378        pa_log_info("setrlimit(%s, (%u, %u)) failed: %s", name, (unsigned) r->value, (unsigned) r->value, pa_cstrerror(errno));
379        return -1;
380    }
381
382    return 0;
383}
384
385static void set_all_rlimits(const pa_daemon_conf *conf) {
386    set_one_rlimit(&conf->rlimit_fsize, RLIMIT_FSIZE, "RLIMIT_FSIZE");
387    set_one_rlimit(&conf->rlimit_data, RLIMIT_DATA, "RLIMIT_DATA");
388    set_one_rlimit(&conf->rlimit_stack, RLIMIT_STACK, "RLIMIT_STACK");
389    set_one_rlimit(&conf->rlimit_core, RLIMIT_CORE, "RLIMIT_CORE");
390#ifdef RLIMIT_RSS
391    set_one_rlimit(&conf->rlimit_rss, RLIMIT_RSS, "RLIMIT_RSS");
392#endif
393#ifdef RLIMIT_NPROC
394    set_one_rlimit(&conf->rlimit_nproc, RLIMIT_NPROC, "RLIMIT_NPROC");
395#endif
396#ifdef RLIMIT_NOFILE
397    set_one_rlimit(&conf->rlimit_nofile, RLIMIT_NOFILE, "RLIMIT_NOFILE");
398#endif
399#ifdef RLIMIT_MEMLOCK
400    set_one_rlimit(&conf->rlimit_memlock, RLIMIT_MEMLOCK, "RLIMIT_MEMLOCK");
401#endif
402#ifdef RLIMIT_AS
403    set_one_rlimit(&conf->rlimit_as, RLIMIT_AS, "RLIMIT_AS");
404#endif
405#ifdef RLIMIT_LOCKS
406    set_one_rlimit(&conf->rlimit_locks, RLIMIT_LOCKS, "RLIMIT_LOCKS");
407#endif
408#ifdef RLIMIT_SIGPENDING
409    set_one_rlimit(&conf->rlimit_sigpending, RLIMIT_SIGPENDING, "RLIMIT_SIGPENDING");
410#endif
411#ifdef RLIMIT_MSGQUEUE
412    set_one_rlimit(&conf->rlimit_msgqueue, RLIMIT_MSGQUEUE, "RLIMIT_MSGQUEUE");
413#endif
414#ifdef RLIMIT_NICE
415    set_one_rlimit(&conf->rlimit_nice, RLIMIT_NICE, "RLIMIT_NICE");
416#endif
417#ifdef RLIMIT_RTPRIO
418    set_one_rlimit(&conf->rlimit_rtprio, RLIMIT_RTPRIO, "RLIMIT_RTPRIO");
419#endif
420#ifdef RLIMIT_RTTIME
421    set_one_rlimit(&conf->rlimit_rttime, RLIMIT_RTTIME, "RLIMIT_RTTIME");
422#endif
423}
424#endif
425
426static char *check_configured_address(void) {
427    char *default_server = NULL;
428    pa_client_conf *c = pa_client_conf_new();
429
430    pa_client_conf_load(c, true, true);
431
432    if (c->default_server && *c->default_server)
433        default_server = pa_xstrdup(c->default_server);
434
435    pa_client_conf_free(c);
436
437    return default_server;
438}
439
440#ifdef HAVE_DBUS
441static pa_dbus_connection *register_dbus_name(pa_core *c, DBusBusType bus, const char* name) {
442    DBusError error;
443    pa_dbus_connection *conn;
444
445    dbus_error_init(&error);
446
447    if (!(conn = pa_dbus_bus_get(c, bus, &error)) || dbus_error_is_set(&error)) {
448        pa_log_warn("Unable to contact D-Bus: %s: %s", error.name, error.message);
449        goto fail;
450    }
451
452    if (dbus_bus_request_name(pa_dbus_connection_get(conn), name, DBUS_NAME_FLAG_DO_NOT_QUEUE, &error) == DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
453        pa_log_debug("Got %s!", name);
454        return conn;
455    }
456
457    if (dbus_error_is_set(&error))
458        pa_log_error("Failed to acquire %s: %s: %s", name, error.name, error.message);
459    else
460        pa_log_error("D-Bus name %s already taken.", name);
461
462    /* PA cannot be started twice by the same user and hence we can
463     * ignore mostly the case that a name is already taken. */
464
465fail:
466    if (conn)
467        pa_dbus_connection_unref(conn);
468
469    dbus_error_free(&error);
470    return NULL;
471}
472#endif
473
474#ifdef OS_IS_WIN32
475#define SVC_NAME "PulseAudio"
476static bool is_svc = true;
477static int argc;
478static char **argv;
479static int real_main(int s_argc, char *s_argv[]);
480static SERVICE_STATUS_HANDLE svc_status;
481
482DWORD svc_callback(DWORD ctl, DWORD evt, LPVOID data, LPVOID userdata) {
483    pa_mainloop **m = userdata;
484    switch (ctl) {
485    case SERVICE_CONTROL_STOP:
486    case SERVICE_CONTROL_SHUTDOWN:
487        if (m) {
488            pa_log_info("Exiting.");
489            pa_mainloop_get_api(*m)->quit(pa_mainloop_get_api(*m), 0);
490        }
491        return NO_ERROR;
492    case SERVICE_CONTROL_INTERROGATE:
493        return NO_ERROR;
494    }
495    return ERROR_CALL_NOT_IMPLEMENTED;
496}
497
498int main(int p_argc, char *p_argv[]) {
499    argc = p_argc;
500    argv = p_argv;
501    if (StartServiceCtrlDispatcherA((SERVICE_TABLE_ENTRYA[]){
502        {SVC_NAME, (LPSERVICE_MAIN_FUNCTIONA) real_main},
503        {0},
504    })) return 0;
505    is_svc = false;
506    return real_main(0, NULL);
507}
508
509static int real_main(int s_argc, char *s_argv[]) {
510#else
511int main(int argc, char *argv[]) {
512#endif
513    pa_core *c = NULL;
514    pa_strbuf *buf = NULL;
515    pa_daemon_conf *conf = NULL;
516    pa_mainloop *mainloop = NULL;
517    char *s;
518    char *configured_address;
519    int r = 0, retval = 1, d = 0;
520    bool valid_pid_file = false;
521    bool ltdl_init = false;
522    int n_fds = 0, *passed_fds = NULL;
523    const char *e;
524#ifdef HAVE_FORK
525    int daemon_pipe[2] = { -1, -1 };
526    int daemon_pipe2[2] = { -1, -1 };
527#endif
528    int autospawn_fd = -1;
529    bool autospawn_locked = false;
530#ifdef HAVE_DBUS
531    pa_dbusobj_server_lookup *server_lookup = NULL; /* /org/pulseaudio/server_lookup */
532    pa_dbus_connection *lookup_service_bus = NULL; /* Always the user bus. */
533    pa_dbus_connection *server_bus = NULL; /* The bus where we reserve org.pulseaudio.Server, either the user or the system bus. */
534    bool start_server;
535#endif
536
537#ifdef OS_IS_WIN32
538    if (is_svc && !(svc_status = RegisterServiceCtrlHandlerExA(SVC_NAME, (LPHANDLER_FUNCTION_EX) svc_callback, &mainloop))) {
539        pa_log("Failed to register service control handler.");
540        goto finish;
541    }
542
543    if (is_svc) {
544        SetServiceStatus(svc_status, &(SERVICE_STATUS){
545            .dwServiceType      = SERVICE_WIN32,
546            .dwCurrentState     = SERVICE_START_PENDING,
547            .dwControlsAccepted = 0,
548            .dwWin32ExitCode    = NO_ERROR,
549            .dwWaitHint         = 3000,
550        });
551    }
552#endif
553
554    pa_log_set_ident("pulseaudio");
555    pa_log_set_level(PA_LOG_NOTICE);
556    pa_log_set_flags(PA_LOG_COLORS|PA_LOG_PRINT_FILE|PA_LOG_PRINT_LEVEL, PA_LOG_RESET);
557
558#if !defined(HAVE_BIND_NOW) && defined(__linux__) && defined(__OPTIMIZE__)
559    /*
560       Disable lazy relocations to make usage of external libraries
561       more deterministic for our RT threads. We abuse __OPTIMIZE__ as
562       a check whether we are a debug build or not. This all is
563       admittedly a bit snake-oilish.
564    */
565
566    if (!getenv("LD_BIND_NOW")) {
567        char *rp;
568        char *canonical_rp;
569
570        /* We have to execute ourselves, because the libc caches the
571         * value of $LD_BIND_NOW on initialization. */
572
573        pa_set_env("LD_BIND_NOW", "1");
574
575        if ((canonical_rp = pa_realpath(PA_BINARY))) {
576
577            if ((rp = pa_readlink("/proc/self/exe"))) {
578
579                if (pa_streq(rp, canonical_rp))
580                    pa_assert_se(execv(rp, argv) == 0);
581                else
582                    pa_log_warn("/proc/self/exe does not point to %s, cannot self execute. Are you playing games?", canonical_rp);
583
584                pa_xfree(rp);
585
586            } else
587                pa_log_warn("Couldn't read /proc/self/exe, cannot self execute. Running in a chroot()?");
588
589            pa_xfree(canonical_rp);
590
591        } else
592            pa_log_warn("Couldn't canonicalize binary path, cannot self execute.");
593    }
594#endif
595
596#ifdef HAVE_SYSTEMD_DAEMON
597    n_fds = sd_listen_fds(0);
598    if (n_fds > 0) {
599        int i = n_fds;
600
601        passed_fds = pa_xnew(int, n_fds+2);
602        passed_fds[n_fds] = passed_fds[n_fds+1] = -1;
603        while (i--)
604            passed_fds[i] = SD_LISTEN_FDS_START + i;
605    }
606#endif
607
608    if (!passed_fds) {
609        n_fds = 0;
610        passed_fds = pa_xnew(int, 2);
611        passed_fds[0] = passed_fds[1] = -1;
612    }
613
614    if ((e = getenv("PULSE_PASSED_FD"))) {
615        int passed_fd = atoi(e);
616        if (passed_fd > 2)
617            passed_fds[n_fds] = passed_fd;
618    }
619
620    /* We might be autospawned, in which case have no idea in which
621     * context we have been started. Let's cleanup our execution
622     * context as good as possible */
623
624    pa_reset_personality();
625    pa_drop_root();
626    pa_close_allv(passed_fds);
627    pa_xfree(passed_fds);
628    pa_reset_sigs(-1);
629    pa_unblock_sigs(-1);
630    pa_reset_priority();
631
632    /* Load locale from the environment. */
633    setlocale(LC_ALL, "");
634
635    /* Set LC_NUMERIC to C so that floating point strings are consistently
636     * formatted and parsed across locales. */
637    setlocale(LC_NUMERIC, "C");
638
639    pa_init_i18n();
640
641    conf = pa_daemon_conf_new();
642
643    if (pa_daemon_conf_load(conf, NULL) < 0)
644        goto finish;
645
646    if (pa_daemon_conf_env(conf) < 0)
647        goto finish;
648
649    if (pa_cmdline_parse(conf, argc, argv, &d) < 0) {
650        pa_log(_("Failed to parse command line."));
651        goto finish;
652    }
653
654    if (conf->log_target)
655        pa_log_set_target(conf->log_target);
656    else {
657        pa_log_target target = { .type = PA_LOG_STDERR, .file = NULL };
658        pa_log_set_target(&target);
659    }
660
661    pa_log_set_level(conf->log_level);
662    if (conf->log_meta)
663        pa_log_set_flags(PA_LOG_PRINT_META, PA_LOG_SET);
664    if (conf->log_time)
665        pa_log_set_flags(PA_LOG_PRINT_TIME, PA_LOG_SET);
666    pa_log_set_show_backtrace(conf->log_backtrace);
667
668#ifdef HAVE_DBUS
669    /* conf->system_instance and conf->local_server_type control almost the
670     * same thing; make them agree about what is requested. */
671    switch (conf->local_server_type) {
672        case PA_SERVER_TYPE_UNSET:
673            conf->local_server_type = conf->system_instance ? PA_SERVER_TYPE_SYSTEM : PA_SERVER_TYPE_USER;
674            break;
675        case PA_SERVER_TYPE_USER:
676        case PA_SERVER_TYPE_NONE:
677            conf->system_instance = false;
678            break;
679        case PA_SERVER_TYPE_SYSTEM:
680            conf->system_instance = true;
681            break;
682        default:
683            pa_assert_not_reached();
684    }
685
686    start_server = conf->local_server_type == PA_SERVER_TYPE_USER || (getuid() == 0 && conf->local_server_type == PA_SERVER_TYPE_SYSTEM);
687
688    if (!start_server && conf->local_server_type == PA_SERVER_TYPE_SYSTEM) {
689        pa_log_notice(_("System mode refused for non-root user. Only starting the D-Bus server lookup service."));
690        conf->system_instance = false;
691    }
692#endif
693
694    LTDL_SET_PRELOADED_SYMBOLS();
695    pa_ltdl_init();
696    ltdl_init = true;
697
698    if (conf->dl_search_path)
699        lt_dlsetsearchpath(conf->dl_search_path);
700
701#ifdef OS_IS_WIN32
702    {
703        WSADATA data;
704        WSAStartup(MAKEWORD(2, 0), &data);
705    }
706#endif
707
708    pa_random_seed();
709
710    switch (conf->cmd) {
711        case PA_CMD_DUMP_MODULES:
712            pa_dump_modules(conf, argc-d, argv+d);
713            retval = 0;
714            goto finish;
715
716        case PA_CMD_DUMP_CONF: {
717
718            if (d < argc) {
719                pa_log("Too many arguments.");
720                goto finish;
721            }
722
723            s = pa_daemon_conf_dump(conf);
724            fputs(s, stdout);
725            pa_xfree(s);
726            retval = 0;
727            goto finish;
728        }
729
730        case PA_CMD_DUMP_RESAMPLE_METHODS: {
731            int i;
732
733            if (d < argc) {
734                pa_log("Too many arguments.");
735                goto finish;
736            }
737
738            for (i = 0; i < PA_RESAMPLER_MAX; i++)
739                if (pa_resample_method_supported(i))
740                    printf("%s\n", pa_resample_method_to_string(i));
741
742            retval = 0;
743            goto finish;
744        }
745
746        case PA_CMD_HELP :
747            pa_cmdline_help(argv[0]);
748            retval = 0;
749            goto finish;
750
751        case PA_CMD_VERSION :
752
753            if (d < argc) {
754                pa_log("Too many arguments.");
755                goto finish;
756            }
757
758            printf(PACKAGE_NAME" "PACKAGE_VERSION"\n");
759            retval = 0;
760            goto finish;
761
762        case PA_CMD_CHECK: {
763            pid_t pid;
764
765            if (d < argc) {
766                pa_log("Too many arguments.");
767                goto finish;
768            }
769
770            if (pa_pid_file_check_running(&pid, "pulseaudio") < 0)
771                pa_log_info("Daemon not running");
772            else {
773                pa_log_info("Daemon running as PID %u", pid);
774                retval = 0;
775            }
776
777            goto finish;
778
779        }
780        case PA_CMD_KILL:
781
782            if (d < argc) {
783                pa_log("Too many arguments.");
784                goto finish;
785            }
786
787            if (pa_pid_file_kill(SIGINT, NULL, "pulseaudio") < 0)
788                pa_log(_("Failed to kill daemon: %s"), pa_cstrerror(errno));
789            else
790                retval = 0;
791
792            goto finish;
793
794        case PA_CMD_CLEANUP_SHM:
795
796            if (d < argc) {
797                pa_log("Too many arguments.");
798                goto finish;
799            }
800
801            if (pa_shm_cleanup() >= 0)
802                retval = 0;
803
804            goto finish;
805
806        default:
807            pa_assert(conf->cmd == PA_CMD_DAEMON || conf->cmd == PA_CMD_START);
808    }
809
810    if (d < argc) {
811        pa_log("Too many arguments.");
812        goto finish;
813    }
814
815#ifdef HAVE_GETUID
816    if (getuid() == 0 && !conf->system_instance)
817        pa_log_warn(_("This program is not intended to be run as root (unless --system is specified)."));
818#ifndef HAVE_DBUS /* A similar, only a notice worthy check was done earlier, if D-Bus is enabled. */
819    else if (getuid() != 0 && conf->system_instance) {
820        pa_log(_("Root privileges required."));
821        goto finish;
822    }
823#endif
824#endif  /* HAVE_GETUID */
825
826    if (conf->cmd == PA_CMD_START && conf->system_instance) {
827        pa_log(_("--start not supported for system instances."));
828        goto finish;
829    }
830
831    if (conf->cmd == PA_CMD_START && (configured_address = check_configured_address())) {
832        /* There is an server address in our config, but where did it come from?
833         * By default a standard X11 login will load module-x11-publish which will
834         * inject PULSE_SERVER X11 property. If the PA daemon crashes, we will end
835         * up hitting this code path. So we have to check to see if our configured_address
836         * is the same as the value that would go into this property so that we can
837         * recover (i.e. autospawn) from a crash.
838         */
839        char *ufn;
840        bool start_anyway = false;
841
842        if ((ufn = pa_runtime_path(PA_NATIVE_DEFAULT_UNIX_SOCKET))) {
843            char *id;
844
845            if ((id = pa_machine_id())) {
846                pa_strlist *server_list;
847                char formatted_ufn[256];
848
849                pa_snprintf(formatted_ufn, sizeof(formatted_ufn), "{%s}unix:%s", id, ufn);
850                pa_xfree(id);
851
852                if ((server_list = pa_strlist_parse(configured_address))) {
853                    char *u = NULL;
854
855                    /* We only need to check the first server */
856                    server_list = pa_strlist_pop(server_list, &u);
857                    pa_strlist_free(server_list);
858
859                    start_anyway = (u && pa_streq(formatted_ufn, u));
860                    pa_xfree(u);
861                }
862            }
863            pa_xfree(ufn);
864        }
865
866        if (!start_anyway) {
867            pa_log_notice(_("User-configured server at %s, refusing to start/autospawn."), configured_address);
868            pa_xfree(configured_address);
869            retval = 0;
870            goto finish;
871        }
872
873        pa_log_notice(_("User-configured server at %s, which appears to be local. Probing deeper."), configured_address);
874        pa_xfree(configured_address);
875    }
876
877    if (conf->system_instance && !conf->disallow_exit)
878        pa_log_warn(_("Running in system mode, but --disallow-exit not set."));
879
880    if (conf->system_instance && !conf->disallow_module_loading)
881        pa_log_warn(_("Running in system mode, but --disallow-module-loading not set."));
882
883    if (conf->system_instance && !conf->disable_shm) {
884        pa_log_notice(_("Running in system mode, forcibly disabling SHM mode."));
885        conf->disable_shm = true;
886    }
887
888    if (conf->system_instance && conf->exit_idle_time >= 0) {
889        pa_log_notice(_("Running in system mode, forcibly disabling exit idle time."));
890        conf->exit_idle_time = -1;
891    }
892
893    if (conf->cmd == PA_CMD_START) {
894        /* If we shall start PA only when it is not running yet, we
895         * first take the autospawn lock to make things
896         * synchronous. */
897
898        /* This locking and thread synchronisation code doesn't work reliably
899         * on kFreeBSD (Debian bug #705435), or in upstream FreeBSD ports
900         * (bug reference: ports/128947, patched in SVN r231972). */
901#if !defined(__FreeBSD__) && !defined(__FreeBSD_kernel__)
902        if ((autospawn_fd = pa_autospawn_lock_init()) < 0) {
903            pa_log("Failed to initialize autospawn lock");
904            goto finish;
905        }
906
907        if ((pa_autospawn_lock_acquire(true) < 0)) {
908            pa_log("Failed to acquire autospawn lock");
909            goto finish;
910        }
911
912        autospawn_locked = true;
913#endif
914    }
915
916    if (conf->daemonize) {
917#ifdef HAVE_FORK
918        pid_t child;
919#endif
920
921        if (pa_stdio_acquire() < 0) {
922            pa_log(_("Failed to acquire stdio."));
923            goto finish;
924        }
925
926#ifdef HAVE_FORK
927        if (pipe(daemon_pipe) < 0) {
928            pa_log(_("pipe() failed: %s"), pa_cstrerror(errno));
929            goto finish;
930        }
931
932        if ((child = fork()) < 0) {
933            pa_log(_("fork() failed: %s"), pa_cstrerror(errno));
934            pa_close_pipe(daemon_pipe);
935            goto finish;
936        }
937
938        if (child != 0) {
939            ssize_t n;
940            /* Father */
941
942            pa_assert_se(pa_close(daemon_pipe[1]) == 0);
943            daemon_pipe[1] = -1;
944
945            if ((n = pa_loop_read(daemon_pipe[0], &retval, sizeof(retval), NULL)) != sizeof(retval)) {
946
947                if (n < 0)
948                    pa_log(_("read() failed: %s"), pa_cstrerror(errno));
949
950                retval = 1;
951            }
952
953            if (retval)
954                pa_log(_("Daemon startup failed."));
955            else
956                pa_log_info("Daemon startup successful.");
957
958            goto finish;
959        }
960
961        if (autospawn_fd >= 0) {
962            /* The lock file is unlocked from the parent, so we need
963             * to close it in the child */
964
965            pa_autospawn_lock_release();
966            pa_autospawn_lock_done(true);
967
968            autospawn_locked = false;
969            autospawn_fd = -1;
970        }
971
972        pa_assert_se(pa_close(daemon_pipe[0]) == 0);
973        daemon_pipe[0] = -1;
974#endif
975
976        if (!conf->log_target) {
977#ifdef HAVE_SYSTEMD_JOURNAL
978            pa_log_target target = { .type = PA_LOG_JOURNAL, .file = NULL };
979#else
980            pa_log_target target = { .type = PA_LOG_SYSLOG, .file = NULL };
981#endif
982            pa_log_set_target(&target);
983        }
984
985#ifdef HAVE_SETSID
986        if (setsid() < 0) {
987            pa_log(_("setsid() failed: %s"), pa_cstrerror(errno));
988            goto finish;
989        }
990#endif
991
992#ifdef HAVE_FORK
993        /* We now are a session and process group leader. Let's fork
994         * again and let the father die, so that we'll become a
995         * process that can never acquire a TTY again, in a session and
996         * process group without leader */
997
998        if (pipe(daemon_pipe2) < 0) {
999            pa_log(_("pipe() failed: %s"), pa_cstrerror(errno));
1000            goto finish;
1001        }
1002
1003        if ((child = fork()) < 0) {
1004            pa_log(_("fork() failed: %s"), pa_cstrerror(errno));
1005            pa_close_pipe(daemon_pipe2);
1006            goto finish;
1007        }
1008
1009        if (child != 0) {
1010            ssize_t n;
1011            /* Father */
1012
1013            pa_assert_se(pa_close(daemon_pipe2[1]) == 0);
1014            daemon_pipe2[1] = -1;
1015
1016            if ((n = pa_loop_read(daemon_pipe2[0], &retval, sizeof(retval), NULL)) != sizeof(retval)) {
1017
1018                if (n < 0)
1019                    pa_log(_("read() failed: %s"), pa_cstrerror(errno));
1020
1021                retval = 1;
1022            }
1023
1024            /* We now have to take care of signalling the first fork with
1025             * the return value we've received from this fork... */
1026            pa_assert(daemon_pipe[1] >= 0);
1027
1028            pa_loop_write(daemon_pipe[1], &retval, sizeof(retval), NULL);
1029            pa_close(daemon_pipe[1]);
1030            daemon_pipe[1] = -1;
1031
1032            goto finish;
1033        }
1034
1035        pa_assert_se(pa_close(daemon_pipe2[0]) == 0);
1036        daemon_pipe2[0] = -1;
1037
1038        /* We no longer need the (first) daemon_pipe as it's handled in our child above */
1039        pa_close_pipe(daemon_pipe);
1040#endif
1041
1042#ifdef SIGTTOU
1043        signal(SIGTTOU, SIG_IGN);
1044#endif
1045#ifdef SIGTTIN
1046        signal(SIGTTIN, SIG_IGN);
1047#endif
1048#ifdef SIGTSTP
1049        signal(SIGTSTP, SIG_IGN);
1050#endif
1051
1052        pa_nullify_stdfds();
1053    }
1054
1055    pa_set_env_and_record("PULSE_INTERNAL", "1");
1056    pa_assert_se(chdir("/") == 0);
1057    umask(0077);
1058
1059#ifdef HAVE_SYS_RESOURCE_H
1060    set_all_rlimits(conf);
1061#endif
1062    pa_rtclock_hrtimer_enable();
1063
1064    if (conf->high_priority)
1065        pa_raise_priority(conf->nice_level);
1066
1067    if (conf->system_instance)
1068        if (change_user() < 0)
1069            goto finish;
1070
1071    pa_set_env_and_record("PULSE_SYSTEM", conf->system_instance ? "1" : "0");
1072
1073    pa_log_info("This is PulseAudio %s", PACKAGE_VERSION);
1074    pa_log_debug("Compilation CFLAGS: %s", PA_CFLAGS);
1075
1076#ifdef HAVE_LIBSAMPLERATE
1077    pa_log_warn("Compiled with DEPRECATED libsamplerate support!");
1078#endif
1079
1080    s = pa_uname_string();
1081    pa_log_debug("Running on host: %s", s);
1082    pa_xfree(s);
1083
1084    pa_log_debug("Found %u CPUs.", pa_ncpus());
1085
1086    pa_log_info("Page size is %zu bytes", pa_page_size());
1087
1088#ifdef HAVE_VALGRIND_MEMCHECK_H
1089    pa_log_debug("Compiled with Valgrind support: yes");
1090#else
1091    pa_log_debug("Compiled with Valgrind support: no");
1092#endif
1093
1094    pa_log_debug("Running in valgrind mode: %s", pa_yes_no(pa_in_valgrind()));
1095
1096    pa_log_debug("Running in VM: %s", pa_yes_no(pa_running_in_vm()));
1097
1098#ifdef HAVE_RUNNING_FROM_BUILD_TREE
1099    pa_log_debug("Running from build tree: %s", pa_yes_no(pa_run_from_build_tree()));
1100#else
1101    pa_log_debug("Running from build tree: no");
1102#endif
1103
1104#ifdef __OPTIMIZE__
1105    pa_log_debug("Optimized build: yes");
1106#else
1107    pa_log_debug("Optimized build: no");
1108#endif
1109
1110#ifdef NDEBUG
1111    pa_log_debug("NDEBUG defined, all asserts disabled.");
1112#elif defined(FASTPATH)
1113    pa_log_debug("FASTPATH defined, only fast path asserts disabled.");
1114#else
1115    pa_log_debug("All asserts enabled.");
1116#endif
1117
1118    if (!(s = pa_machine_id())) {
1119        pa_log(_("Failed to get machine ID"));
1120        goto finish;
1121    }
1122    pa_log_info("Machine ID is %s.", s);
1123    pa_xfree(s);
1124
1125    if ((s = pa_session_id())) {
1126        pa_log_info("Session ID is %s.", s);
1127        pa_xfree(s);
1128    }
1129
1130    if (!(s = pa_get_runtime_dir()))
1131        goto finish;
1132    pa_log_info("Using runtime directory %s.", s);
1133    pa_xfree(s);
1134
1135    if (!(s = pa_get_state_dir()))
1136        goto finish;
1137    pa_log_info("Using state directory %s.", s);
1138    pa_xfree(s);
1139
1140    pa_log_info("Using modules directory %s.", conf->dl_search_path);
1141
1142    pa_log_info("Running in system mode: %s", pa_yes_no(pa_in_system_mode()));
1143
1144    if (pa_in_system_mode())
1145        pa_log_warn(_("OK, so you are running PA in system mode. Please make sure that you actually do want to do that.\n"
1146                      "Please read http://www.freedesktop.org/wiki/Software/PulseAudio/Documentation/User/WhatIsWrongWithSystemWide/ for an explanation why system mode is usually a bad idea."));
1147
1148    if (conf->use_pid_file) {
1149        int z;
1150
1151        if ((z = pa_pid_file_create("pulseaudio")) != 0) {
1152
1153            if (conf->cmd == PA_CMD_START && z > 0) {
1154                /* If we are already running and with are run in
1155                 * --start mode, then let's return this as success. */
1156
1157                retval = 0;
1158                goto finish;
1159            }
1160
1161            pa_log(_("pa_pid_file_create() failed."));
1162            goto finish;
1163        }
1164
1165        valid_pid_file = true;
1166    }
1167
1168    pa_disable_sigpipe();
1169
1170    if (pa_rtclock_hrtimer())
1171        pa_log_info("System supports high resolution timers");
1172    else
1173        pa_log_info("System appears to not support high resolution timers");
1174
1175    if (conf->lock_memory) {
1176#if defined(HAVE_SYS_MMAN_H) && !defined(__ANDROID__)
1177        if (mlockall(MCL_FUTURE) < 0)
1178            pa_log_warn("mlockall() failed: %s", pa_cstrerror(errno));
1179        else
1180            pa_log_info("Successfully locked process into memory.");
1181#else
1182        pa_log_warn("Memory locking requested but not supported on platform.");
1183#endif
1184    }
1185
1186    pa_memtrap_install();
1187
1188    pa_assert_se(mainloop = pa_mainloop_new());
1189
1190    if (!(c = pa_core_new(pa_mainloop_get_api(mainloop), !conf->disable_shm,
1191                          !conf->disable_shm && !conf->disable_memfd && pa_memfd_is_locally_supported(),
1192                          conf->shm_size))) {
1193        pa_log(_("pa_core_new() failed."));
1194        goto finish;
1195    }
1196
1197    c->default_sample_spec = conf->default_sample_spec;
1198    c->alternate_sample_rate = conf->alternate_sample_rate;
1199    c->default_channel_map = conf->default_channel_map;
1200    c->default_n_fragments = conf->default_n_fragments;
1201    c->default_fragment_size_msec = conf->default_fragment_size_msec;
1202    c->deferred_volume_safety_margin_usec = conf->deferred_volume_safety_margin_usec;
1203    c->deferred_volume_extra_delay_usec = conf->deferred_volume_extra_delay_usec;
1204    c->lfe_crossover_freq = conf->lfe_crossover_freq;
1205    c->exit_idle_time = conf->exit_idle_time;
1206    c->scache_idle_time = conf->scache_idle_time;
1207    c->resample_method = conf->resample_method;
1208    c->realtime_priority = conf->realtime_priority;
1209    c->realtime_scheduling = conf->realtime_scheduling;
1210    c->avoid_resampling = conf->avoid_resampling;
1211    c->disable_remixing = conf->disable_remixing;
1212    c->remixing_use_all_sink_channels = conf->remixing_use_all_sink_channels;
1213    c->remixing_produce_lfe = conf->remixing_produce_lfe;
1214    c->remixing_consume_lfe = conf->remixing_consume_lfe;
1215    c->deferred_volume = conf->deferred_volume;
1216    c->running_as_daemon = conf->daemonize;
1217    c->disallow_exit = conf->disallow_exit;
1218    c->flat_volumes = conf->flat_volumes;
1219    c->rescue_streams = conf->rescue_streams;
1220#ifdef HAVE_DBUS
1221    c->server_type = conf->local_server_type;
1222#endif
1223
1224    pa_core_check_idle(c);
1225
1226    c->state = PA_CORE_RUNNING;
1227
1228    pa_cpu_init(&c->cpu_info);
1229
1230    pa_assert_se(pa_signal_init(pa_mainloop_get_api(mainloop)) == 0);
1231    pa_signal_new(SIGINT, signal_callback, c);
1232    pa_signal_new(SIGTERM, signal_callback, c);
1233#ifdef SIGUSR1
1234    pa_signal_new(SIGUSR1, signal_callback, c);
1235#endif
1236#ifdef SIGUSR2
1237    pa_signal_new(SIGUSR2, signal_callback, c);
1238#endif
1239#ifdef SIGHUP
1240    pa_signal_new(SIGHUP, signal_callback, c);
1241#endif
1242
1243    if (!conf->no_cpu_limit)
1244        pa_assert_se(pa_cpu_limit_init(pa_mainloop_get_api(mainloop)) == 0);
1245
1246    buf = pa_strbuf_new();
1247
1248#ifdef HAVE_DBUS
1249    pa_assert_se(dbus_threads_init_default());
1250
1251    if (start_server)
1252#endif
1253    {
1254        const char *command_source = NULL;
1255
1256        if (conf->load_default_script_file) {
1257            FILE *f;
1258
1259            if ((f = pa_daemon_conf_open_default_script_file(conf))) {
1260                r = pa_cli_command_execute_file_stream(c, f, buf, &conf->fail);
1261                fclose(f);
1262                command_source = pa_daemon_conf_get_default_script_file(conf);
1263            }
1264        }
1265
1266        if (r >= 0) {
1267            r = pa_cli_command_execute(c, conf->script_commands, buf, &conf->fail);
1268            command_source = _("command line arguments");
1269        }
1270
1271        pa_log_error("%s", s = pa_strbuf_to_string_free(buf));
1272        pa_xfree(s);
1273
1274        if (r < 0 && conf->fail) {
1275            pa_log(_("Failed to initialize daemon due to errors while executing startup commands. Source of commands: %s"), command_source);
1276            goto finish;
1277        }
1278
1279        if (!c->modules || pa_idxset_size(c->modules) == 0) {
1280            pa_log(_("Daemon startup without any loaded modules, refusing to work."));
1281            goto finish;
1282        }
1283#ifdef HAVE_DBUS
1284    } else {
1285        /* When we just provide the D-Bus server lookup service, we don't want
1286         * any modules to be loaded. We haven't loaded any so far, so one might
1287         * think there's no way to contact the server, but receiving certain
1288         * signals could still cause modules to load. */
1289        conf->disallow_module_loading = true;
1290#endif
1291    }
1292
1293    /* We completed the initial module loading, so let's disable it
1294     * from now on, if requested */
1295    c->disallow_module_loading = conf->disallow_module_loading;
1296
1297#ifdef HAVE_DBUS
1298    if (!conf->system_instance) {
1299        if ((server_lookup = pa_dbusobj_server_lookup_new(c))) {
1300            if (!(lookup_service_bus = register_dbus_name(c, DBUS_BUS_SESSION, "org.PulseAudio1")))
1301                goto finish;
1302        }
1303    }
1304
1305    if (start_server)
1306        server_bus = register_dbus_name(c, conf->system_instance ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, "org.pulseaudio.Server");
1307#endif
1308
1309#ifdef HAVE_FORK
1310    if (daemon_pipe2[1] >= 0) {
1311        int ok = 0;
1312        pa_loop_write(daemon_pipe2[1], &ok, sizeof(ok), NULL);
1313        pa_close(daemon_pipe2[1]);
1314        daemon_pipe2[1] = -1;
1315    }
1316#endif
1317
1318    pa_log_info("Daemon startup complete.");
1319
1320#ifdef HAVE_SYSTEMD_DAEMON
1321    sd_notify(0, "READY=1");
1322#endif
1323
1324#ifdef OS_IS_WIN32
1325    if (is_svc) {
1326        SetServiceStatus(svc_status, &(SERVICE_STATUS){
1327            .dwServiceType      = SERVICE_WIN32,
1328            .dwCurrentState     = SERVICE_RUNNING,
1329            .dwControlsAccepted = SERVICE_ACCEPT_STOP|SERVICE_ACCEPT_SHUTDOWN,
1330            .dwWin32ExitCode    = NO_ERROR,
1331            .dwWaitHint         = 0,
1332        });
1333    }
1334#endif
1335
1336    retval = 0;
1337    if (pa_mainloop_run(mainloop, &retval) < 0)
1338        goto finish;
1339
1340    pa_log_info("Daemon shutdown initiated.");
1341
1342#ifdef HAVE_SYSTEMD_DAEMON
1343    sd_notify(0, "STOPPING=1");
1344#endif
1345
1346#ifdef OS_IS_WIN32
1347    if (is_svc) {
1348        SetServiceStatus(svc_status, &(SERVICE_STATUS){
1349            .dwServiceType      = SERVICE_WIN32,
1350            .dwCurrentState     = SERVICE_STOP_PENDING,
1351            .dwControlsAccepted = 0,
1352            .dwWin32ExitCode    = NO_ERROR,
1353            .dwWaitHint         = 2000,
1354        });
1355    }
1356#endif
1357
1358finish:
1359#ifdef HAVE_DBUS
1360    if (server_bus)
1361        pa_dbus_connection_unref(server_bus);
1362    if (lookup_service_bus)
1363        pa_dbus_connection_unref(lookup_service_bus);
1364    if (server_lookup)
1365        pa_dbusobj_server_lookup_free(server_lookup);
1366#endif
1367
1368    if (autospawn_fd >= 0) {
1369        if (autospawn_locked)
1370            pa_autospawn_lock_release();
1371
1372        pa_autospawn_lock_done(false);
1373    }
1374
1375    if (c) {
1376        /* Ensure all the modules/samples are unloaded when the core is still ref'ed,
1377         * as unlink callback hooks in modules may need the core to be ref'ed */
1378        pa_module_unload_all(c);
1379        pa_scache_free_all(c);
1380
1381        pa_core_unref(c);
1382        pa_log_info("Daemon terminated.");
1383    }
1384
1385    if (!conf->no_cpu_limit)
1386        pa_cpu_limit_done();
1387
1388    pa_signal_done();
1389
1390#ifdef HAVE_FORK
1391    /* If we have daemon_pipe[1] still open, this means we've failed after
1392     * the first fork, but before the second. Therefore just write to it. */
1393    if (daemon_pipe[1] >= 0)
1394        pa_loop_write(daemon_pipe[1], &retval, sizeof(retval), NULL);
1395    else if (daemon_pipe2[1] >= 0)
1396        pa_loop_write(daemon_pipe2[1], &retval, sizeof(retval), NULL);
1397
1398    pa_close_pipe(daemon_pipe2);
1399    pa_close_pipe(daemon_pipe);
1400#endif
1401
1402    if (mainloop)
1403        pa_mainloop_free(mainloop);
1404
1405    if (conf)
1406        pa_daemon_conf_free(conf);
1407
1408    if (valid_pid_file)
1409        pa_pid_file_remove();
1410
1411    /* This has no real purpose except making things valgrind-clean */
1412    pa_unset_env_recorded();
1413
1414#ifdef OS_IS_WIN32
1415    WSACleanup();
1416#endif
1417
1418    if (ltdl_init)
1419        pa_ltdl_done();
1420
1421#ifdef HAVE_DBUS
1422    dbus_shutdown();
1423#endif
1424
1425#ifdef OS_IS_WIN32
1426    if (is_svc) {
1427        SetServiceStatus(svc_status, &(SERVICE_STATUS){
1428            .dwServiceType      = SERVICE_WIN32,
1429            .dwCurrentState     = SERVICE_STOPPED,
1430            .dwControlsAccepted = 0,
1431            .dwWin32ExitCode    = retval ? ERROR_PROCESS_ABORTED : NO_ERROR,
1432            .dwWaitHint         = 0,
1433        });
1434    }
1435#endif
1436
1437    return retval;
1438}
1439