2 This file is part of PulseAudio.
4 Copyright 2004-2006 Lennart Poettering
5 Copyright 2004 Joe Marcus Clarke
6 Copyright 2006-2007 Pierre Ossman <ossman@cendio.se> for Cendio AB
8 PulseAudio is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as
10 published by the Free Software Foundation; either version 2.1 of the
11 License, or (at your option) any later version.
13 PulseAudio is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public
19 License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
37 #include <sys/types.h>
41 #ifdef HAVE_LANGINFO_H
46 #include <sys/utsname.h>
49 #if defined(HAVE_REGEX_H)
51 #elif defined(HAVE_PCREPOSIX_H)
52 #include <pcreposix.h>
64 #ifdef HAVE_SYS_RESOURCE_H
65 #include <sys/resource.h>
68 #ifdef HAVE_SYS_CAPABILITY_H
69 #include <sys/capability.h>
72 #ifdef HAVE_SYS_MMAN_H
101 #ifdef HAVE_LIBSAMPLERATE
102 #include <samplerate.h>
106 #include <pulsecore/rtkit.h>
109 #if defined(__linux__) && !defined(__ANDROID__)
110 #include <sys/personality.h>
117 #include <pulse/xmalloc.h>
118 #include <pulse/util.h>
119 #include <pulse/utf8.h>
121 #include <pulsecore/core-error.h>
122 #include <pulsecore/socket.h>
123 #include <pulsecore/log.h>
124 #include <pulsecore/macro.h>
125 #include <pulsecore/thread.h>
126 #include <pulsecore/strbuf.h>
127 #include <pulsecore/usergroup.h>
128 #include <pulsecore/strlist.h>
129 #include <pulsecore/pipe.h>
130 #include <pulsecore/once.h>
132 #include "core-util.h"
134 /* Not all platforms have this */
136 #define MSG_NOSIGNAL 0
139 #define NEWLINE "\r\n"
140 #define WHITESPACE "\n\r \t"
142 static pa_strlist *recorded_env = NULL;
145 static fd_set nonblocking_fds;
150 /* Returns the directory of the current DLL, with '/bin/' removed if it is the last component */
151 char *pa_win32_get_toplevel(HANDLE handle) {
152 static char *toplevel = NULL;
155 char library_path[MAX_PATH];
158 if (!GetModuleFileName(handle, library_path, MAX_PATH))
161 toplevel = pa_xstrdup(library_path);
163 p = strrchr(toplevel, PA_PATH_SEP_CHAR);
167 p = strrchr(toplevel, PA_PATH_SEP_CHAR);
168 if (p && pa_streq(p + 1, "bin"))
175 char *pa_win32_get_system_appdata() {
176 static char appdata[MAX_PATH] = {0};
178 if (!*appdata && SHGetFolderPathAndSubDirA(NULL, CSIDL_COMMON_APPDATA|CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, "PulseAudio", appdata) != S_OK)
186 static void set_nonblock(int fd, bool nonblock) {
192 pa_assert_se((v = fcntl(fd, F_GETFL)) >= 0);
197 nv = v & ~O_NONBLOCK;
200 pa_assert_se(fcntl(fd, F_SETFL, nv) >= 0);
202 #elif defined(OS_IS_WIN32)
210 if (ioctlsocket(fd, FIONBIO, &arg) < 0) {
211 pa_assert_se(WSAGetLastError() == WSAENOTSOCK);
212 pa_log_warn("Only sockets can be made non-blocking!");
216 /* There is no method to query status, so we remember all fds */
218 FD_SET(fd, &nonblocking_fds);
220 FD_CLR(fd, &nonblocking_fds);
222 pa_log_warn("Non-blocking I/O not supported.!");
227 /** Make a file descriptor nonblock. Doesn't do any error checking */
228 void pa_make_fd_nonblock(int fd) {
229 set_nonblock(fd, true);
232 /** Make a file descriptor blocking. Doesn't do any error checking */
233 void pa_make_fd_block(int fd) {
234 set_nonblock(fd, false);
237 /** Query if a file descriptor is non-blocking */
238 bool pa_is_fd_nonblock(int fd) {
244 pa_assert_se((v = fcntl(fd, F_GETFL)) >= 0);
246 return !!(v & O_NONBLOCK);
248 #elif defined(OS_IS_WIN32)
249 return !!FD_ISSET(fd, &nonblocking_fds);
256 /* Set the FD_CLOEXEC flag for a fd */
257 void pa_make_fd_cloexec(int fd) {
264 v = fcntl(fd, F_GETFD, 0);
266 pa_log_warn("fcntl(%d, F_GETFD, 0) failed: %s", fd, pa_cstrerror(errno));
270 if (!(v & FD_CLOEXEC)) {
271 v = fcntl(fd, F_SETFD, v|FD_CLOEXEC);
273 pa_log_warn("fcntl(%d, F_SETFD, v|FD_CLOEXEC) failed: %s", fd, pa_cstrerror(errno));
278 pa_assert_se((v = fcntl(fd, F_GETFD, 0)) >= 0);
280 if (!(v & FD_CLOEXEC))
281 pa_assert_se(fcntl(fd, F_SETFD, v|FD_CLOEXEC) >= 0);
282 #endif /* __TIZEN__ */
287 /** Creates a directory securely. Will create parent directories recursively if
288 * required. This will not update permissions on parent directories if they
289 * already exist, however. */
290 int pa_make_secure_dir(const char* dir, mode_t m, uid_t uid, gid_t gid, bool update_perms) {
303 u = umask((~m) & 0777);
309 if (r < 0 && errno == ENOENT && retry) {
310 /* If a parent directory in the path doesn't exist, try to create that
311 * first, then try again. */
312 pa_make_secure_parent_dir(dir, m, uid, gid, false);
317 if (r < 0 && errno != EEXIST)
320 #if defined(HAVE_FSTAT) && !defined(OS_IS_WIN32)
336 if (fstat(fd, &st) < 0) {
337 pa_assert_se(pa_close(fd) >= 0);
341 if (!S_ISDIR(st.st_mode)) {
342 pa_assert_se(pa_close(fd) >= 0);
348 pa_assert_se(pa_close(fd) >= 0);
353 if (uid == (uid_t) -1)
355 if (gid == (gid_t) -1)
357 if (((st.st_uid != uid) || (st.st_gid != gid)) && fchown(fd, uid, gid) < 0) {
358 pa_assert_se(pa_close(fd) >= 0);
364 if ((st.st_mode & 07777) != m && fchmod(fd, m) < 0) {
365 pa_assert_se(pa_close(fd) >= 0);
370 pa_assert_se(pa_close(fd) >= 0);
373 pa_log_warn("Secure directory creation not supported on this platform.");
386 /* Return a newly allocated sting containing the parent directory of the specified file */
387 char *pa_parent_dir(const char *fn) {
388 char *slash, *dir = pa_xstrdup(fn);
390 if ((slash = (char*) pa_path_get_filename(dir)) == dir) {
400 /* Creates a the parent directory of the specified path securely */
401 int pa_make_secure_parent_dir(const char *fn, mode_t m, uid_t uid, gid_t gid, bool update_perms) {
405 if (!(dir = pa_parent_dir(fn)))
408 if (pa_make_secure_dir(dir, m, uid, gid, update_perms) < 0)
418 /** Platform independent read function. Necessary since not all
419 * systems treat all file descriptors equal. If type is
420 * non-NULL it is used to cache the type of the fd. This is
421 * useful for making sure that only a single syscall is executed per
422 * function call. The variable pointed to should be initialized to 0
424 ssize_t pa_read(int fd, void *buf, size_t count, int *type) {
428 if (!type || *type == 0) {
431 if ((r = recv(fd, buf, count, 0)) >= 0)
434 if (WSAGetLastError() != WSAENOTSOCK) {
435 errno = WSAGetLastError();
436 if (errno == WSAEWOULDBLOCK)
450 if ((r = read(fd, buf, count)) < 0)
458 /** Similar to pa_read(), but handles writes */
459 ssize_t pa_write(int fd, const void *buf, size_t count, int *type) {
461 if (!type || *type == 0) {
465 if ((r = send(fd, buf, count, MSG_NOSIGNAL)) < 0) {
477 if (WSAGetLastError() != WSAENOTSOCK) {
478 errno = WSAGetLastError();
479 if (errno == WSAEWOULDBLOCK)
484 if (errno != ENOTSOCK)
495 if ((r = write(fd, buf, count)) < 0)
503 /** Calls read() in a loop. Makes sure that as much as 'size' bytes,
504 * unless EOF is reached or an error occurred */
505 ssize_t pa_loop_read(int fd, void*data, size_t size, int *type) {
521 if ((r = pa_read(fd, data, size, type)) < 0)
528 data = (uint8_t*) data + r;
535 /** Similar to pa_loop_read(), but wraps write() */
536 ssize_t pa_loop_write(int fd, const void*data, size_t size, int *type) {
552 if ((r = pa_write(fd, data, size, type)) < 0)
559 data = (const uint8_t*) data + r;
566 /** Platform independent close function. Necessary since not all
567 * systems treat all file descriptors equal. */
568 int pa_close(int fd) {
573 FD_CLR(fd, &nonblocking_fds);
575 if ((ret = closesocket(fd)) == 0)
578 if (WSAGetLastError() != WSAENOTSOCK) {
579 errno = WSAGetLastError();
587 if ((r = close(fd)) < 0)
595 /* Print a warning messages in case that the given signal is not
596 * blocked or trapped */
597 void pa_check_signal_is_blocked(int sig) {
598 #ifdef HAVE_SIGACTION
602 /* If POSIX threads are supported use thread-aware
603 * pthread_sigmask() function, to check if the signal is
604 * blocked. Otherwise fall back to sigprocmask() */
607 if (pthread_sigmask(SIG_SETMASK, NULL, &set) < 0) {
609 if (sigprocmask(SIG_SETMASK, NULL, &set) < 0) {
610 pa_log("sigprocmask(): %s", pa_cstrerror(errno));
617 if (sigismember(&set, sig))
620 /* Check whether the signal is trapped */
622 if (sigaction(sig, NULL, &sa) < 0) {
623 pa_log("sigaction(): %s", pa_cstrerror(errno));
627 if (sa.sa_handler != SIG_DFL)
630 pa_log_warn("%s is not trapped. This might cause malfunction!", pa_sig2str(sig));
631 #else /* HAVE_SIGACTION */
632 pa_log_warn("%s might not be trapped. This might cause malfunction!", pa_sig2str(sig));
636 /* The following function is based on an example from the GNU libc
637 * documentation. This function is similar to GNU's asprintf(). */
638 char *pa_sprintf_malloc(const char *format, ...) {
648 c = pa_xrealloc(c, size);
650 va_start(ap, format);
651 r = vsnprintf(c, size, format, ap);
656 if (r > -1 && (size_t) r < size)
659 if (r > -1) /* glibc 2.1 */
666 /* Same as the previous function, but use a va_list instead of an
668 char *pa_vsprintf_malloc(const char *format, va_list ap) {
678 c = pa_xrealloc(c, size);
681 r = vsnprintf(c, size, format, aq);
686 if (r > -1 && (size_t) r < size)
689 if (r > -1) /* glibc 2.1 */
696 /* Similar to OpenBSD's strlcpy() function */
697 char *pa_strlcpy(char *b, const char *s, size_t l) {
715 #ifdef HAVE_SYS_RESOURCE_H
716 static int set_nice(int nice_level) {
722 dbus_error_init(&error);
725 #ifdef HAVE_SYS_RESOURCE_H
726 if (setpriority(PRIO_PROCESS, 0, nice_level) >= 0) {
727 pa_log_debug("setpriority() worked.");
733 /* Try to talk to RealtimeKit */
735 if (!(bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error))) {
736 pa_log("Failed to connect to system bus: %s", error.message);
737 dbus_error_free(&error);
742 /* We need to disable exit on disconnect because otherwise
743 * dbus_shutdown will kill us. See
744 * https://bugs.freedesktop.org/show_bug.cgi?id=16924 */
745 dbus_connection_set_exit_on_disconnect(bus, FALSE);
747 r = rtkit_make_high_priority(bus, 0, nice_level);
748 dbus_connection_close(bus);
749 dbus_connection_unref(bus);
752 pa_log_debug("RealtimeKit worked.");
763 /* Raise the priority of the current process as much as possible that
764 * is <= the specified nice level..*/
765 int pa_raise_priority(int nice_level) {
767 #ifdef HAVE_SYS_RESOURCE_H
770 if (set_nice(nice_level) >= 0) {
771 pa_log_info("Successfully gained nice level %i.", nice_level);
775 for (n = nice_level+1; n < 0; n++)
776 if (set_nice(n) >= 0) {
777 pa_log_info("Successfully acquired nice level %i, which is lower than the requested %i.", n, nice_level);
781 pa_log_info("Failed to acquire high-priority scheduling: %s", pa_cstrerror(errno));
786 if (nice_level < 0) {
787 if (!SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS)) {
788 pa_log_warn("SetPriorityClass() failed: 0x%08lX", GetLastError());
793 pa_log_info("Successfully gained high priority class.");
800 /* Reset the priority to normal, inverting the changes made by
801 * pa_raise_priority() and pa_thread_make_realtime()*/
802 void pa_reset_priority(void) {
803 #ifdef HAVE_SYS_RESOURCE_H
804 struct sched_param sp;
806 setpriority(PRIO_PROCESS, 0, 0);
809 pthread_setschedparam(pthread_self(), SCHED_OTHER, &sp);
813 SetPriorityClass(GetCurrentProcess(), NORMAL_PRIORITY_CLASS);
817 /* Check whenever any substring in v matches the provided regex. */
818 int pa_match(const char *expr, const char *v) {
819 #if defined(HAVE_REGEX_H) || defined(HAVE_PCREPOSIX_H)
827 if (regcomp(&re, expr, REG_NOSUB|REG_EXTENDED) != 0) {
832 if ((k = regexec(&re, v, 0, NULL, 0)) == 0)
834 else if (k == REG_NOMATCH)
851 /* Check whenever the provided regex pattern is valid. */
852 bool pa_is_regex_valid(const char *expr) {
853 #if defined(HAVE_REGEX_H) || defined(HAVE_PCREPOSIX_H)
856 if (expr == NULL || regcomp(&re, expr, REG_NOSUB|REG_EXTENDED) != 0) {
867 /* Try to parse a boolean string value.*/
868 int pa_parse_boolean(const char *v) {
871 /* First we check language independent */
872 if (pa_streq(v, "1") || !strcasecmp(v, "y") || !strcasecmp(v, "t")
873 || !strcasecmp(v, "yes") || !strcasecmp(v, "true") || !strcasecmp(v, "on"))
875 else if (pa_streq(v, "0") || !strcasecmp(v, "n") || !strcasecmp(v, "f")
876 || !strcasecmp(v, "no") || !strcasecmp(v, "false") || !strcasecmp(v, "off"))
879 #ifdef HAVE_LANGINFO_H
882 /* And then we check language dependent */
883 if ((expr = nl_langinfo(YESEXPR)))
885 if (pa_match(expr, v) > 0)
888 if ((expr = nl_langinfo(NOEXPR)))
890 if (pa_match(expr, v) > 0)
899 /* Try to parse a volume string to pa_volume_t. The allowed formats are:
900 * db, % and unsigned integer */
901 int pa_parse_volume(const char *v, pa_volume_t *volume) {
912 if (len <= 0 || len >= 64)
915 memcpy(str, v, len + 1);
917 if (str[len - 1] == '%') {
919 if (pa_atod(str, &d) < 0)
922 d = d / 100 * PA_VOLUME_NORM;
924 if (d < 0 || d > PA_VOLUME_MAX)
931 if (len > 2 && (str[len - 1] == 'b' || str[len - 1] == 'B') &&
932 (str[len - 2] == 'd' || str[len - 2] == 'D')) {
934 if (pa_atod(str, &d) < 0)
937 if (d > pa_sw_volume_to_dB(PA_VOLUME_MAX))
940 *volume = pa_sw_volume_from_dB(d);
944 if (pa_atou(v, &i) < 0 || !PA_VOLUME_IS_VALID(i))
951 /* Split the specified string wherever one of the characters in delimiter
952 * occurs. Each time it is called returns a newly allocated string
953 * with pa_xmalloc(). The variable state points to, should be
954 * initialized to NULL before the first call. */
955 char *pa_split(const char *c, const char *delimiter, const char**state) {
956 const char *current = *state ? *state : c;
962 l = strcspn(current, delimiter);
968 return pa_xstrndup(current, l);
971 /* Split the specified string wherever one of the characters in delimiter
972 * occurs. Each time it is called returns a pointer to the substring within the
973 * string and the length in 'n'. Note that the resultant string cannot be used
974 * as-is without the length parameter, since it is merely pointing to a point
975 * within the original string. The variable state points to, should be
976 * initialized to NULL before the first call. */
977 const char *pa_split_in_place(const char *c, const char *delimiter, size_t *n, const char**state) {
978 const char *current = *state ? *state : c;
984 l = strcspn(current, delimiter);
994 /* Split a string into words. Otherwise similar to pa_split(). */
995 char *pa_split_spaces(const char *c, const char **state) {
996 const char *current = *state ? *state : c;
999 if (!*current || *c == 0)
1002 current += strspn(current, WHITESPACE);
1003 l = strcspn(current, WHITESPACE);
1007 return pa_xstrndup(current, l);
1010 /* Similar to pa_split_spaces, except this returns a string in-place.
1011 Returned string is generally not NULL-terminated.
1012 See pa_split_in_place(). */
1013 const char *pa_split_spaces_in_place(const char *c, size_t *n, const char **state) {
1014 const char *current = *state ? *state : c;
1017 if (!*current || *c == 0)
1020 current += strspn(current, WHITESPACE);
1021 l = strcspn(current, WHITESPACE);
1029 PA_STATIC_TLS_DECLARE(signame, pa_xfree);
1031 /* Return the name of an UNIX signal. Similar to Solaris sig2str() */
1032 const char *pa_sig2str(int sig) {
1045 char buf[SIG2STR_MAX];
1047 if (sig2str(sig, buf) == 0) {
1048 pa_xfree(PA_STATIC_TLS_GET(signame));
1049 t = pa_sprintf_malloc("SIG%s", buf);
1050 PA_STATIC_TLS_SET(signame, t);
1058 case SIGHUP: return "SIGHUP";
1060 case SIGINT: return "SIGINT";
1062 case SIGQUIT: return "SIGQUIT";
1064 case SIGILL: return "SIGULL";
1066 case SIGTRAP: return "SIGTRAP";
1068 case SIGABRT: return "SIGABRT";
1070 case SIGBUS: return "SIGBUS";
1072 case SIGFPE: return "SIGFPE";
1074 case SIGKILL: return "SIGKILL";
1077 case SIGUSR1: return "SIGUSR1";
1079 case SIGSEGV: return "SIGSEGV";
1081 case SIGUSR2: return "SIGUSR2";
1084 case SIGPIPE: return "SIGPIPE";
1087 case SIGALRM: return "SIGALRM";
1089 case SIGTERM: return "SIGTERM";
1091 case SIGSTKFLT: return "SIGSTKFLT";
1094 case SIGCHLD: return "SIGCHLD";
1097 case SIGCONT: return "SIGCONT";
1100 case SIGSTOP: return "SIGSTOP";
1103 case SIGTSTP: return "SIGTSTP";
1106 case SIGTTIN: return "SIGTTIN";
1109 case SIGTTOU: return "SIGTTOU";
1112 case SIGURG: return "SIGURG";
1115 case SIGXCPU: return "SIGXCPU";
1118 case SIGXFSZ: return "SIGXFSZ";
1121 case SIGVTALRM: return "SIGVTALRM";
1124 case SIGPROF: return "SIGPROF";
1127 case SIGWINCH: return "SIGWINCH";
1130 case SIGIO: return "SIGIO";
1133 case SIGPWR: return "SIGPWR";
1136 case SIGSYS: return "SIGSYS";
1141 if (sig >= SIGRTMIN && sig <= SIGRTMAX) {
1142 pa_xfree(PA_STATIC_TLS_GET(signame));
1143 t = pa_sprintf_malloc("SIGRTMIN+%i", sig - SIGRTMIN);
1144 PA_STATIC_TLS_SET(signame, t);
1153 pa_xfree(PA_STATIC_TLS_GET(signame));
1154 t = pa_sprintf_malloc("SIG%i", sig);
1155 PA_STATIC_TLS_SET(signame, t);
1161 /* Check whether the specified GID and the group name match */
1162 static int is_group(gid_t gid, const char *name) {
1163 struct group *group = NULL;
1167 if (!(group = pa_getgrgid_malloc(gid))) {
1171 pa_log("pa_getgrgid_malloc(%u): %s", gid, pa_cstrerror(errno));
1176 r = pa_streq(name, group->gr_name);
1179 pa_getgrgid_free(group);
1184 /* Check the current user is member of the specified group */
1185 int pa_own_uid_in_group(const char *name, gid_t *gid) {
1186 GETGROUPS_T *gids, tgid;
1187 long n = sysconf(_SC_NGROUPS_MAX);
1192 gids = pa_xmalloc(sizeof(GETGROUPS_T) * (size_t) n);
1194 if ((n = getgroups((int) n, gids)) < 0) {
1195 pa_log("getgroups(): %s", pa_cstrerror(errno));
1199 for (i = 0; i < n; i++) {
1201 if ((k = is_group(gids[i], name)) < 0)
1210 if ((k = is_group(tgid = getgid(), name)) < 0)
1226 /* Check whether the specific user id is a member of the specified group */
1227 int pa_uid_in_group(uid_t uid, const char *name) {
1228 struct group *group = NULL;
1233 if (!(group = pa_getgrnam_malloc(name))) {
1240 for (i = group->gr_mem; *i; i++) {
1241 struct passwd *pw = NULL;
1244 if (!(pw = pa_getpwnam_malloc(*i)))
1247 if (pw->pw_uid == uid)
1250 pa_getpwnam_free(pw);
1257 pa_getgrnam_free(group);
1262 /* Get the GID of a given group, return (gid_t) -1 on failure. */
1263 gid_t pa_get_gid_of_group(const char *name) {
1264 gid_t ret = (gid_t) -1;
1265 struct group *gr = NULL;
1268 if (!(gr = pa_getgrnam_malloc(name))) {
1277 pa_getgrnam_free(gr);
1281 int pa_check_in_group(gid_t g) {
1282 gid_t gids[NGROUPS_MAX];
1285 if ((r = getgroups(NGROUPS_MAX, gids)) < 0)
1295 #else /* HAVE_GRP_H */
1297 int pa_own_uid_in_group(const char *name, gid_t *gid) {
1303 int pa_uid_in_group(uid_t uid, const char *name) {
1308 gid_t pa_get_gid_of_group(const char *name) {
1313 int pa_check_in_group(gid_t g) {
1320 /* Lock or unlock a file entirely.
1321 (advisory on UNIX, mandatory on Windows) */
1322 int pa_lock_fd(int fd, int b) {
1324 struct flock f_lock;
1326 /* Try a R/W lock first */
1328 f_lock.l_type = (short) (b ? F_WRLCK : F_UNLCK);
1329 f_lock.l_whence = SEEK_SET;
1333 if (fcntl(fd, F_SETLKW, &f_lock) >= 0)
1336 /* Perhaps the file descriptor was opened for read only, than try again with a read lock. */
1337 if (b && errno == EBADF) {
1338 f_lock.l_type = F_RDLCK;
1339 if (fcntl(fd, F_SETLKW, &f_lock) >= 0)
1343 pa_log("%slock: %s", !b ? "un" : "", pa_cstrerror(errno));
1347 HANDLE h = (HANDLE) _get_osfhandle(fd);
1349 if (b && LockFile(h, 0, 0, 0xFFFFFFFF, 0xFFFFFFFF))
1351 if (!b && UnlockFile(h, 0, 0, 0xFFFFFFFF, 0xFFFFFFFF))
1354 pa_log("%slock failed: 0x%08lX", !b ? "un" : "", GetLastError());
1356 /* FIXME: Needs to set errno! */
1362 /* Remove trailing newlines from a string */
1363 char* pa_strip_nl(char *s) {
1366 s[strcspn(s, NEWLINE)] = 0;
1370 char *pa_strip(char *s) {
1373 /* Drops trailing whitespace. Modifies the string in
1374 * place. Returns pointer to first non-space character */
1376 s += strspn(s, WHITESPACE);
1378 for (e = s; *e; e++)
1379 if (!strchr(WHITESPACE, *e))
1390 /* Create a temporary lock file and lock it. */
1391 int pa_lock_lockfile(const char *fn) {
1398 if ((fd = pa_open_cloexec(fn, O_CREAT|O_RDWR
1402 , S_IRUSR|S_IWUSR)) < 0) {
1403 pa_log_warn("Failed to create lock file '%s': %s", fn, pa_cstrerror(errno));
1407 if (pa_lock_fd(fd, 1) < 0) {
1408 pa_log_warn("Failed to lock file '%s'.", fn);
1412 if (fstat(fd, &st) < 0) {
1413 pa_log_warn("Failed to fstat() file '%s': %s", fn, pa_cstrerror(errno));
1417 /* Check whether the file has been removed meanwhile. When yes,
1418 * restart this loop, otherwise, we're done */
1419 if (st.st_nlink >= 1)
1422 if (pa_lock_fd(fd, 0) < 0) {
1423 pa_log_warn("Failed to unlock file '%s'.", fn);
1427 if (pa_close(fd) < 0) {
1428 pa_log_warn("Failed to close file '%s': %s", fn, pa_cstrerror(errno));
1439 int saved_errno = errno;
1441 errno = saved_errno;
1447 /* Unlock a temporary lock file */
1448 int pa_unlock_lockfile(const char *fn, int fd) {
1453 if (unlink(fn) < 0) {
1454 pa_log_warn("Unable to remove lock file '%s': %s", fn, pa_cstrerror(errno));
1459 if (pa_lock_fd(fd, 0) < 0) {
1460 pa_log_warn("Failed to unlock file '%s'.", fn);
1464 if (pa_close(fd) < 0) {
1465 pa_log_warn("Failed to close '%s': %s", fn, pa_cstrerror(errno));
1472 static int check_ours(const char *p) {
1477 if (stat(p, &st) < 0)
1481 if (st.st_uid != getuid() && st.st_uid != 0)
1488 static char *get_pulse_home(void) {
1492 h = pa_get_home_dir_malloc();
1494 pa_log_error("Failed to get home directory.");
1499 if (t < 0 && t != -ENOENT) {
1500 pa_log_error("Home directory not accessible: %s", pa_cstrerror(-t));
1505 /* If the old directory exists, use it. */
1506 ret = pa_sprintf_malloc("%s" PA_PATH_SEP ".pulse", h);
1508 if (access(ret, F_OK) >= 0)
1512 /* Otherwise go for the XDG compliant directory. */
1513 if (pa_get_config_home_dir(&ret) < 0)
1519 char *pa_get_state_dir(void) {
1522 /* The state directory shall contain dynamic data that should be
1523 * kept across reboots, and is private to this user */
1525 if (!(d = pa_xstrdup(getenv("PULSE_STATE_PATH"))))
1526 if (!(d = get_pulse_home()))
1529 /* If PULSE_STATE_PATH and PULSE_RUNTIME_PATH point to the same
1530 * dir then this will break. */
1532 if (pa_make_secure_dir(d, 0700U, (uid_t) -1, (gid_t) -1, true) < 0) {
1533 pa_log_error("Failed to create secure directory (%s): %s", d, pa_cstrerror(errno));
1541 char *pa_get_home_dir_malloc(void) {
1543 size_t allocated = 128;
1546 homedir = pa_xmalloc(allocated);
1548 if (!pa_get_home_dir(homedir, allocated)) {
1553 if (strlen(homedir) < allocated - 1)
1563 int pa_append_to_home_dir(const char *path, char **_r) {
1569 home_dir = pa_get_home_dir_malloc();
1571 pa_log("Failed to get home directory.");
1572 return -PA_ERR_NOENTITY;
1575 *_r = pa_sprintf_malloc("%s" PA_PATH_SEP "%s", home_dir, path);
1580 int pa_get_config_home_dir(char **_r) {
1586 e = getenv("XDG_CONFIG_HOME");
1588 *_r = pa_sprintf_malloc("%s" PA_PATH_SEP "pulse", e);
1592 home_dir = pa_get_home_dir_malloc();
1594 return -PA_ERR_NOENTITY;
1596 *_r = pa_sprintf_malloc("%s" PA_PATH_SEP ".config" PA_PATH_SEP "pulse", home_dir);
1601 int pa_get_data_home_dir(char **_r) {
1607 e = getenv("XDG_DATA_HOME");
1609 if (pa_is_path_absolute(e)) {
1610 *_r = pa_sprintf_malloc("%s" PA_PATH_SEP "pulseaudio", e);
1614 pa_log_warn("Ignored non-absolute XDG_DATA_HOME value '%s'", e);
1617 home_dir = pa_get_home_dir_malloc();
1619 return -PA_ERR_NOENTITY;
1621 *_r = pa_sprintf_malloc("%s" PA_PATH_SEP ".local" PA_PATH_SEP "share" PA_PATH_SEP "pulseaudio", home_dir);
1626 int pa_get_data_dirs(pa_dynarray **_r) {
1628 const char *def = "/usr/local/share/:/usr/share/";
1630 const char *split_state = NULL;
1636 e = getenv("XDG_DATA_DIRS");
1637 p = e && *e ? e : def;
1639 paths = pa_dynarray_new((pa_free_cb_t) pa_xfree);
1641 while ((n = pa_split(p, ":", &split_state))) {
1644 if (!pa_is_path_absolute(n)) {
1645 pa_log_warn("Ignored non-absolute path '%s' in XDG_DATA_DIRS", n);
1650 path = pa_sprintf_malloc("%s" PA_PATH_SEP "pulseaudio", n);
1652 pa_dynarray_append(paths, path);
1655 if (pa_dynarray_size(paths) == 0) {
1656 pa_log_warn("XDG_DATA_DIRS contains no valid paths");
1657 pa_dynarray_free(paths);
1658 return -PA_ERR_INVALID;
1665 int pa_append_to_config_home_dir(const char *path, char **_r) {
1667 char *config_home_dir;
1672 r = pa_get_config_home_dir(&config_home_dir);
1676 *_r = pa_sprintf_malloc("%s" PA_PATH_SEP "%s", config_home_dir, path);
1677 pa_xfree(config_home_dir);
1681 char *pa_get_binary_name_malloc(void) {
1683 size_t allocated = 128;
1686 t = pa_xmalloc(allocated);
1688 if (!pa_get_binary_name(t, allocated)) {
1694 if (strnlen(t, allocated - 1) < allocated - 1)
1696 if (strlen(t) < allocated - 1)
1707 static char* make_random_dir(mode_t m) {
1708 static const char table[] =
1709 "abcdefghijklmnopqrstuvwxyz"
1710 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1716 fn = pa_sprintf_malloc("%s" PA_PATH_SEP "pulse-XXXXXXXXXXXX", pa_get_temp_dir());
1717 pathlen = strlen(fn);
1725 for (i = pathlen - 12; i < pathlen; i++)
1726 fn[i] = table[rand() % (sizeof(table)-1)];
1728 u = umask((~m) & 0777);
1735 saved_errno = errno;
1737 errno = saved_errno;
1742 if (errno != EEXIST) {
1743 pa_log_error("Failed to create random directory %s: %s", fn, pa_cstrerror(errno));
1750 static int make_random_dir_and_link(mode_t m, const char *k) {
1753 if (!(p = make_random_dir(m)))
1757 if (symlink(p, k) < 0) {
1758 int saved_errno = errno;
1760 if (errno != EEXIST)
1761 pa_log_error("Failed to symlink %s to %s: %s", k, p, pa_cstrerror(errno));
1766 errno = saved_errno;
1778 char *pa_get_runtime_dir(void) {
1779 char *d, *k = NULL, *p = NULL, *t = NULL, *mid;
1782 /* The runtime directory shall contain dynamic data that needs NOT
1783 * to be kept across reboots and is usually private to the user,
1784 * except in system mode, where it might be accessible by other
1785 * users, too. Since we need POSIX locking and UNIX sockets in
1786 * this directory, we try XDG_RUNTIME_DIR first, and if that isn't
1787 * set create a directory in $HOME and link it to a random subdir
1788 * in /tmp, if it was not explicitly configured. */
1790 m = pa_in_system_mode() ? 0755U : 0700U;
1792 /* Use the explicitly configured value if it is set */
1793 d = getenv("PULSE_RUNTIME_PATH");
1796 if (pa_make_secure_dir(d, m, (uid_t) -1, (gid_t) -1, true) < 0) {
1797 pa_log_error("Failed to create secure directory (%s): %s", d, pa_cstrerror(errno));
1801 return pa_xstrdup(d);
1804 /* Use the XDG standard for the runtime directory. */
1805 d = getenv("XDG_RUNTIME_DIR");
1809 if (stat(d, &st) == 0 && st.st_uid != getuid()) {
1810 pa_log(_("XDG_RUNTIME_DIR (%s) is not owned by us (uid %d), but by uid %d! "
1811 "(This could e.g. happen if you try to connect to a non-root PulseAudio as a root user, over the native protocol. Don't do that.)"),
1812 d, getuid(), st.st_uid);
1817 k = pa_sprintf_malloc("%s" PA_PATH_SEP "pulse", d);
1819 if (pa_make_secure_dir(k, m, (uid_t) -1, (gid_t) -1, true) < 0) {
1820 pa_log_error("Failed to create secure directory (%s): %s", k, pa_cstrerror(errno));
1827 /* XDG_RUNTIME_DIR wasn't set, use the old legacy fallback */
1828 d = get_pulse_home();
1832 if (pa_make_secure_dir(d, m, (uid_t) -1, (gid_t) -1, true) < 0) {
1833 pa_log_error("Failed to create secure directory (%s): %s", d, pa_cstrerror(errno));
1838 mid = pa_machine_id();
1844 k = pa_sprintf_malloc("%s" PA_PATH_SEP "%s-runtime", d, mid);
1849 /* OK, first let's check if the "runtime" symlink already exists */
1854 if (errno != ENOENT) {
1855 pa_log_error("Failed to stat runtime directory %s: %s", k, pa_cstrerror(errno));
1860 /* Hmm, so the runtime directory didn't exist yet, so let's
1861 * create one in /tmp and symlink that to it */
1863 if (make_random_dir_and_link(0700, k) < 0) {
1865 /* Mhmm, maybe another process was quicker than us,
1866 * let's check if that was valid */
1867 if (errno == EEXIST)
1873 /* No symlink possible, so let's just create the runtime directly
1874 * Do not check again if it exists since it cannot be a symlink */
1875 if (mkdir(k) < 0 && errno != EEXIST)
1882 /* Make sure that this actually makes sense */
1883 if (!pa_is_path_absolute(p)) {
1884 pa_log_error("Path %s in link %s is not absolute.", p, k);
1889 /* Hmm, so this symlink is still around, make sure nobody fools us */
1893 if (lstat(p, &st) < 0) {
1895 if (errno != ENOENT) {
1896 pa_log_error("Failed to stat runtime directory %s: %s", p, pa_cstrerror(errno));
1902 if (S_ISDIR(st.st_mode) &&
1903 (st.st_uid == getuid()) &&
1904 ((st.st_mode & 0777) == 0700)) {
1910 pa_log_info("Hmm, runtime path exists, but points to an invalid directory. Changing runtime directory.");
1918 /* Hmm, so the link points to some nonexisting or invalid
1919 * dir. Let's replace it by a new link. We first create a
1920 * temporary link and then rename that to allow concurrent
1921 * execution of this function. */
1923 t = pa_sprintf_malloc("%s.tmp", k);
1925 if (make_random_dir_and_link(0700, t) < 0) {
1927 if (errno != EEXIST) {
1928 pa_log_error("Failed to symlink %s: %s", t, pa_cstrerror(errno));
1935 /* Hmm, someone else was quicker then us. Let's give
1936 * him some time to finish, and retry. */
1941 /* OK, we succeeded in creating the temporary symlink, so
1942 * let's rename it */
1943 if (rename(t, k) < 0) {
1944 pa_log_error("Failed to rename %s to %s: %s", t, k, pa_cstrerror(errno));
1960 /* Try to open a configuration file. If "env" is specified, open the
1961 * value of the specified environment variable. Otherwise look for a
1962 * file "local" in the home directory or a file "global" in global
1963 * file system. If "result" is non-NULL, a pointer to a newly
1964 * allocated buffer containing the used configuration file is
1966 FILE *pa_open_config_file(const char *global, const char *local, const char *env, char **result) {
1970 if (env && (fn = getenv(env))) {
1971 if ((f = pa_fopen_cloexec(fn, "r"))) {
1973 *result = pa_xstrdup(fn);
1978 pa_log_warn("Failed to open configuration file '%s': %s", fn, pa_cstrerror(errno));
1987 if ((e = getenv("PULSE_CONFIG_PATH"))) {
1988 fn = lfn = pa_sprintf_malloc("%s" PA_PATH_SEP "%s", e, local);
1989 f = pa_fopen_cloexec(fn, "r");
1990 } else if ((h = pa_get_home_dir_malloc())) {
1991 fn = lfn = pa_sprintf_malloc("%s" PA_PATH_SEP ".pulse" PA_PATH_SEP "%s", h, local);
1992 f = pa_fopen_cloexec(fn, "r");
1995 fn = lfn = pa_sprintf_malloc("%s" PA_PATH_SEP ".config/pulse" PA_PATH_SEP "%s", h, local);
1996 f = pa_fopen_cloexec(fn, "r");
2004 *result = pa_xstrdup(fn);
2010 if (errno != ENOENT) {
2011 pa_log_warn("Failed to open configuration file '%s': %s", fn, pa_cstrerror(errno));
2023 if (strncmp(global, PA_DEFAULT_CONFIG_DIR, strlen(PA_DEFAULT_CONFIG_DIR)) == 0)
2024 gfn = pa_sprintf_malloc("%s" PA_PATH_SEP "etc" PA_PATH_SEP "pulse%s",
2025 pa_win32_get_toplevel(NULL),
2026 global + strlen(PA_DEFAULT_CONFIG_DIR));
2029 gfn = pa_xstrdup(global);
2031 if ((f = pa_fopen_cloexec(gfn, "r"))) {
2046 char *pa_find_config_file(const char *global, const char *local, const char *env) {
2049 if (env && (fn = getenv(env))) {
2050 if (access(fn, R_OK) == 0)
2051 return pa_xstrdup(fn);
2053 pa_log_warn("Failed to access configuration file '%s': %s", fn, pa_cstrerror(errno));
2062 if ((e = getenv("PULSE_CONFIG_PATH")))
2063 fn = lfn = pa_sprintf_malloc("%s" PA_PATH_SEP "%s", e, local);
2064 else if ((h = pa_get_home_dir_malloc())) {
2065 fn = lfn = pa_sprintf_malloc("%s" PA_PATH_SEP ".pulse" PA_PATH_SEP "%s", h, local);
2070 if (access(fn, R_OK) == 0) {
2071 char *r = pa_xstrdup(fn);
2076 if (errno != ENOENT) {
2077 pa_log_warn("Failed to access configuration file '%s': %s", fn, pa_cstrerror(errno));
2089 if (strncmp(global, PA_DEFAULT_CONFIG_DIR, strlen(PA_DEFAULT_CONFIG_DIR)) == 0)
2090 gfn = pa_sprintf_malloc("%s" PA_PATH_SEP "etc" PA_PATH_SEP "pulse%s",
2091 pa_win32_get_toplevel(NULL),
2092 global + strlen(PA_DEFAULT_CONFIG_DIR));
2095 gfn = pa_xstrdup(global);
2097 if (access(gfn, R_OK) == 0)
2107 /* Format the specified data as a hexademical string */
2108 char *pa_hexstr(const uint8_t* d, size_t dlength, char *s, size_t slength) {
2109 size_t i = 0, j = 0;
2110 const char hex[] = "0123456789abcdef";
2114 pa_assert(slength > 0);
2116 while (j+2 < slength && i < dlength) {
2117 s[j++] = hex[*d >> 4];
2118 s[j++] = hex[*d & 0xF];
2124 s[j < slength ? j : slength] = 0;
2128 /* Convert a hexadecimal digit to a number or -1 if invalid */
2129 static int hexc(char c) {
2130 if (c >= '0' && c <= '9')
2133 if (c >= 'A' && c <= 'F')
2134 return c - 'A' + 10;
2136 if (c >= 'a' && c <= 'f')
2137 return c - 'a' + 10;
2143 /* Parse a hexadecimal string as created by pa_hexstr() to a BLOB */
2144 size_t pa_parsehex(const char *p, uint8_t *d, size_t dlength) {
2150 while (j < dlength && *p) {
2153 if ((b = hexc(*(p++))) < 0)
2156 d[j] = (uint8_t) (b << 4);
2161 if ((b = hexc(*(p++))) < 0)
2164 d[j] |= (uint8_t) b;
2171 /* Returns nonzero when *s starts with *pfx */
2172 bool pa_startswith(const char *s, const char *pfx) {
2180 return strlen(s) >= l && strncmp(s, pfx, l) == 0;
2183 /* Returns nonzero when *s ends with *sfx */
2184 bool pa_endswith(const char *s, const char *sfx) {
2193 return l1 >= l2 && pa_streq(s + l1 - l2, sfx);
2196 bool pa_is_path_absolute(const char *fn) {
2202 return strlen(fn) >= 3 && isalpha(fn[0]) && fn[1] == ':' && fn[2] == '\\';
2206 char *pa_make_path_absolute(const char *p) {
2212 if (pa_is_path_absolute(p))
2213 return pa_xstrdup(p);
2215 if (!(cwd = pa_getcwd()))
2216 return pa_xstrdup(p);
2218 r = pa_sprintf_malloc("%s" PA_PATH_SEP "%s", cwd, p);
2223 /* If fn is NULL, return the PulseAudio runtime or state dir (depending on the
2224 * rt parameter). If fn is non-NULL and starts with /, return fn. Otherwise,
2225 * append fn to the runtime/state dir and return it. */
2226 static char *get_path(const char *fn, bool prependmid, bool rt) {
2229 rtp = rt ? pa_get_runtime_dir() : pa_get_state_dir();
2232 char *r, *canonical_rtp;
2234 if (pa_is_path_absolute(fn)) {
2236 return pa_xstrdup(fn);
2242 /* Hopefully make the path smaller to avoid 108 char limit (fdo#44680) */
2243 if ((canonical_rtp = pa_realpath(rtp))) {
2244 if (strlen(rtp) >= strlen(canonical_rtp))
2247 pa_xfree(canonical_rtp);
2248 canonical_rtp = rtp;
2251 canonical_rtp = rtp;
2256 if (!(mid = pa_machine_id())) {
2257 pa_xfree(canonical_rtp);
2261 r = pa_sprintf_malloc("%s" PA_PATH_SEP "%s-%s", canonical_rtp, mid, fn);
2264 r = pa_sprintf_malloc("%s" PA_PATH_SEP "%s", canonical_rtp, fn);
2266 pa_xfree(canonical_rtp);
2272 char *pa_runtime_path(const char *fn) {
2273 return get_path(fn, false, true);
2276 char *pa_state_path(const char *fn, bool appendmid) {
2277 return get_path(fn, appendmid, false);
2280 /* Convert the string s to a signed integer in *ret_i */
2281 int pa_atoi(const char *s, int32_t *ret_i) {
2287 if (pa_atol(s, &l) < 0)
2290 if (l < INT32_MIN || l > INT32_MAX) {
2295 *ret_i = (int32_t) l;
2306 /* A helper function for pa_atou() and friends. This does some common checks,
2307 * because our number parsing is more strict than the strtoX functions.
2309 * Leading zeros are stripped from integers so that they don't get parsed as
2310 * octal (but "0x" is preserved for hexadecimal numbers). For NUMTYPE_INT the
2311 * zero stripping may involve allocating a new string, in which case it's
2312 * stored in tmp. Otherwise tmp is set to NULL. The caller needs to free tmp
2313 * after they're done with ret. When parsing other types than NUMTYPE_INT the
2314 * caller can pass NULL as tmp.
2316 * The final string to parse is returned in ret. ret will point either inside
2318 static int prepare_number_string(const char *s, enum numtype type, char **tmp, const char **ret) {
2319 const char *original = s;
2320 bool negative = false;
2323 pa_assert(type != NUMTYPE_INT || tmp);
2329 /* The strtoX functions accept leading spaces, we don't. */
2330 if (isspace((unsigned char) s[0]))
2333 /* The strtoX functions accept a plus sign, we don't. */
2337 /* The strtoul and strtoull functions allow a minus sign even though they
2338 * parse an unsigned number. In case of a minus sign the original negative
2339 * number gets negated. We don't want that kind of behviour. */
2340 if (type == NUMTYPE_UINT && s[0] == '-')
2343 /* The strtoX functions interpret the number as octal if it starts with
2344 * a zero. We prefer to use base 10, so we strip all leading zeros (if the
2345 * string starts with "0x", strtoul() interprets it as hexadecimal, which
2346 * is fine, because it's unambiguous unlike octal).
2348 * While stripping the leading zeros, we have to remember to also handle
2349 * the case where the number is negative, which makes the zero skipping
2350 * code somewhat complex. */
2352 /* Doubles don't need zero stripping, we can finish now. */
2353 if (type == NUMTYPE_DOUBLE)
2358 s++; /* Skip the minus sign. */
2361 /* Don't skip zeros if the string starts with "0x". */
2362 if (s[0] == '0' && s[1] != 'x') {
2363 while (s[0] == '0' && s[1])
2364 s++; /* Skip zeros. */
2368 s--; /* Go back one step, we need the minus sign back. */
2370 /* If s != original, then we have skipped some zeros and we need to replace
2371 * the last skipped zero with a minus sign. */
2372 if (s != original) {
2373 *tmp = pa_xstrdup(s);
2384 /* Convert the string s to an unsigned integer in *ret_u */
2385 int pa_atou(const char *s, uint32_t *ret_u) {
2392 if (prepare_number_string(s, NUMTYPE_UINT, NULL, &s) < 0) {
2398 l = strtoul(s, &x, 0);
2400 /* If x doesn't point to the end of s, there was some trailing garbage in
2401 * the string. If x points to s, no conversion was done (empty string). */
2402 if (!x || *x || x == s || errno) {
2408 if (l > UINT32_MAX) {
2413 *ret_u = (uint32_t) l;
2418 /* Convert the string s to an unsigned 64 bit integer in *ret_u */
2419 int pa_atou64(const char *s, uint64_t *ret_u) {
2421 unsigned long long l;
2426 if (prepare_number_string(s, NUMTYPE_UINT, NULL, &s) < 0) {
2432 l = strtoull(s, &x, 0);
2434 /* If x doesn't point to the end of s, there was some trailing garbage in
2435 * the string. If x points to s, no conversion was done (empty string). */
2436 if (!x || *x || x == s || errno) {
2442 if (l > UINT64_MAX) {
2447 *ret_u = (uint64_t) l;
2452 /* Convert the string s to a signed long integer in *ret_l. */
2453 int pa_atol(const char *s, long *ret_l) {
2461 if (prepare_number_string(s, NUMTYPE_INT, &tmp, &s) < 0) {
2467 l = strtol(s, &x, 0);
2469 /* If x doesn't point to the end of s, there was some trailing garbage in
2470 * the string. If x points to s, no conversion was done (at least an empty
2471 * string can trigger this). */
2472 if (!x || *x || x == s || errno) {
2486 /* Convert the string s to a signed 64 bit integer in *ret_l. */
2487 int pa_atoi64(const char *s, int64_t *ret_l) {
2495 if (prepare_number_string(s, NUMTYPE_INT, &tmp, &s) < 0) {
2501 l = strtoll(s, &x, 0);
2503 /* If x doesn't point to the end of s, there was some trailing garbage in
2504 * the string. If x points to s, no conversion was done (at least an empty
2505 * string can trigger this). */
2506 if (!x || *x || x == s || errno) {
2517 if (l < INT64_MIN || l > INT64_MAX) {
2525 #ifdef HAVE_STRTOD_L
2526 static locale_t c_locale = NULL;
2528 static void c_locale_destroy(void) {
2529 freelocale(c_locale);
2533 int pa_atod(const char *s, double *ret_d) {
2540 if (prepare_number_string(s, NUMTYPE_DOUBLE, NULL, &s) < 0) {
2545 /* This should be locale independent */
2547 #ifdef HAVE_STRTOD_L
2551 if ((c_locale = newlocale(LC_ALL_MASK, "C", NULL)))
2552 atexit(c_locale_destroy);
2558 f = strtod_l(s, &x, c_locale);
2566 /* If x doesn't point to the end of s, there was some trailing garbage in
2567 * the string. If x points to s, no conversion was done (at least an empty
2568 * string can trigger this). */
2569 if (!x || *x || x == s || errno) {
2585 /* Same as snprintf, but guarantees NUL-termination on every platform */
2586 size_t pa_snprintf(char *str, size_t size, const char *format, ...) {
2591 pa_assert(size > 0);
2594 va_start(ap, format);
2595 ret = pa_vsnprintf(str, size, format, ap);
2601 /* Same as vsnprintf, but guarantees NUL-termination on every platform */
2602 size_t pa_vsnprintf(char *str, size_t size, const char *format, va_list ap) {
2606 pa_assert(size > 0);
2609 ret = vsnprintf(str, size, format, ap);
2616 if ((size_t) ret > size-1)
2619 return (size_t) ret;
2622 /* Truncate the specified string, but guarantee that the string
2623 * returned still validates as UTF8 */
2624 char *pa_truncate_utf8(char *c, size_t l) {
2626 pa_assert(pa_utf8_valid(c));
2633 while (l > 0 && !pa_utf8_valid(c))
2639 char *pa_getcwd(void) {
2643 char *p = pa_xmalloc(l);
2647 if (errno != ERANGE) {
2657 void *pa_will_need(const void *p, size_t l) {
2658 #ifdef RLIMIT_MEMLOCK
2665 const size_t page_size = pa_page_size();
2670 a = PA_PAGE_ALIGN_PTR(p);
2671 size = (size_t) ((const uint8_t*) p + l - (const uint8_t*) a);
2673 #ifdef HAVE_POSIX_MADVISE
2674 if ((r = posix_madvise((void*) a, size, POSIX_MADV_WILLNEED)) == 0) {
2675 pa_log_debug("posix_madvise() worked fine!");
2680 /* Most likely the memory was not mmap()ed from a file and thus
2681 * madvise() didn't work, so let's misuse mlock() do page this
2682 * stuff back into RAM. Yeah, let's fuck with the MM! It's so
2683 * inviting, the man page of mlock() tells us: "All pages that
2684 * contain a part of the specified address range are guaranteed to
2685 * be resident in RAM when the call returns successfully." */
2687 #ifdef RLIMIT_MEMLOCK
2688 pa_assert_se(getrlimit(RLIMIT_MEMLOCK, &rlim) == 0);
2690 if (rlim.rlim_cur < page_size) {
2691 pa_log_debug("posix_madvise() failed (or doesn't exist), resource limits don't allow mlock(), can't page in data: %s", pa_cstrerror(r));
2696 bs = PA_PAGE_ALIGN((size_t) rlim.rlim_cur);
2701 pa_log_debug("posix_madvise() failed (or doesn't exist), trying mlock(): %s", pa_cstrerror(r));
2704 while (size > 0 && bs > 0) {
2709 if (mlock(a, bs) < 0) {
2710 bs = PA_PAGE_ALIGN(bs / 2);
2714 pa_assert_se(munlock(a, bs) == 0);
2716 a = (const uint8_t*) a + bs;
2722 pa_log_debug("mlock() failed too (or doesn't exist), giving up: %s", pa_cstrerror(errno));
2724 pa_log_debug("mlock() worked fine!");
2730 int pa_safe_close_pipe(int fd) {
2733 for (retry = 5; retry > 0; retry--) {
2738 pa_log("pa_close() failed while trying to close fd(%d) retry(%d): %s",
2739 fd, retry, pa_cstrerror(errno));
2747 void pa_close_pipe(int fds[2]) {
2752 pa_assert_se(pa_safe_close_pipe(fds[0]) == 0);
2754 pa_assert_se(pa_close(fds[0]) == 0);
2759 pa_assert_se(pa_safe_close_pipe(fds[1]) == 0);
2761 pa_assert_se(pa_close(fds[1]) == 0);
2764 fds[0] = fds[1] = -1;
2767 char *pa_readlink(const char *p) {
2768 #ifdef HAVE_READLINK
2777 if ((n = readlink(p, c, l-1)) < 0) {
2782 if ((size_t) n < l-1) {
2795 int pa_close_all(int except_fd, ...) {
2800 va_start(ap, except_fd);
2803 for (n = 1; va_arg(ap, int) >= 0; n++)
2808 p = pa_xnew(int, n+1);
2810 va_start(ap, except_fd);
2813 if (except_fd >= 0) {
2817 while ((fd = va_arg(ap, int)) >= 0)
2824 r = pa_close_allv(p);
2830 int pa_close_allv(const int except_fds[]) {
2835 #if defined(__linux__) || defined(__sun)
2839 if ((d = opendir("/proc/self/fd"))) {
2843 while ((de = readdir(d))) {
2849 if (de->d_name[0] == '.')
2853 l = strtol(de->d_name, &e, 10);
2854 if (errno != 0 || !e || *e) {
2862 if ((long) fd != l) {
2875 for (i = 0; except_fds[i] >= 0; i++)
2876 if (except_fds[i] == fd) {
2884 if (pa_close(fd) < 0) {
2885 saved_errno = errno;
2887 errno = saved_errno;
2899 if (getrlimit(RLIMIT_NOFILE, &rl) >= 0)
2900 maxfd = (int) rl.rlim_max;
2902 maxfd = sysconf(_SC_OPEN_MAX);
2904 for (fd = 3; fd < maxfd; fd++) {
2909 for (i = 0; except_fds[i] >= 0; i++)
2910 if (except_fds[i] == fd) {
2918 if (pa_close(fd) < 0 && errno != EBADF)
2921 #endif /* !OS_IS_WIN32 */
2926 int pa_unblock_sigs(int except, ...) {
2931 va_start(ap, except);
2934 for (n = 1; va_arg(ap, int) >= 0; n++)
2939 p = pa_xnew(int, n+1);
2941 va_start(ap, except);
2948 while ((sig = va_arg(ap, int)) >= 0)
2955 r = pa_unblock_sigsv(p);
2961 int pa_unblock_sigsv(const int except[]) {
2966 if (sigemptyset(&ss) < 0)
2969 for (i = 0; except[i] > 0; i++)
2970 if (sigaddset(&ss, except[i]) < 0)
2973 return sigprocmask(SIG_SETMASK, &ss, NULL);
2979 int pa_reset_sigs(int except, ...) {
2984 va_start(ap, except);
2987 for (n = 1; va_arg(ap, int) >= 0; n++)
2992 p = pa_xnew(int, n+1);
2994 va_start(ap, except);
3001 while ((sig = va_arg(ap, int)) >= 0)
3008 r = pa_reset_sigsv(p);
3014 int pa_reset_sigsv(const int except[]) {
3018 for (sig = 1; sig < NSIG; sig++) {
3030 for (i = 0; except[i] > 0; i++) {
3031 if (sig == except[i]) {
3040 struct sigaction sa;
3042 memset(&sa, 0, sizeof(sa));
3043 sa.sa_handler = SIG_DFL;
3045 /* On Linux the first two RT signals are reserved by
3046 * glibc, and sigaction() will return EINVAL for them. */
3047 if ((sigaction(sig, &sa, NULL) < 0))
3048 if (errno != EINVAL)
3057 void pa_set_env(const char *key, const char *value) {
3061 /* This is not thread-safe */
3064 int kl = strlen(key);
3065 int vl = strlen(value);
3066 char *tmp = pa_xmalloc(kl+vl+2);
3067 memcpy(tmp, key, kl);
3068 memcpy(tmp+kl+1, value, vl);
3070 tmp[kl+1+vl] = '\0';
3072 /* Even though it should be safe to free it on Windows, we don't want to
3073 * rely on undocumented behaviour. */
3075 setenv(key, value, 1);
3079 void pa_unset_env(const char *key) {
3082 /* This is not thread-safe */
3085 int kl = strlen(key);
3086 char *tmp = pa_xmalloc(kl+2);
3087 memcpy(tmp, key, kl);
3091 /* Even though it should be safe to free it on Windows, we don't want to
3092 * rely on undocumented behaviour. */
3098 void pa_set_env_and_record(const char *key, const char *value) {
3102 /* This is not thread-safe */
3104 pa_set_env(key, value);
3105 recorded_env = pa_strlist_prepend(recorded_env, key);
3108 void pa_unset_env_recorded(void) {
3110 /* This is not thread-safe */
3115 recorded_env = pa_strlist_pop(recorded_env, &s);
3125 bool pa_in_system_mode(void) {
3128 if (!(e = getenv("PULSE_SYSTEM")))
3134 /* Checks a delimiters-separated list of words in haystack for needle */
3135 bool pa_str_in_list(const char *haystack, const char *delimiters, const char *needle) {
3137 const char *state = NULL;
3139 if (!haystack || !needle)
3142 while ((s = pa_split(haystack, delimiters, &state))) {
3143 if (pa_streq(needle, s)) {
3154 /* Checks a whitespace-separated list of words in haystack for needle */
3155 bool pa_str_in_list_spaces(const char *haystack, const char *needle) {
3158 const char *state = NULL;
3160 if (!haystack || !needle)
3163 while ((s = pa_split_spaces_in_place(haystack, &n, &state))) {
3164 if (pa_strneq(needle, s, n))
3171 char* pa_str_strip_suffix(const char *str, const char *suffix) {
3172 size_t str_l, suf_l, prefix;
3178 str_l = strlen(str);
3179 suf_l = strlen(suffix);
3184 prefix = str_l - suf_l;
3186 if (!pa_streq(&str[prefix], suffix))
3189 ret = pa_xmalloc(prefix + 1);
3191 strncpy(ret, str, prefix);
3197 char *pa_get_user_name_malloc(void) {
3201 #ifdef _SC_LOGIN_NAME_MAX
3202 k = (ssize_t) sysconf(_SC_LOGIN_NAME_MAX);
3208 u = pa_xnew(char, k+1);
3210 if (!(pa_get_user_name(u, k))) {
3218 char *pa_get_host_name_malloc(void) {
3227 if (!pa_get_host_name(c, l)) {
3229 if (errno != EINVAL && errno != ENAMETOOLONG)
3232 } else if (strlen(c) < l-1) {
3240 u = pa_utf8_filter(c);
3245 /* Hmm, the hostname is as long the space we offered the
3246 * function, we cannot know if it fully fit in, so let's play
3247 * safe and retry. */
3256 char *pa_machine_id(void) {
3260 /* The returned value is supposed be some kind of ascii identifier
3261 * that is unique and stable across reboots. First we try if the machine-id
3262 * file is available. If it's available, that's great, since it provides an
3263 * identifier that suits our needs perfectly. If it's not, we fall back to
3264 * the hostname, which is not as good, since it can change over time. */
3266 /* We search for the machine-id file from four locations. The first two are
3267 * relative to the configured installation prefix, but if we're installed
3268 * under /usr/local, for example, it's likely that the machine-id won't be
3269 * found there, so we also try the hardcoded paths.
3271 * PA_MACHINE_ID or PA_MACHINE_ID_FALLBACK might exist on a Windows system,
3272 * but the last two hardcoded paths certainly don't, hence we don't try
3273 * them on Windows. */
3274 if ((f = pa_fopen_cloexec(PA_MACHINE_ID, "r")) ||
3275 (f = pa_fopen_cloexec(PA_MACHINE_ID_FALLBACK, "r")) ||
3276 #if !defined(OS_IS_WIN32)
3277 (f = pa_fopen_cloexec("/etc/machine-id", "r")) ||
3278 (f = pa_fopen_cloexec("/var/lib/dbus/machine-id", "r"))
3283 char ln[34] = "", *r;
3285 r = fgets(ln, sizeof(ln)-1, f);
3291 return pa_utf8_filter(ln);
3294 if ((h = pa_get_host_name_malloc()))
3297 #if !defined(OS_IS_WIN32) && !defined(__ANDROID__)
3298 /* If no hostname was set we use the POSIX hostid. It's usually
3299 * the IPv4 address. Might not be that stable. */
3300 return pa_sprintf_malloc("%08lx", (unsigned long) gethostid());
3306 char *pa_session_id(void) {
3309 e = getenv("XDG_SESSION_ID");
3313 return pa_utf8_filter(e);
3316 char *pa_uname_string(void) {
3320 pa_assert_se(uname(&u) >= 0);
3322 return pa_sprintf_malloc("%s %s %s %s", u.sysname, u.machine, u.release, u.version);
3328 i.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
3329 pa_assert_se(GetVersionEx(&i));
3331 return pa_sprintf_malloc("Windows %lu.%lu (%lu) %s", i.dwMajorVersion, i.dwMinorVersion, i.dwBuildNumber, i.szCSDVersion);
3335 #ifdef HAVE_VALGRIND_MEMCHECK_H
3336 bool pa_in_valgrind(void) {
3339 /* To make heisenbugs a bit simpler to find we check for $VALGRIND
3340 * here instead of really checking whether we run in valgrind or
3344 b = getenv("VALGRIND") ? 2 : 1;
3350 unsigned pa_gcd(unsigned a, unsigned b) {
3361 void pa_reduce(unsigned *num, unsigned *den) {
3363 unsigned gcd = pa_gcd(*num, *den);
3371 pa_assert(pa_gcd(*num, *den) == 1);
3374 unsigned pa_ncpus(void) {
3377 #ifdef _SC_NPROCESSORS_ONLN
3378 ncpus = sysconf(_SC_NPROCESSORS_ONLN);
3383 return ncpus <= 0 ? 1 : (unsigned) ncpus;
3386 char *pa_replace(const char*s, const char*a, const char *b) {
3396 sb = pa_strbuf_new();
3401 if (!(p = strstr(s, a)))
3404 pa_strbuf_putsn(sb, s, p-s);
3405 pa_strbuf_puts(sb, b);
3409 pa_strbuf_puts(sb, s);
3411 return pa_strbuf_to_string_free(sb);
3414 char *pa_escape(const char *p, const char *chars) {
3417 char *out_string, *output;
3418 int char_count = strlen(p);
3420 /* Maximum number of characters in output string
3421 * including trailing 0. */
3422 char_count = 2 * char_count + 1;
3424 /* allocate output string */
3425 out_string = pa_xmalloc(char_count);
3426 output = out_string;
3428 /* write output string */
3429 for (s = p; *s; ++s) {
3433 for (c = chars; *c; ++c) {
3445 /* Remove trailing garbage */
3446 output = pa_xstrdup(out_string);
3448 pa_xfree(out_string);
3452 char *pa_unescape(char *p) {
3454 bool escaped = false;
3456 for (s = p, d = p; *s; s++) {
3457 if (!escaped && *s == '\\') {
3471 char *pa_realpath(const char *path) {
3475 /* We want only absolute paths */
3476 if (path[0] != '/') {
3481 #if defined(__GLIBC__)
3485 if (!(r = realpath(path, NULL)))
3488 /* We copy this here in case our pa_xmalloc() is not
3489 * implemented on top of libc malloc() */
3493 #elif defined(PATH_MAX)
3496 path_buf = pa_xmalloc(PATH_MAX);
3498 #if defined(OS_IS_WIN32)
3499 if (!(t = _fullpath(path_buf, path, _MAX_PATH))) {
3504 if (!(t = realpath(path, path_buf))) {
3511 #error "It's not clear whether this system supports realpath(..., NULL) like GNU libc does. If it doesn't we need a private version of realpath() here."
3517 void pa_disable_sigpipe(void) {
3520 struct sigaction sa;
3524 if (sigaction(SIGPIPE, NULL, &sa) < 0) {
3525 pa_log("sigaction(): %s", pa_cstrerror(errno));
3529 sa.sa_handler = SIG_IGN;
3531 if (sigaction(SIGPIPE, &sa, NULL) < 0) {
3532 pa_log("sigaction(): %s", pa_cstrerror(errno));
3538 void pa_xfreev(void**a) {
3544 for (p = a; *p; p++)
3550 char **pa_split_spaces_strv(const char *s) {
3552 unsigned i = 0, n = 8;
3553 const char *state = NULL;
3555 t = pa_xnew(char*, n);
3556 while ((e = pa_split_spaces(s, &state))) {
3561 t = pa_xrenew(char*, t, n);
3574 char* pa_maybe_prefix_path(const char *path, const char *prefix) {
3577 if (pa_is_path_absolute(path))
3578 return pa_xstrdup(path);
3580 return pa_sprintf_malloc("%s" PA_PATH_SEP "%s", prefix, path);
3583 size_t pa_pipe_buf(int fd) {
3588 if ((n = fpathconf(fd, _PC_PIPE_BUF)) >= 0)
3599 void pa_reset_personality(void) {
3601 #if defined(__linux__) && !defined(__ANDROID__)
3602 if (personality(PER_LINUX) < 0)
3603 pa_log_warn("Uh, personality() failed: %s", pa_cstrerror(errno));
3608 bool pa_run_from_build_tree(void) {
3609 static bool b = false;
3611 #ifdef HAVE_RUNNING_FROM_BUILD_TREE
3614 if ((rp = pa_readlink("/proc/self/exe"))) {
3615 b = pa_startswith(rp, PA_BUILDDIR);
3624 const char *pa_get_temp_dir(void) {
3627 if ((t = getenv("TMPDIR")) &&
3628 pa_is_path_absolute(t))
3631 if ((t = getenv("TMP")) &&
3632 pa_is_path_absolute(t))
3635 if ((t = getenv("TEMP")) &&
3636 pa_is_path_absolute(t))
3639 if ((t = getenv("TEMPDIR")) &&
3640 pa_is_path_absolute(t))
3646 int pa_open_cloexec(const char *fn, int flags, mode_t mode) {
3654 if ((fd = open(fn, flags|O_CLOEXEC, mode)) >= 0)
3657 if (errno != EINVAL)
3661 if ((fd = open(fn, flags, mode)) >= 0)
3668 /* Some implementations might simply ignore O_CLOEXEC if it is not
3669 * understood, make sure FD_CLOEXEC is enabled anyway */
3671 pa_make_fd_cloexec(fd);
3675 int pa_socket_cloexec(int domain, int type, int protocol) {
3679 if ((fd = socket(domain, type | SOCK_CLOEXEC, protocol)) >= 0)
3682 if (errno != EINVAL)
3686 if ((fd = socket(domain, type, protocol)) >= 0)
3693 /* Some implementations might simply ignore SOCK_CLOEXEC if it is
3694 * not understood, make sure FD_CLOEXEC is enabled anyway */
3696 pa_make_fd_cloexec(fd);
3700 int pa_pipe_cloexec(int pipefd[2]) {
3704 if ((r = pipe2(pipefd, O_CLOEXEC)) >= 0)
3707 if (errno == EMFILE) {
3708 pa_log_error("The per-process limit on the number of open file descriptors has been reached.");
3712 if (errno == ENFILE) {
3713 pa_log_error("The system-wide limit on the total number of open files has been reached.");
3717 if (errno != EINVAL && errno != ENOSYS)
3722 if ((r = pipe(pipefd)) >= 0)
3725 if (errno == EMFILE) {
3726 pa_log_error("The per-process limit on the number of open file descriptors has been reached.");
3730 if (errno == ENFILE) {
3731 pa_log_error("The system-wide limit on the total number of open files has been reached.");
3739 pa_make_fd_cloexec(pipefd[0]);
3740 pa_make_fd_cloexec(pipefd[1]);
3745 int pa_accept_cloexec(int sockfd, struct sockaddr *addr, socklen_t *addrlen) {
3751 if ((fd = accept4(sockfd, addr, addrlen, SOCK_CLOEXEC)) >= 0)
3754 if (errno != EINVAL && errno != ENOSYS)
3760 if ((fd = paccept(sockfd, addr, addrlen, NULL, SOCK_CLOEXEC)) >= 0)
3764 if ((fd = accept(sockfd, addr, addrlen)) >= 0)
3771 pa_make_fd_cloexec(fd);
3775 FILE* pa_fopen_cloexec(const char *path, const char *mode) {
3779 m = pa_sprintf_malloc("%se", mode);
3782 if ((f = fopen(path, m))) {
3789 if (errno != EINVAL)
3792 if (!(f = fopen(path, mode)))
3796 pa_make_fd_cloexec(fileno(f));
3800 void pa_nullify_stdfds(void) {
3803 pa_close(STDIN_FILENO);
3804 pa_close(STDOUT_FILENO);
3805 pa_close(STDERR_FILENO);
3807 pa_assert_se(open("/dev/null", O_RDONLY) == STDIN_FILENO);
3808 pa_assert_se(open("/dev/null", O_WRONLY) == STDOUT_FILENO);
3809 pa_assert_se(open("/dev/null", O_WRONLY) == STDERR_FILENO);
3816 char *pa_read_line_from_file(const char *fn) {
3818 char ln[256] = "", *r;
3820 if (!(f = pa_fopen_cloexec(fn, "r")))
3823 r = fgets(ln, sizeof(ln)-1, f);
3832 return pa_xstrdup(ln);
3835 bool pa_running_in_vm(void) {
3837 #if defined(__i386__) || defined(__x86_64__)
3839 /* Both CPUID and DMI are x86 specific interfaces... */
3842 unsigned int eax, ebx, ecx, edx;
3846 const char *const dmi_vendors[] = {
3847 "/sys/class/dmi/id/sys_vendor",
3848 "/sys/class/dmi/id/board_vendor",
3849 "/sys/class/dmi/id/bios_vendor"
3854 for (i = 0; i < PA_ELEMENTSOF(dmi_vendors); i++) {
3857 if ((s = pa_read_line_from_file(dmi_vendors[i]))) {
3859 if (pa_startswith(s, "QEMU") ||
3860 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3861 pa_startswith(s, "VMware") ||
3862 pa_startswith(s, "VMW") ||
3863 pa_startswith(s, "Microsoft Corporation") ||
3864 pa_startswith(s, "innotek GmbH") ||
3865 pa_startswith(s, "Xen")) {
3879 /* Hypervisors provide presence on 0x1 cpuid leaf.
3880 * http://lwn.net/Articles/301888/ */
3881 if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) == 0)
3884 if (ecx & 0x80000000)
3887 #endif /* HAVE_CPUID_H */
3889 #endif /* defined(__i386__) || defined(__x86_64__) */
3894 size_t pa_page_size(void) {
3895 #if defined(PAGE_SIZE)
3897 #elif defined(PAGESIZE)
3899 #elif defined(HAVE_SYSCONF)
3900 static size_t page_size = 4096; /* Let's hope it's like x86. */
3903 long ret = sysconf(_SC_PAGE_SIZE);