e63a67627a83b51d278390af9a6548a665748c79
[platform/upstream/pulseaudio.git] / src / pulsecore / core-util.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2004-2006 Lennart Poettering
5   Copyright 2004 Joe Marcus Clarke
6   Copyright 2006-2007 Pierre Ossman <ossman@cendio.se> for Cendio AB
7
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.
12
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.
17
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/>.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <math.h>
27 #include <stdarg.h>
28 #include <stdlib.h>
29 #include <signal.h>
30 #include <errno.h>
31 #include <string.h>
32 #include <stdio.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35 #include <limits.h>
36 #include <ctype.h>
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <dirent.h>
40
41 #ifdef HAVE_LANGINFO_H
42 #include <langinfo.h>
43 #endif
44
45 #ifdef HAVE_UNAME
46 #include <sys/utsname.h>
47 #endif
48
49 #if defined(HAVE_REGEX_H)
50 #include <regex.h>
51 #elif defined(HAVE_PCREPOSIX_H)
52 #include <pcreposix.h>
53 #endif
54
55 #ifdef HAVE_STRTOD_L
56 #ifdef HAVE_LOCALE_H
57 #include <locale.h>
58 #endif
59 #ifdef HAVE_XLOCALE_H
60 #include <xlocale.h>
61 #endif
62 #endif
63
64 #ifdef HAVE_SYS_RESOURCE_H
65 #include <sys/resource.h>
66 #endif
67
68 #ifdef HAVE_SYS_CAPABILITY_H
69 #include <sys/capability.h>
70 #endif
71
72 #ifdef HAVE_SYS_MMAN_H
73 #include <sys/mman.h>
74 #endif
75
76 #ifdef HAVE_PTHREAD
77 #include <pthread.h>
78 #endif
79
80 #ifdef HAVE_NETDB_H
81 #include <netdb.h>
82 #endif
83
84 #ifdef HAVE_WINDOWS_H
85 #include <windows.h>
86 #endif
87
88 #ifndef ENOTSUP
89 #define ENOTSUP   135
90 #endif
91
92 #ifdef HAVE_PWD_H
93 #include <pwd.h>
94 #endif
95
96 #ifdef HAVE_GRP_H
97 #include <grp.h>
98 #endif
99
100 #ifdef HAVE_LIBSAMPLERATE
101 #include <samplerate.h>
102 #endif
103
104 #ifdef HAVE_DBUS
105 #include <pulsecore/rtkit.h>
106 #endif
107
108 #if defined(__linux__) && !defined(__ANDROID__)
109 #include <sys/personality.h>
110 #endif
111
112 #ifdef HAVE_CPUID_H
113 #include <cpuid.h>
114 #endif
115
116 #include <pulse/xmalloc.h>
117 #include <pulse/util.h>
118 #include <pulse/utf8.h>
119
120 #include <pulsecore/core-error.h>
121 #include <pulsecore/socket.h>
122 #include <pulsecore/log.h>
123 #include <pulsecore/macro.h>
124 #include <pulsecore/thread.h>
125 #include <pulsecore/strbuf.h>
126 #include <pulsecore/usergroup.h>
127 #include <pulsecore/strlist.h>
128 #include <pulsecore/pipe.h>
129 #include <pulsecore/once.h>
130
131 #include "core-util.h"
132
133 /* Not all platforms have this */
134 #ifndef MSG_NOSIGNAL
135 #define MSG_NOSIGNAL 0
136 #endif
137
138 #define NEWLINE "\r\n"
139 #define WHITESPACE "\n\r \t"
140
141 static pa_strlist *recorded_env = NULL;
142
143 #ifdef OS_IS_WIN32
144 static fd_set nonblocking_fds;
145 #endif
146
147 #ifdef OS_IS_WIN32
148
149 /* Returns the directory of the current DLL, with '/bin/' removed if it is the last component */
150 char *pa_win32_get_toplevel(HANDLE handle) {
151     static char *toplevel = NULL;
152
153     if (!toplevel) {
154         char library_path[MAX_PATH];
155         char *p;
156
157         if (!GetModuleFileName(handle, library_path, MAX_PATH))
158             return NULL;
159
160         toplevel = pa_xstrdup(library_path);
161
162         p = strrchr(toplevel, PA_PATH_SEP_CHAR);
163         if (p)
164             *p = '\0';
165
166         p = strrchr(toplevel, PA_PATH_SEP_CHAR);
167         if (p && pa_streq(p + 1, "bin"))
168             *p = '\0';
169     }
170
171     return toplevel;
172 }
173
174 #endif
175
176 static void set_nonblock(int fd, bool nonblock) {
177
178 #ifdef O_NONBLOCK
179     int v, nv;
180     pa_assert(fd >= 0);
181
182     pa_assert_se((v = fcntl(fd, F_GETFL)) >= 0);
183
184     if (nonblock)
185         nv = v | O_NONBLOCK;
186     else
187         nv = v & ~O_NONBLOCK;
188
189     if (v != nv)
190         pa_assert_se(fcntl(fd, F_SETFL, nv) >= 0);
191
192 #elif defined(OS_IS_WIN32)
193     u_long arg;
194
195     if (nonblock)
196         arg = 1;
197     else
198         arg = 0;
199
200     if (ioctlsocket(fd, FIONBIO, &arg) < 0) {
201         pa_assert_se(WSAGetLastError() == WSAENOTSOCK);
202         pa_log_warn("Only sockets can be made non-blocking!");
203         return;
204     }
205
206     /* There is no method to query status, so we remember all fds */
207     if (nonblock)
208         FD_SET(fd, &nonblocking_fds);
209     else
210         FD_CLR(fd, &nonblocking_fds);
211 #else
212     pa_log_warn("Non-blocking I/O not supported.!");
213 #endif
214
215 }
216
217 /** Make a file descriptor nonblock. Doesn't do any error checking */
218 void pa_make_fd_nonblock(int fd) {
219     set_nonblock(fd, true);
220 }
221
222 /** Make a file descriptor blocking. Doesn't do any error checking */
223 void pa_make_fd_block(int fd) {
224     set_nonblock(fd, false);
225 }
226
227 /** Query if a file descriptor is non-blocking */
228 bool pa_is_fd_nonblock(int fd) {
229
230 #ifdef O_NONBLOCK
231     int v;
232     pa_assert(fd >= 0);
233
234     pa_assert_se((v = fcntl(fd, F_GETFL)) >= 0);
235
236     return !!(v & O_NONBLOCK);
237
238 #elif defined(OS_IS_WIN32)
239     return !!FD_ISSET(fd, &nonblocking_fds);
240 #else
241     return false;
242 #endif
243
244 }
245
246 /* Set the FD_CLOEXEC flag for a fd */
247 void pa_make_fd_cloexec(int fd) {
248
249 #ifdef FD_CLOEXEC
250     int v;
251     pa_assert(fd >= 0);
252
253     pa_assert_se((v = fcntl(fd, F_GETFD, 0)) >= 0);
254
255     if (!(v & FD_CLOEXEC))
256         pa_assert_se(fcntl(fd, F_SETFD, v|FD_CLOEXEC) >= 0);
257 #endif
258
259 }
260
261 /** Creates a directory securely. Will create parent directories recursively if
262  * required. This will not update permissions on parent directories if they
263  * already exist, however. */
264 int pa_make_secure_dir(const char* dir, mode_t m, uid_t uid, gid_t gid, bool update_perms) {
265     struct stat st;
266     int r, saved_errno;
267     bool retry = true;
268
269     pa_assert(dir);
270
271 again:
272 #ifdef OS_IS_WIN32
273     r = mkdir(dir);
274 #else
275 {
276     mode_t u;
277     u = umask((~m) & 0777);
278     r = mkdir(dir, m);
279     umask(u);
280 }
281 #endif
282
283     if (r < 0 && errno == ENOENT && retry) {
284         /* If a parent directory in the path doesn't exist, try to create that
285          * first, then try again. */
286         pa_make_secure_parent_dir(dir, m, uid, gid, false);
287         retry = false;
288         goto again;
289     }
290
291     if (r < 0 && errno != EEXIST)
292         return -1;
293
294 #if defined(HAVE_FSTAT) && !defined(OS_IS_WIN32)
295 {
296     int fd;
297     if ((fd = open(dir,
298 #ifdef O_CLOEXEC
299                    O_CLOEXEC|
300 #endif
301 #ifdef O_NOCTTY
302                    O_NOCTTY|
303 #endif
304 #ifdef O_NOFOLLOW
305                    O_NOFOLLOW|
306 #endif
307                    O_RDONLY)) < 0)
308         goto fail;
309
310     if (fstat(fd, &st) < 0) {
311         pa_assert_se(pa_close(fd) >= 0);
312         goto fail;
313     }
314
315     if (!S_ISDIR(st.st_mode)) {
316         pa_assert_se(pa_close(fd) >= 0);
317         errno = EEXIST;
318         goto fail;
319     }
320
321     if (!update_perms) {
322         pa_assert_se(pa_close(fd) >= 0);
323         return 0;
324     }
325
326 #ifdef HAVE_FCHOWN
327     if (uid == (uid_t) -1)
328         uid = getuid();
329     if (gid == (gid_t) -1)
330         gid = getgid();
331     if (((st.st_uid != uid) || (st.st_gid != gid)) && fchown(fd, uid, gid) < 0) {
332         pa_assert_se(pa_close(fd) >= 0);
333         goto fail;
334     }
335 #endif
336
337 #ifdef HAVE_FCHMOD
338     if ((st.st_mode & 07777) != m && fchmod(fd, m) < 0) {
339         pa_assert_se(pa_close(fd) >= 0);
340         goto fail;
341     };
342 #endif
343
344     pa_assert_se(pa_close(fd) >= 0);
345 }
346 #else
347     pa_log_warn("Secure directory creation not supported on this platform.");
348 #endif
349
350     return 0;
351
352 fail:
353     saved_errno = errno;
354     rmdir(dir);
355     errno = saved_errno;
356
357     return -1;
358 }
359
360 /* Return a newly allocated sting containing the parent directory of the specified file */
361 char *pa_parent_dir(const char *fn) {
362     char *slash, *dir = pa_xstrdup(fn);
363
364     if ((slash = (char*) pa_path_get_filename(dir)) == dir) {
365         pa_xfree(dir);
366         errno = ENOENT;
367         return NULL;
368     }
369
370     *(slash-1) = 0;
371     return dir;
372 }
373
374 /* Creates a the parent directory of the specified path securely */
375 int pa_make_secure_parent_dir(const char *fn, mode_t m, uid_t uid, gid_t gid, bool update_perms) {
376     int ret = -1;
377     char *dir;
378
379     if (!(dir = pa_parent_dir(fn)))
380         goto finish;
381
382     if (pa_make_secure_dir(dir, m, uid, gid, update_perms) < 0)
383         goto finish;
384
385     ret = 0;
386
387 finish:
388     pa_xfree(dir);
389     return ret;
390 }
391
392 /** Platform independent read function. Necessary since not all
393  * systems treat all file descriptors equal. If type is
394  * non-NULL it is used to cache the type of the fd. This is
395  * useful for making sure that only a single syscall is executed per
396  * function call. The variable pointed to should be initialized to 0
397  * by the caller. */
398 ssize_t pa_read(int fd, void *buf, size_t count, int *type) {
399
400 #ifdef OS_IS_WIN32
401
402     if (!type || *type == 0) {
403         ssize_t r;
404
405         if ((r = recv(fd, buf, count, 0)) >= 0)
406             return r;
407
408         if (WSAGetLastError() != WSAENOTSOCK) {
409             errno = WSAGetLastError();
410             return r;
411         }
412
413         if (type)
414             *type = 1;
415     }
416
417 #endif
418
419     for (;;) {
420         ssize_t r;
421
422         if ((r = read(fd, buf, count)) < 0)
423             if (errno == EINTR)
424                 continue;
425
426         return r;
427     }
428 }
429
430 /** Similar to pa_read(), but handles writes */
431 ssize_t pa_write(int fd, const void *buf, size_t count, int *type) {
432
433     if (!type || *type == 0) {
434         ssize_t r;
435
436         for (;;) {
437             if ((r = send(fd, buf, count, MSG_NOSIGNAL)) < 0) {
438
439                 if (errno == EINTR)
440                     continue;
441
442                 break;
443             }
444
445             return r;
446         }
447
448 #ifdef OS_IS_WIN32
449         if (WSAGetLastError() != WSAENOTSOCK) {
450             errno = WSAGetLastError();
451             return r;
452         }
453 #else
454         if (errno != ENOTSOCK)
455             return r;
456 #endif
457
458         if (type)
459             *type = 1;
460     }
461
462     for (;;) {
463         ssize_t r;
464
465         if ((r = write(fd, buf, count)) < 0)
466             if (errno == EINTR)
467                 continue;
468
469         return r;
470     }
471 }
472
473 /** Calls read() in a loop. Makes sure that as much as 'size' bytes,
474  * unless EOF is reached or an error occurred */
475 ssize_t pa_loop_read(int fd, void*data, size_t size, int *type) {
476     ssize_t ret = 0;
477     int _type;
478
479     pa_assert(fd >= 0);
480     pa_assert(data);
481     pa_assert(size);
482
483     if (!type) {
484         _type = 0;
485         type = &_type;
486     }
487
488     while (size > 0) {
489         ssize_t r;
490
491         if ((r = pa_read(fd, data, size, type)) < 0)
492             return r;
493
494         if (r == 0)
495             break;
496
497         ret += r;
498         data = (uint8_t*) data + r;
499         size -= (size_t) r;
500     }
501
502     return ret;
503 }
504
505 /** Similar to pa_loop_read(), but wraps write() */
506 ssize_t pa_loop_write(int fd, const void*data, size_t size, int *type) {
507     ssize_t ret = 0;
508     int _type;
509
510     pa_assert(fd >= 0);
511     pa_assert(data);
512     pa_assert(size);
513
514     if (!type) {
515         _type = 0;
516         type = &_type;
517     }
518
519     while (size > 0) {
520         ssize_t r;
521
522         if ((r = pa_write(fd, data, size, type)) < 0)
523             return r;
524
525         if (r == 0)
526             break;
527
528         ret += r;
529         data = (const uint8_t*) data + r;
530         size -= (size_t) r;
531     }
532
533     return ret;
534 }
535
536 /** Platform independent close function. Necessary since not all
537  * systems treat all file descriptors equal. */
538 int pa_close(int fd) {
539
540 #ifdef OS_IS_WIN32
541     int ret;
542
543     FD_CLR(fd, &nonblocking_fds);
544
545     if ((ret = closesocket(fd)) == 0)
546         return 0;
547
548     if (WSAGetLastError() != WSAENOTSOCK) {
549         errno = WSAGetLastError();
550         return ret;
551     }
552 #endif
553
554     for (;;) {
555         int r;
556
557         if ((r = close(fd)) < 0)
558             if (errno == EINTR)
559                 continue;
560
561         return r;
562     }
563 }
564
565 /* Print a warning messages in case that the given signal is not
566  * blocked or trapped */
567 void pa_check_signal_is_blocked(int sig) {
568 #ifdef HAVE_SIGACTION
569     struct sigaction sa;
570     sigset_t set;
571
572     /* If POSIX threads are supported use thread-aware
573      * pthread_sigmask() function, to check if the signal is
574      * blocked. Otherwise fall back to sigprocmask() */
575
576 #ifdef HAVE_PTHREAD
577     if (pthread_sigmask(SIG_SETMASK, NULL, &set) < 0) {
578 #endif
579         if (sigprocmask(SIG_SETMASK, NULL, &set) < 0) {
580             pa_log("sigprocmask(): %s", pa_cstrerror(errno));
581             return;
582         }
583 #ifdef HAVE_PTHREAD
584     }
585 #endif
586
587     if (sigismember(&set, sig))
588         return;
589
590     /* Check whether the signal is trapped */
591
592     if (sigaction(sig, NULL, &sa) < 0) {
593         pa_log("sigaction(): %s", pa_cstrerror(errno));
594         return;
595     }
596
597     if (sa.sa_handler != SIG_DFL)
598         return;
599
600     pa_log_warn("%s is not trapped. This might cause malfunction!", pa_sig2str(sig));
601 #else /* HAVE_SIGACTION */
602     pa_log_warn("%s might not be trapped. This might cause malfunction!", pa_sig2str(sig));
603 #endif
604 }
605
606 /* The following function is based on an example from the GNU libc
607  * documentation. This function is similar to GNU's asprintf(). */
608 char *pa_sprintf_malloc(const char *format, ...) {
609     size_t size = 100;
610     char *c = NULL;
611
612     pa_assert(format);
613
614     for(;;) {
615         int r;
616         va_list ap;
617
618         c = pa_xrealloc(c, size);
619
620         va_start(ap, format);
621         r = vsnprintf(c, size, format, ap);
622         va_end(ap);
623
624         c[size-1] = 0;
625
626         if (r > -1 && (size_t) r < size)
627             return c;
628
629         if (r > -1)    /* glibc 2.1 */
630             size = (size_t) r+1;
631         else           /* glibc 2.0 */
632             size *= 2;
633     }
634 }
635
636 /* Same as the previous function, but use a va_list instead of an
637  * ellipsis */
638 char *pa_vsprintf_malloc(const char *format, va_list ap) {
639     size_t size = 100;
640     char *c = NULL;
641
642     pa_assert(format);
643
644     for(;;) {
645         int r;
646         va_list aq;
647
648         c = pa_xrealloc(c, size);
649
650         va_copy(aq, ap);
651         r = vsnprintf(c, size, format, aq);
652         va_end(aq);
653
654         c[size-1] = 0;
655
656         if (r > -1 && (size_t) r < size)
657             return c;
658
659         if (r > -1)    /* glibc 2.1 */
660             size = (size_t) r+1;
661         else           /* glibc 2.0 */
662             size *= 2;
663     }
664 }
665
666 /* Similar to OpenBSD's strlcpy() function */
667 char *pa_strlcpy(char *b, const char *s, size_t l) {
668     size_t k;
669
670     pa_assert(b);
671     pa_assert(s);
672     pa_assert(l > 0);
673
674     k = strlen(s);
675
676     if (k > l-1)
677         k = l-1;
678
679     memcpy(b, s, k);
680     b[k] = 0;
681
682     return b;
683 }
684
685 #ifdef HAVE_SYS_RESOURCE_H
686 static int set_nice(int nice_level) {
687 #ifdef HAVE_DBUS
688     DBusError error;
689     DBusConnection *bus;
690     int r;
691
692     dbus_error_init(&error);
693 #endif
694
695 #ifdef HAVE_SYS_RESOURCE_H
696     if (setpriority(PRIO_PROCESS, 0, nice_level) >= 0) {
697         pa_log_debug("setpriority() worked.");
698         return 0;
699     }
700 #endif
701
702 #ifdef HAVE_DBUS
703     /* Try to talk to RealtimeKit */
704
705     if (!(bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error))) {
706         pa_log("Failed to connect to system bus: %s", error.message);
707         dbus_error_free(&error);
708         errno = -EIO;
709         return -1;
710     }
711
712     /* We need to disable exit on disconnect because otherwise
713      * dbus_shutdown will kill us. See
714      * https://bugs.freedesktop.org/show_bug.cgi?id=16924 */
715     dbus_connection_set_exit_on_disconnect(bus, FALSE);
716
717     r = rtkit_make_high_priority(bus, 0, nice_level);
718     dbus_connection_close(bus);
719     dbus_connection_unref(bus);
720
721     if (r >= 0) {
722         pa_log_debug("RealtimeKit worked.");
723         return 0;
724     }
725
726     errno = -r;
727 #endif
728
729     return -1;
730 }
731 #endif
732
733 /* Raise the priority of the current process as much as possible that
734  * is <= the specified nice level..*/
735 int pa_raise_priority(int nice_level) {
736
737 #ifdef HAVE_SYS_RESOURCE_H
738     int n;
739
740     if (set_nice(nice_level) >= 0) {
741         pa_log_info("Successfully gained nice level %i.", nice_level);
742         return 0;
743     }
744
745     for (n = nice_level+1; n < 0; n++)
746         if (set_nice(n) >= 0) {
747             pa_log_info("Successfully acquired nice level %i, which is lower than the requested %i.", n, nice_level);
748             return 0;
749         }
750
751     pa_log_info("Failed to acquire high-priority scheduling: %s", pa_cstrerror(errno));
752     return -1;
753 #endif
754
755 #ifdef OS_IS_WIN32
756     if (nice_level < 0) {
757         if (!SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS)) {
758             pa_log_warn("SetPriorityClass() failed: 0x%08X", GetLastError());
759             errno = EPERM;
760             return -1;
761         }
762
763         pa_log_info("Successfully gained high priority class.");
764     }
765 #endif
766
767     return 0;
768 }
769
770 /* Reset the priority to normal, inverting the changes made by
771  * pa_raise_priority() and pa_thread_make_realtime()*/
772 void pa_reset_priority(void) {
773 #ifdef HAVE_SYS_RESOURCE_H
774     struct sched_param sp;
775
776     setpriority(PRIO_PROCESS, 0, 0);
777
778     pa_zero(sp);
779     pthread_setschedparam(pthread_self(), SCHED_OTHER, &sp);
780 #endif
781
782 #ifdef OS_IS_WIN32
783     SetPriorityClass(GetCurrentProcess(), NORMAL_PRIORITY_CLASS);
784 #endif
785 }
786
787 int pa_match(const char *expr, const char *v) {
788 #if defined(HAVE_REGEX_H) || defined(HAVE_PCREPOSIX_H)
789     int k;
790     regex_t re;
791     int r;
792
793     if (regcomp(&re, expr, REG_NOSUB|REG_EXTENDED) != 0) {
794         errno = EINVAL;
795         return -1;
796     }
797
798     if ((k = regexec(&re, v, 0, NULL, 0)) == 0)
799         r = 1;
800     else if (k == REG_NOMATCH)
801         r = 0;
802     else
803         r = -1;
804
805     regfree(&re);
806
807     if (r < 0)
808         errno = EINVAL;
809
810     return r;
811 #else
812     errno = ENOSYS;
813     return -1;
814 #endif
815 }
816
817 /* Try to parse a boolean string value.*/
818 int pa_parse_boolean(const char *v) {
819     pa_assert(v);
820
821     /* First we check language independent */
822     if (pa_streq(v, "1") || !strcasecmp(v, "y") || !strcasecmp(v, "t")
823             || !strcasecmp(v, "yes") || !strcasecmp(v, "true") || !strcasecmp(v, "on"))
824         return 1;
825     else if (pa_streq(v, "0") || !strcasecmp(v, "n") || !strcasecmp(v, "f")
826                  || !strcasecmp(v, "no") || !strcasecmp(v, "false") || !strcasecmp(v, "off"))
827         return 0;
828
829 #ifdef HAVE_LANGINFO_H
830 {
831     const char *expr;
832     /* And then we check language dependent */
833     if ((expr = nl_langinfo(YESEXPR)))
834         if (expr[0])
835             if (pa_match(expr, v) > 0)
836                 return 1;
837
838     if ((expr = nl_langinfo(NOEXPR)))
839         if (expr[0])
840             if (pa_match(expr, v) > 0)
841                 return 0;
842 }
843 #endif
844
845     errno = EINVAL;
846     return -1;
847 }
848
849 /* Try to parse a volume string to pa_volume_t. The allowed formats are:
850  * db, % and unsigned integer */
851 int pa_parse_volume(const char *v, pa_volume_t *volume) {
852     int len;
853     uint32_t i;
854     double d;
855     char str[64];
856
857     pa_assert(v);
858     pa_assert(volume);
859
860     len = strlen(v);
861
862     if (len >= 64)
863         return -1;
864
865     memcpy(str, v, len + 1);
866
867     if (str[len - 1] == '%') {
868         str[len - 1] = '\0';
869         if (pa_atod(str, &d) < 0)
870             return -1;
871
872         d = d / 100 * PA_VOLUME_NORM;
873
874         if (d < 0 || d > PA_VOLUME_MAX)
875             return -1;
876
877         *volume = d;
878         return 0;
879     }
880
881     if (len > 2 && (str[len - 1] == 'b' || str[len - 1] == 'B') &&
882                (str[len - 2] == 'd' || str[len - 2] == 'D')) {
883         str[len - 2] = '\0';
884         if (pa_atod(str, &d) < 0)
885             return -1;
886
887         if (d > pa_sw_volume_to_dB(PA_VOLUME_MAX))
888             return -1;
889
890         *volume = pa_sw_volume_from_dB(d);
891         return 0;
892     }
893
894     if (pa_atou(v, &i) < 0 || !PA_VOLUME_IS_VALID(i))
895         return -1;
896
897     *volume = i;
898     return 0;
899 }
900
901 /* Split the specified string wherever one of the characters in delimiter
902  * occurs. Each time it is called returns a newly allocated string
903  * with pa_xmalloc(). The variable state points to, should be
904  * initialized to NULL before the first call. */
905 char *pa_split(const char *c, const char *delimiter, const char**state) {
906     const char *current = *state ? *state : c;
907     size_t l;
908
909     if (!*current)
910         return NULL;
911
912     l = strcspn(current, delimiter);
913     *state = current+l;
914
915     if (**state)
916         (*state)++;
917
918     return pa_xstrndup(current, l);
919 }
920
921 /* Split the specified string wherever one of the characters in delimiter
922  * occurs. Each time it is called returns a pointer to the substring within the
923  * string and the length in 'n'. Note that the resultant string cannot be used
924  * as-is without the length parameter, since it is merely pointing to a point
925  * within the original string. The variable state points to, should be
926  * initialized to NULL before the first call. */
927 const char *pa_split_in_place(const char *c, const char *delimiter, size_t *n, const char**state) {
928     const char *current = *state ? *state : c;
929     size_t l;
930
931     if (!*current)
932         return NULL;
933
934     l = strcspn(current, delimiter);
935     *state = current+l;
936
937     if (**state)
938         (*state)++;
939
940     *n = l;
941     return current;
942 }
943
944 /* Split a string into words. Otherwise similar to pa_split(). */
945 char *pa_split_spaces(const char *c, const char **state) {
946     const char *current = *state ? *state : c;
947     size_t l;
948
949     if (!*current || *c == 0)
950         return NULL;
951
952     current += strspn(current, WHITESPACE);
953     l = strcspn(current, WHITESPACE);
954
955     *state = current+l;
956
957     return pa_xstrndup(current, l);
958 }
959
960 /* Similar to pa_split_spaces, except this returns a string in-place.
961    Returned string is generally not NULL-terminated.
962    See pa_split_in_place(). */
963 const char *pa_split_spaces_in_place(const char *c, size_t *n, const char **state) {
964     const char *current = *state ? *state : c;
965     size_t l;
966
967     if (!*current || *c == 0)
968         return NULL;
969
970     current += strspn(current, WHITESPACE);
971     l = strcspn(current, WHITESPACE);
972
973     *state = current+l;
974
975     *n = l;
976     return current;
977 }
978
979 PA_STATIC_TLS_DECLARE(signame, pa_xfree);
980
981 /* Return the name of an UNIX signal. Similar to Solaris sig2str() */
982 const char *pa_sig2str(int sig) {
983     char *t;
984
985     if (sig <= 0)
986         goto fail;
987
988 #ifdef NSIG
989     if (sig >= NSIG)
990         goto fail;
991 #endif
992
993 #ifdef HAVE_SIG2STR
994     {
995         char buf[SIG2STR_MAX];
996
997         if (sig2str(sig, buf) == 0) {
998             pa_xfree(PA_STATIC_TLS_GET(signame));
999             t = pa_sprintf_malloc("SIG%s", buf);
1000             PA_STATIC_TLS_SET(signame, t);
1001             return t;
1002         }
1003     }
1004 #else
1005
1006     switch (sig) {
1007 #ifdef SIGHUP
1008         case SIGHUP:    return "SIGHUP";
1009 #endif
1010         case SIGINT:    return "SIGINT";
1011 #ifdef SIGQUIT
1012         case SIGQUIT:   return "SIGQUIT";
1013 #endif
1014         case SIGILL:    return "SIGULL";
1015 #ifdef SIGTRAP
1016         case SIGTRAP:   return "SIGTRAP";
1017 #endif
1018         case SIGABRT:   return "SIGABRT";
1019 #ifdef SIGBUS
1020         case SIGBUS:    return "SIGBUS";
1021 #endif
1022         case SIGFPE:    return "SIGFPE";
1023 #ifdef SIGKILL
1024         case SIGKILL:   return "SIGKILL";
1025 #endif
1026 #ifdef SIGUSR1
1027         case SIGUSR1:   return "SIGUSR1";
1028 #endif
1029         case SIGSEGV:   return "SIGSEGV";
1030 #ifdef SIGUSR2
1031         case SIGUSR2:   return "SIGUSR2";
1032 #endif
1033 #ifdef SIGPIPE
1034         case SIGPIPE:   return "SIGPIPE";
1035 #endif
1036 #ifdef SIGALRM
1037         case SIGALRM:   return "SIGALRM";
1038 #endif
1039         case SIGTERM:   return "SIGTERM";
1040 #ifdef SIGSTKFLT
1041         case SIGSTKFLT: return "SIGSTKFLT";
1042 #endif
1043 #ifdef SIGCHLD
1044         case SIGCHLD:   return "SIGCHLD";
1045 #endif
1046 #ifdef SIGCONT
1047         case SIGCONT:   return "SIGCONT";
1048 #endif
1049 #ifdef SIGSTOP
1050         case SIGSTOP:   return "SIGSTOP";
1051 #endif
1052 #ifdef SIGTSTP
1053         case SIGTSTP:   return "SIGTSTP";
1054 #endif
1055 #ifdef SIGTTIN
1056         case SIGTTIN:   return "SIGTTIN";
1057 #endif
1058 #ifdef SIGTTOU
1059         case SIGTTOU:   return "SIGTTOU";
1060 #endif
1061 #ifdef SIGURG
1062         case SIGURG:    return "SIGURG";
1063 #endif
1064 #ifdef SIGXCPU
1065         case SIGXCPU:   return "SIGXCPU";
1066 #endif
1067 #ifdef SIGXFSZ
1068         case SIGXFSZ:   return "SIGXFSZ";
1069 #endif
1070 #ifdef SIGVTALRM
1071         case SIGVTALRM: return "SIGVTALRM";
1072 #endif
1073 #ifdef SIGPROF
1074         case SIGPROF:   return "SIGPROF";
1075 #endif
1076 #ifdef SIGWINCH
1077         case SIGWINCH:  return "SIGWINCH";
1078 #endif
1079 #ifdef SIGIO
1080         case SIGIO:     return "SIGIO";
1081 #endif
1082 #ifdef SIGPWR
1083         case SIGPWR:    return "SIGPWR";
1084 #endif
1085 #ifdef SIGSYS
1086         case SIGSYS:    return "SIGSYS";
1087 #endif
1088     }
1089
1090 #ifdef SIGRTMIN
1091     if (sig >= SIGRTMIN && sig <= SIGRTMAX) {
1092         pa_xfree(PA_STATIC_TLS_GET(signame));
1093         t = pa_sprintf_malloc("SIGRTMIN+%i", sig - SIGRTMIN);
1094         PA_STATIC_TLS_SET(signame, t);
1095         return t;
1096     }
1097 #endif
1098
1099 #endif
1100
1101 fail:
1102
1103     pa_xfree(PA_STATIC_TLS_GET(signame));
1104     t = pa_sprintf_malloc("SIG%i", sig);
1105     PA_STATIC_TLS_SET(signame, t);
1106     return t;
1107 }
1108
1109 #ifdef HAVE_GRP_H
1110
1111 /* Check whether the specified GID and the group name match */
1112 static int is_group(gid_t gid, const char *name) {
1113     struct group *group = NULL;
1114     int r = -1;
1115
1116     errno = 0;
1117     if (!(group = pa_getgrgid_malloc(gid))) {
1118         if (!errno)
1119             errno = ENOENT;
1120
1121         pa_log("pa_getgrgid_malloc(%u): %s", gid, pa_cstrerror(errno));
1122
1123         goto finish;
1124     }
1125
1126     r = pa_streq(name, group->gr_name);
1127
1128 finish:
1129     pa_getgrgid_free(group);
1130
1131     return r;
1132 }
1133
1134 /* Check the current user is member of the specified group */
1135 int pa_own_uid_in_group(const char *name, gid_t *gid) {
1136     GETGROUPS_T *gids, tgid;
1137     long n = sysconf(_SC_NGROUPS_MAX);
1138     int r = -1, i, k;
1139
1140     pa_assert(n > 0);
1141
1142     gids = pa_xmalloc(sizeof(GETGROUPS_T) * (size_t) n);
1143
1144     if ((n = getgroups((int) n, gids)) < 0) {
1145         pa_log("getgroups(): %s", pa_cstrerror(errno));
1146         goto finish;
1147     }
1148
1149     for (i = 0; i < n; i++) {
1150
1151         if ((k = is_group(gids[i], name)) < 0)
1152             goto finish;
1153         else if (k > 0) {
1154             *gid = gids[i];
1155             r = 1;
1156             goto finish;
1157         }
1158     }
1159
1160     if ((k = is_group(tgid = getgid(), name)) < 0)
1161         goto finish;
1162     else if (k > 0) {
1163         *gid = tgid;
1164         r = 1;
1165         goto finish;
1166     }
1167
1168     r = 0;
1169
1170 finish:
1171
1172     pa_xfree(gids);
1173     return r;
1174 }
1175
1176 /* Check whether the specific user id is a member of the specified group */
1177 int pa_uid_in_group(uid_t uid, const char *name) {
1178     struct group *group = NULL;
1179     char **i;
1180     int r = -1;
1181
1182     errno = 0;
1183     if (!(group = pa_getgrnam_malloc(name))) {
1184         if (!errno)
1185             errno = ENOENT;
1186         goto finish;
1187     }
1188
1189     r = 0;
1190     for (i = group->gr_mem; *i; i++) {
1191         struct passwd *pw = NULL;
1192
1193         errno = 0;
1194         if (!(pw = pa_getpwnam_malloc(*i)))
1195             continue;
1196
1197         if (pw->pw_uid == uid)
1198             r = 1;
1199
1200         pa_getpwnam_free(pw);
1201
1202         if (r == 1)
1203             break;
1204     }
1205
1206 finish:
1207     pa_getgrnam_free(group);
1208
1209     return r;
1210 }
1211
1212 /* Get the GID of a given group, return (gid_t) -1 on failure. */
1213 gid_t pa_get_gid_of_group(const char *name) {
1214     gid_t ret = (gid_t) -1;
1215     struct group *gr = NULL;
1216
1217     errno = 0;
1218     if (!(gr = pa_getgrnam_malloc(name))) {
1219         if (!errno)
1220             errno = ENOENT;
1221         goto finish;
1222     }
1223
1224     ret = gr->gr_gid;
1225
1226 finish:
1227     pa_getgrnam_free(gr);
1228     return ret;
1229 }
1230
1231 int pa_check_in_group(gid_t g) {
1232     gid_t gids[NGROUPS_MAX];
1233     int r;
1234
1235     if ((r = getgroups(NGROUPS_MAX, gids)) < 0)
1236         return -1;
1237
1238     for (; r > 0; r--)
1239         if (gids[r-1] == g)
1240             return 1;
1241
1242     return 0;
1243 }
1244
1245 #else /* HAVE_GRP_H */
1246
1247 int pa_own_uid_in_group(const char *name, gid_t *gid) {
1248     errno = ENOTSUP;
1249     return -1;
1250
1251 }
1252
1253 int pa_uid_in_group(uid_t uid, const char *name) {
1254     errno = ENOTSUP;
1255     return -1;
1256 }
1257
1258 gid_t pa_get_gid_of_group(const char *name) {
1259     errno = ENOTSUP;
1260     return (gid_t) -1;
1261 }
1262
1263 int pa_check_in_group(gid_t g) {
1264     errno = ENOTSUP;
1265     return -1;
1266 }
1267
1268 #endif
1269
1270 /* Lock or unlock a file entirely.
1271   (advisory on UNIX, mandatory on Windows) */
1272 int pa_lock_fd(int fd, int b) {
1273 #ifdef F_SETLKW
1274     struct flock f_lock;
1275
1276     /* Try a R/W lock first */
1277
1278     f_lock.l_type = (short) (b ? F_WRLCK : F_UNLCK);
1279     f_lock.l_whence = SEEK_SET;
1280     f_lock.l_start = 0;
1281     f_lock.l_len = 0;
1282
1283     if (fcntl(fd, F_SETLKW, &f_lock) >= 0)
1284         return 0;
1285
1286     /* Perhaps the file descriptor was opened for read only, than try again with a read lock. */
1287     if (b && errno == EBADF) {
1288         f_lock.l_type = F_RDLCK;
1289         if (fcntl(fd, F_SETLKW, &f_lock) >= 0)
1290             return 0;
1291     }
1292
1293     pa_log("%slock: %s", !b ? "un" : "", pa_cstrerror(errno));
1294 #endif
1295
1296 #ifdef OS_IS_WIN32
1297     HANDLE h = (HANDLE) _get_osfhandle(fd);
1298
1299     if (b && LockFile(h, 0, 0, 0xFFFFFFFF, 0xFFFFFFFF))
1300         return 0;
1301     if (!b && UnlockFile(h, 0, 0, 0xFFFFFFFF, 0xFFFFFFFF))
1302         return 0;
1303
1304     pa_log("%slock failed: 0x%08X", !b ? "un" : "", GetLastError());
1305
1306     /* FIXME: Needs to set errno! */
1307 #endif
1308
1309     return -1;
1310 }
1311
1312 /* Remove trailing newlines from a string */
1313 char* pa_strip_nl(char *s) {
1314     pa_assert(s);
1315
1316     s[strcspn(s, NEWLINE)] = 0;
1317     return s;
1318 }
1319
1320 char *pa_strip(char *s) {
1321     char *e, *l = NULL;
1322
1323     /* Drops trailing whitespace. Modifies the string in
1324      * place. Returns pointer to first non-space character */
1325
1326     s += strspn(s, WHITESPACE);
1327
1328     for (e = s; *e; e++)
1329         if (!strchr(WHITESPACE, *e))
1330             l = e;
1331
1332     if (l)
1333         *(l+1) = 0;
1334     else
1335         *s = 0;
1336
1337     return s;
1338 }
1339
1340 /* Create a temporary lock file and lock it. */
1341 int pa_lock_lockfile(const char *fn) {
1342     int fd;
1343     pa_assert(fn);
1344
1345     for (;;) {
1346         struct stat st;
1347
1348         if ((fd = pa_open_cloexec(fn, O_CREAT|O_RDWR
1349 #ifdef O_NOFOLLOW
1350                        |O_NOFOLLOW
1351 #endif
1352                        , S_IRUSR|S_IWUSR)) < 0) {
1353             pa_log_warn("Failed to create lock file '%s': %s", fn, pa_cstrerror(errno));
1354             goto fail;
1355         }
1356
1357         if (pa_lock_fd(fd, 1) < 0) {
1358             pa_log_warn("Failed to lock file '%s'.", fn);
1359             goto fail;
1360         }
1361
1362         if (fstat(fd, &st) < 0) {
1363             pa_log_warn("Failed to fstat() file '%s': %s", fn, pa_cstrerror(errno));
1364             goto fail;
1365         }
1366
1367         /* Check whether the file has been removed meanwhile. When yes,
1368          * restart this loop, otherwise, we're done */
1369         if (st.st_nlink >= 1)
1370             break;
1371
1372         if (pa_lock_fd(fd, 0) < 0) {
1373             pa_log_warn("Failed to unlock file '%s'.", fn);
1374             goto fail;
1375         }
1376
1377         if (pa_close(fd) < 0) {
1378             pa_log_warn("Failed to close file '%s': %s", fn, pa_cstrerror(errno));
1379             fd = -1;
1380             goto fail;
1381         }
1382     }
1383
1384     return fd;
1385
1386 fail:
1387
1388     if (fd >= 0) {
1389         int saved_errno = errno;
1390         pa_close(fd);
1391         errno = saved_errno;
1392     }
1393
1394     return -1;
1395 }
1396
1397 /* Unlock a temporary lock file */
1398 int pa_unlock_lockfile(const char *fn, int fd) {
1399     int r = 0;
1400     pa_assert(fd >= 0);
1401
1402     if (fn) {
1403         if (unlink(fn) < 0) {
1404             pa_log_warn("Unable to remove lock file '%s': %s", fn, pa_cstrerror(errno));
1405             r = -1;
1406         }
1407     }
1408
1409     if (pa_lock_fd(fd, 0) < 0) {
1410         pa_log_warn("Failed to unlock file '%s'.", fn);
1411         r = -1;
1412     }
1413
1414     if (pa_close(fd) < 0) {
1415         pa_log_warn("Failed to close '%s': %s", fn, pa_cstrerror(errno));
1416         r = -1;
1417     }
1418
1419     return r;
1420 }
1421
1422 static int check_ours(const char *p) {
1423     struct stat st;
1424
1425     pa_assert(p);
1426
1427     if (stat(p, &st) < 0)
1428         return -errno;
1429
1430 #ifdef HAVE_GETUID
1431     if (st.st_uid != getuid())
1432         return -EACCES;
1433 #endif
1434
1435     return 0;
1436 }
1437
1438 static char *get_pulse_home(void) {
1439     char *h, *ret;
1440     int t;
1441
1442     h = pa_get_home_dir_malloc();
1443     if (!h) {
1444         pa_log_error("Failed to get home directory.");
1445         return NULL;
1446     }
1447
1448     t = check_ours(h);
1449     if (t < 0 && t != -ENOENT) {
1450         pa_log_error("Home directory not accessible: %s", pa_cstrerror(-t));
1451         pa_xfree(h);
1452         return NULL;
1453     }
1454
1455     /* If the old directory exists, use it. */
1456     ret = pa_sprintf_malloc("%s" PA_PATH_SEP ".pulse", h);
1457     pa_xfree(h);
1458     if (access(ret, F_OK) >= 0)
1459         return ret;
1460     free(ret);
1461
1462     /* Otherwise go for the XDG compliant directory. */
1463     if (pa_get_config_home_dir(&ret) < 0)
1464         return NULL;
1465
1466     return ret;
1467 }
1468
1469 char *pa_get_state_dir(void) {
1470     char *d;
1471
1472     /* The state directory shall contain dynamic data that should be
1473      * kept across reboots, and is private to this user */
1474
1475     if (!(d = pa_xstrdup(getenv("PULSE_STATE_PATH"))))
1476         if (!(d = get_pulse_home()))
1477             return NULL;
1478
1479     /* If PULSE_STATE_PATH and PULSE_RUNTIME_PATH point to the same
1480      * dir then this will break. */
1481
1482     if (pa_make_secure_dir(d, 0700U, (uid_t) -1, (gid_t) -1, true) < 0) {
1483         pa_log_error("Failed to create secure directory (%s): %s", d, pa_cstrerror(errno));
1484         pa_xfree(d);
1485         return NULL;
1486     }
1487
1488     return d;
1489 }
1490
1491 char *pa_get_home_dir_malloc(void) {
1492     char *homedir;
1493     size_t allocated = 128;
1494
1495     for (;;) {
1496         homedir = pa_xmalloc(allocated);
1497
1498         if (!pa_get_home_dir(homedir, allocated)) {
1499             pa_xfree(homedir);
1500             return NULL;
1501         }
1502
1503         if (strlen(homedir) < allocated - 1)
1504             break;
1505
1506         pa_xfree(homedir);
1507         allocated *= 2;
1508     }
1509
1510     return homedir;
1511 }
1512
1513 int pa_append_to_home_dir(const char *path, char **_r) {
1514     char *home_dir;
1515
1516     pa_assert(path);
1517     pa_assert(_r);
1518
1519     home_dir = pa_get_home_dir_malloc();
1520     if (!home_dir) {
1521         pa_log("Failed to get home directory.");
1522         return -PA_ERR_NOENTITY;
1523     }
1524
1525     *_r = pa_sprintf_malloc("%s" PA_PATH_SEP "%s", home_dir, path);
1526     pa_xfree(home_dir);
1527     return 0;
1528 }
1529
1530 int pa_get_config_home_dir(char **_r) {
1531     const char *e;
1532     char *home_dir;
1533
1534     pa_assert(_r);
1535
1536     e = getenv("XDG_CONFIG_HOME");
1537     if (e && *e) {
1538         *_r = pa_sprintf_malloc("%s" PA_PATH_SEP "pulse", e);
1539         return 0;
1540     }
1541
1542     home_dir = pa_get_home_dir_malloc();
1543     if (!home_dir)
1544         return -PA_ERR_NOENTITY;
1545
1546     *_r = pa_sprintf_malloc("%s" PA_PATH_SEP ".config" PA_PATH_SEP "pulse", home_dir);
1547     pa_xfree(home_dir);
1548     return 0;
1549 }
1550
1551 int pa_append_to_config_home_dir(const char *path, char **_r) {
1552     int r;
1553     char *config_home_dir;
1554
1555     pa_assert(path);
1556     pa_assert(_r);
1557
1558     r = pa_get_config_home_dir(&config_home_dir);
1559     if (r < 0)
1560         return r;
1561
1562     *_r = pa_sprintf_malloc("%s" PA_PATH_SEP "%s", config_home_dir, path);
1563     pa_xfree(config_home_dir);
1564     return 0;
1565 }
1566
1567 char *pa_get_binary_name_malloc(void) {
1568     char *t;
1569     size_t allocated = 128;
1570
1571     for (;;) {
1572         t = pa_xmalloc(allocated);
1573
1574         if (!pa_get_binary_name(t, allocated)) {
1575             pa_xfree(t);
1576             return NULL;
1577         }
1578
1579 #ifdef __TIZEN__
1580         if (strnlen(t, allocated - 1) < allocated - 1)
1581 #else
1582         if (strlen(t) < allocated - 1)
1583 #endif
1584             break;
1585
1586         pa_xfree(t);
1587         allocated *= 2;
1588     }
1589
1590     return t;
1591 }
1592
1593 static char* make_random_dir(mode_t m) {
1594     static const char table[] =
1595         "abcdefghijklmnopqrstuvwxyz"
1596         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1597         "0123456789";
1598
1599     char *fn;
1600     size_t pathlen;
1601
1602     fn = pa_sprintf_malloc("%s" PA_PATH_SEP "pulse-XXXXXXXXXXXX", pa_get_temp_dir());
1603     pathlen = strlen(fn);
1604
1605     for (;;) {
1606         size_t i;
1607         int r;
1608         mode_t u;
1609         int saved_errno;
1610
1611         for (i = pathlen - 12; i < pathlen; i++)
1612             fn[i] = table[rand() % (sizeof(table)-1)];
1613
1614         u = umask((~m) & 0777);
1615 #ifndef OS_IS_WIN32
1616         r = mkdir(fn, m);
1617 #else
1618         r = mkdir(fn);
1619 #endif
1620
1621         saved_errno = errno;
1622         umask(u);
1623         errno = saved_errno;
1624
1625         if (r >= 0)
1626             return fn;
1627
1628         if (errno != EEXIST) {
1629             pa_log_error("Failed to create random directory %s: %s", fn, pa_cstrerror(errno));
1630             pa_xfree(fn);
1631             return NULL;
1632         }
1633     }
1634 }
1635
1636 static int make_random_dir_and_link(mode_t m, const char *k) {
1637     char *p;
1638
1639     if (!(p = make_random_dir(m)))
1640         return -1;
1641
1642 #ifdef HAVE_SYMLINK
1643     if (symlink(p, k) < 0) {
1644         int saved_errno = errno;
1645
1646         if (errno != EEXIST)
1647             pa_log_error("Failed to symlink %s to %s: %s", k, p, pa_cstrerror(errno));
1648
1649         rmdir(p);
1650         pa_xfree(p);
1651
1652         errno = saved_errno;
1653         return -1;
1654     }
1655 #else
1656     pa_xfree(p);
1657     return -1;
1658 #endif
1659
1660     pa_xfree(p);
1661     return 0;
1662 }
1663
1664 char *pa_get_runtime_dir(void) {
1665     char *d, *k = NULL, *p = NULL, *t = NULL, *mid;
1666     mode_t m;
1667
1668     /* The runtime directory shall contain dynamic data that needs NOT
1669      * to be kept across reboots and is usually private to the user,
1670      * except in system mode, where it might be accessible by other
1671      * users, too. Since we need POSIX locking and UNIX sockets in
1672      * this directory, we try XDG_RUNTIME_DIR first, and if that isn't
1673      * set create a directory in $HOME and link it to a random subdir
1674      * in /tmp, if it was not explicitly configured. */
1675
1676     m = pa_in_system_mode() ? 0755U : 0700U;
1677
1678     /* Use the explicitly configured value if it is set */
1679     d = getenv("PULSE_RUNTIME_PATH");
1680     if (d) {
1681
1682         if (pa_make_secure_dir(d, m, (uid_t) -1, (gid_t) -1, true) < 0) {
1683             pa_log_error("Failed to create secure directory (%s): %s", d, pa_cstrerror(errno));
1684             goto fail;
1685         }
1686
1687         return pa_xstrdup(d);
1688     }
1689
1690     /* Use the XDG standard for the runtime directory. */
1691     d = getenv("XDG_RUNTIME_DIR");
1692     if (d) {
1693 #ifdef HAVE_GETUID
1694         struct stat st;
1695         if (stat(d, &st) == 0 && st.st_uid != getuid()) {
1696             pa_log(_("XDG_RUNTIME_DIR (%s) is not owned by us (uid %d), but by uid %d! "
1697                    "(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.)"),
1698                    d, getuid(), st.st_uid);
1699             goto fail;
1700         }
1701 #endif
1702
1703         k = pa_sprintf_malloc("%s" PA_PATH_SEP "pulse", d);
1704
1705         if (pa_make_secure_dir(k, m, (uid_t) -1, (gid_t) -1, true) < 0) {
1706             pa_log_error("Failed to create secure directory (%s): %s", k, pa_cstrerror(errno));
1707             goto fail;
1708         }
1709
1710         return k;
1711     }
1712
1713     /* XDG_RUNTIME_DIR wasn't set, use the old legacy fallback */
1714     d = get_pulse_home();
1715     if (!d)
1716         goto fail;
1717
1718     if (pa_make_secure_dir(d, m, (uid_t) -1, (gid_t) -1, true) < 0) {
1719         pa_log_error("Failed to create secure directory (%s): %s", d, pa_cstrerror(errno));
1720         pa_xfree(d);
1721         goto fail;
1722     }
1723
1724     mid = pa_machine_id();
1725     if (!mid) {
1726         pa_xfree(d);
1727         goto fail;
1728     }
1729
1730     k = pa_sprintf_malloc("%s" PA_PATH_SEP "%s-runtime", d, mid);
1731     pa_xfree(d);
1732     pa_xfree(mid);
1733
1734     for (;;) {
1735         /* OK, first let's check if the "runtime" symlink already exists */
1736
1737         p = pa_readlink(k);
1738         if (!p) {
1739
1740             if (errno != ENOENT) {
1741                 pa_log_error("Failed to stat runtime directory %s: %s", k, pa_cstrerror(errno));
1742                 goto fail;
1743             }
1744
1745 #ifdef HAVE_SYMLINK
1746             /* Hmm, so the runtime directory didn't exist yet, so let's
1747              * create one in /tmp and symlink that to it */
1748
1749             if (make_random_dir_and_link(0700, k) < 0) {
1750
1751                 /* Mhmm, maybe another process was quicker than us,
1752                  * let's check if that was valid */
1753                 if (errno == EEXIST)
1754                     continue;
1755
1756                 goto fail;
1757             }
1758 #else
1759             /* No symlink possible, so let's just create the runtime directly
1760              * Do not check again if it exists since it cannot be a symlink */
1761             if (mkdir(k) < 0 && errno != EEXIST)
1762                 goto fail;
1763 #endif
1764
1765             return k;
1766         }
1767
1768         /* Make sure that this actually makes sense */
1769         if (!pa_is_path_absolute(p)) {
1770             pa_log_error("Path %s in link %s is not absolute.", p, k);
1771             errno = ENOENT;
1772             goto fail;
1773         }
1774
1775         /* Hmm, so this symlink is still around, make sure nobody fools us */
1776 #ifdef HAVE_LSTAT
1777 {
1778         struct stat st;
1779         if (lstat(p, &st) < 0) {
1780
1781             if (errno != ENOENT) {
1782                 pa_log_error("Failed to stat runtime directory %s: %s", p, pa_cstrerror(errno));
1783                 goto fail;
1784             }
1785
1786         } else {
1787
1788             if (S_ISDIR(st.st_mode) &&
1789                 (st.st_uid == getuid()) &&
1790                 ((st.st_mode & 0777) == 0700)) {
1791
1792                 pa_xfree(p);
1793                 return k;
1794             }
1795
1796             pa_log_info("Hmm, runtime path exists, but points to an invalid directory. Changing runtime directory.");
1797         }
1798 }
1799 #endif
1800
1801         pa_xfree(p);
1802         p = NULL;
1803
1804         /* Hmm, so the link points to some nonexisting or invalid
1805          * dir. Let's replace it by a new link. We first create a
1806          * temporary link and then rename that to allow concurrent
1807          * execution of this function. */
1808
1809         t = pa_sprintf_malloc("%s.tmp", k);
1810
1811         if (make_random_dir_and_link(0700, t) < 0) {
1812
1813             if (errno != EEXIST) {
1814                 pa_log_error("Failed to symlink %s: %s", t, pa_cstrerror(errno));
1815                 goto fail;
1816             }
1817
1818             pa_xfree(t);
1819             t = NULL;
1820
1821             /* Hmm, someone else was quicker then us. Let's give
1822              * him some time to finish, and retry. */
1823             pa_msleep(10);
1824             continue;
1825         }
1826
1827         /* OK, we succeeded in creating the temporary symlink, so
1828          * let's rename it */
1829         if (rename(t, k) < 0) {
1830             pa_log_error("Failed to rename %s to %s: %s", t, k, pa_cstrerror(errno));
1831             goto fail;
1832         }
1833
1834         pa_xfree(t);
1835         return k;
1836     }
1837
1838 fail:
1839     pa_xfree(p);
1840     pa_xfree(k);
1841     pa_xfree(t);
1842
1843     return NULL;
1844 }
1845
1846 /* Try to open a configuration file. If "env" is specified, open the
1847  * value of the specified environment variable. Otherwise look for a
1848  * file "local" in the home directory or a file "global" in global
1849  * file system. If "result" is non-NULL, a pointer to a newly
1850  * allocated buffer containing the used configuration file is
1851  * stored there.*/
1852 FILE *pa_open_config_file(const char *global, const char *local, const char *env, char **result) {
1853     const char *fn;
1854     FILE *f;
1855
1856     if (env && (fn = getenv(env))) {
1857         if ((f = pa_fopen_cloexec(fn, "r"))) {
1858             if (result)
1859                 *result = pa_xstrdup(fn);
1860
1861             return f;
1862         }
1863
1864         pa_log_warn("Failed to open configuration file '%s': %s", fn, pa_cstrerror(errno));
1865         return NULL;
1866     }
1867
1868     if (local) {
1869         const char *e;
1870         char *lfn;
1871         char *h;
1872
1873         if ((e = getenv("PULSE_CONFIG_PATH"))) {
1874             fn = lfn = pa_sprintf_malloc("%s" PA_PATH_SEP "%s", e, local);
1875             f = pa_fopen_cloexec(fn, "r");
1876         } else if ((h = pa_get_home_dir_malloc())) {
1877             fn = lfn = pa_sprintf_malloc("%s" PA_PATH_SEP ".pulse" PA_PATH_SEP "%s", h, local);
1878             f = pa_fopen_cloexec(fn, "r");
1879             if (!f) {
1880                 free(lfn);
1881                 fn = lfn = pa_sprintf_malloc("%s" PA_PATH_SEP ".config/pulse" PA_PATH_SEP "%s", h, local);
1882                 f = pa_fopen_cloexec(fn, "r");
1883             }
1884             pa_xfree(h);
1885         } else
1886             return NULL;
1887
1888         if (f) {
1889             if (result)
1890                 *result = pa_xstrdup(fn);
1891
1892             pa_xfree(lfn);
1893             return f;
1894         }
1895
1896         if (errno != ENOENT) {
1897             pa_log_warn("Failed to open configuration file '%s': %s", fn, pa_cstrerror(errno));
1898             pa_xfree(lfn);
1899             return NULL;
1900         }
1901
1902         pa_xfree(lfn);
1903     }
1904
1905     if (global) {
1906         char *gfn;
1907
1908 #ifdef OS_IS_WIN32
1909         if (strncmp(global, PA_DEFAULT_CONFIG_DIR, strlen(PA_DEFAULT_CONFIG_DIR)) == 0)
1910             gfn = pa_sprintf_malloc("%s" PA_PATH_SEP "etc" PA_PATH_SEP "pulse%s",
1911                                     pa_win32_get_toplevel(NULL),
1912                                     global + strlen(PA_DEFAULT_CONFIG_DIR));
1913         else
1914 #endif
1915         gfn = pa_xstrdup(global);
1916
1917         if ((f = pa_fopen_cloexec(gfn, "r"))) {
1918             if (result)
1919                 *result = gfn;
1920             else
1921                 pa_xfree(gfn);
1922
1923             return f;
1924         }
1925         pa_xfree(gfn);
1926     }
1927
1928     errno = ENOENT;
1929     return NULL;
1930 }
1931
1932 char *pa_find_config_file(const char *global, const char *local, const char *env) {
1933     const char *fn;
1934
1935     if (env && (fn = getenv(env))) {
1936         if (access(fn, R_OK) == 0)
1937             return pa_xstrdup(fn);
1938
1939         pa_log_warn("Failed to access configuration file '%s': %s", fn, pa_cstrerror(errno));
1940         return NULL;
1941     }
1942
1943     if (local) {
1944         const char *e;
1945         char *lfn;
1946         char *h;
1947
1948         if ((e = getenv("PULSE_CONFIG_PATH")))
1949             fn = lfn = pa_sprintf_malloc("%s" PA_PATH_SEP "%s", e, local);
1950         else if ((h = pa_get_home_dir_malloc())) {
1951             fn = lfn = pa_sprintf_malloc("%s" PA_PATH_SEP ".pulse" PA_PATH_SEP "%s", h, local);
1952             pa_xfree(h);
1953         } else
1954             return NULL;
1955
1956         if (access(fn, R_OK) == 0) {
1957             char *r = pa_xstrdup(fn);
1958             pa_xfree(lfn);
1959             return r;
1960         }
1961
1962         if (errno != ENOENT) {
1963             pa_log_warn("Failed to access configuration file '%s': %s", fn, pa_cstrerror(errno));
1964             pa_xfree(lfn);
1965             return NULL;
1966         }
1967
1968         pa_xfree(lfn);
1969     }
1970
1971     if (global) {
1972         char *gfn;
1973
1974 #ifdef OS_IS_WIN32
1975         if (strncmp(global, PA_DEFAULT_CONFIG_DIR, strlen(PA_DEFAULT_CONFIG_DIR)) == 0)
1976             gfn = pa_sprintf_malloc("%s" PA_PATH_SEP "etc" PA_PATH_SEP "pulse%s",
1977                                     pa_win32_get_toplevel(NULL),
1978                                     global + strlen(PA_DEFAULT_CONFIG_DIR));
1979         else
1980 #endif
1981         gfn = pa_xstrdup(global);
1982
1983         if (access(gfn, R_OK) == 0)
1984             return gfn;
1985         pa_xfree(gfn);
1986     }
1987
1988     errno = ENOENT;
1989
1990     return NULL;
1991 }
1992
1993 /* Format the specified data as a hexademical string */
1994 char *pa_hexstr(const uint8_t* d, size_t dlength, char *s, size_t slength) {
1995     size_t i = 0, j = 0;
1996     const char hex[] = "0123456789abcdef";
1997
1998     pa_assert(d);
1999     pa_assert(s);
2000     pa_assert(slength > 0);
2001
2002     while (j+2 < slength && i < dlength) {
2003         s[j++] = hex[*d >> 4];
2004         s[j++] = hex[*d & 0xF];
2005
2006         d++;
2007         i++;
2008     }
2009
2010     s[j < slength ? j : slength] = 0;
2011     return s;
2012 }
2013
2014 /* Convert a hexadecimal digit to a number or -1 if invalid */
2015 static int hexc(char c) {
2016     if (c >= '0' && c <= '9')
2017         return c - '0';
2018
2019     if (c >= 'A' && c <= 'F')
2020         return c - 'A' + 10;
2021
2022     if (c >= 'a' && c <= 'f')
2023         return c - 'a' + 10;
2024
2025     errno = EINVAL;
2026     return -1;
2027 }
2028
2029 /* Parse a hexadecimal string as created by pa_hexstr() to a BLOB */
2030 size_t pa_parsehex(const char *p, uint8_t *d, size_t dlength) {
2031     size_t j = 0;
2032
2033     pa_assert(p);
2034     pa_assert(d);
2035
2036     while (j < dlength && *p) {
2037         int b;
2038
2039         if ((b = hexc(*(p++))) < 0)
2040             return (size_t) -1;
2041
2042         d[j] = (uint8_t) (b << 4);
2043
2044         if (!*p)
2045             return (size_t) -1;
2046
2047         if ((b = hexc(*(p++))) < 0)
2048             return (size_t) -1;
2049
2050         d[j] |= (uint8_t) b;
2051         j++;
2052     }
2053
2054     return j;
2055 }
2056
2057 /* Returns nonzero when *s starts with *pfx */
2058 bool pa_startswith(const char *s, const char *pfx) {
2059     size_t l;
2060
2061     pa_assert(s);
2062     pa_assert(pfx);
2063
2064     l = strlen(pfx);
2065
2066     return strlen(s) >= l && strncmp(s, pfx, l) == 0;
2067 }
2068
2069 /* Returns nonzero when *s ends with *sfx */
2070 bool pa_endswith(const char *s, const char *sfx) {
2071     size_t l1, l2;
2072
2073     pa_assert(s);
2074     pa_assert(sfx);
2075
2076     l1 = strlen(s);
2077     l2 = strlen(sfx);
2078
2079     return l1 >= l2 && pa_streq(s + l1 - l2, sfx);
2080 }
2081
2082 bool pa_is_path_absolute(const char *fn) {
2083     pa_assert(fn);
2084
2085 #ifndef OS_IS_WIN32
2086     return *fn == '/';
2087 #else
2088     return strlen(fn) >= 3 && isalpha(fn[0]) && fn[1] == ':' && fn[2] == '\\';
2089 #endif
2090 }
2091
2092 char *pa_make_path_absolute(const char *p) {
2093     char *r;
2094     char *cwd;
2095
2096     pa_assert(p);
2097
2098     if (pa_is_path_absolute(p))
2099         return pa_xstrdup(p);
2100
2101     if (!(cwd = pa_getcwd()))
2102         return pa_xstrdup(p);
2103
2104     r = pa_sprintf_malloc("%s" PA_PATH_SEP "%s", cwd, p);
2105     pa_xfree(cwd);
2106     return r;
2107 }
2108
2109 /* If fn is NULL, return the PulseAudio runtime or state dir (depending on the
2110  * rt parameter). If fn is non-NULL and starts with /, return fn. Otherwise,
2111  * append fn to the runtime/state dir and return it. */
2112 static char *get_path(const char *fn, bool prependmid, bool rt) {
2113     char *rtp;
2114
2115     rtp = rt ? pa_get_runtime_dir() : pa_get_state_dir();
2116
2117     if (fn) {
2118         char *r, *canonical_rtp;
2119
2120         if (pa_is_path_absolute(fn)) {
2121             pa_xfree(rtp);
2122             return pa_xstrdup(fn);
2123         }
2124
2125         if (!rtp)
2126             return NULL;
2127
2128         /* Hopefully make the path smaller to avoid 108 char limit (fdo#44680) */
2129         if ((canonical_rtp = pa_realpath(rtp))) {
2130             if (strlen(rtp) >= strlen(canonical_rtp))
2131                 pa_xfree(rtp);
2132             else {
2133                 pa_xfree(canonical_rtp);
2134                 canonical_rtp = rtp;
2135             }
2136         } else
2137             canonical_rtp = rtp;
2138
2139         if (prependmid) {
2140             char *mid;
2141
2142             if (!(mid = pa_machine_id())) {
2143                 pa_xfree(canonical_rtp);
2144                 return NULL;
2145             }
2146
2147             r = pa_sprintf_malloc("%s" PA_PATH_SEP "%s-%s", canonical_rtp, mid, fn);
2148             pa_xfree(mid);
2149         } else
2150             r = pa_sprintf_malloc("%s" PA_PATH_SEP "%s", canonical_rtp, fn);
2151
2152         pa_xfree(canonical_rtp);
2153         return r;
2154     } else
2155         return rtp;
2156 }
2157
2158 char *pa_runtime_path(const char *fn) {
2159     return get_path(fn, false, true);
2160 }
2161
2162 char *pa_state_path(const char *fn, bool appendmid) {
2163     return get_path(fn, appendmid, false);
2164 }
2165
2166 /* Convert the string s to a signed integer in *ret_i */
2167 int pa_atoi(const char *s, int32_t *ret_i) {
2168     long l;
2169
2170     pa_assert(s);
2171     pa_assert(ret_i);
2172
2173     if (pa_atol(s, &l) < 0)
2174         return -1;
2175
2176     if ((int32_t) l != l) {
2177         errno = ERANGE;
2178         return -1;
2179     }
2180
2181     *ret_i = (int32_t) l;
2182
2183     return 0;
2184 }
2185
2186 /* Convert the string s to an unsigned integer in *ret_u */
2187 int pa_atou(const char *s, uint32_t *ret_u) {
2188     char *x = NULL;
2189     unsigned long l;
2190
2191     pa_assert(s);
2192     pa_assert(ret_u);
2193
2194     /* strtoul() ignores leading spaces. We don't. */
2195     if (isspace((unsigned char)*s)) {
2196         errno = EINVAL;
2197         return -1;
2198     }
2199
2200     /* strtoul() accepts strings that start with a minus sign. In that case the
2201      * original negative number gets negated, and strtoul() returns the negated
2202      * result. We don't want that kind of behaviour. strtoul() also allows a
2203      * leading plus sign, which is also a thing that we don't want. */
2204     if (*s == '-' || *s == '+') {
2205         errno = EINVAL;
2206         return -1;
2207     }
2208
2209     errno = 0;
2210     l = strtoul(s, &x, 0);
2211
2212     /* If x doesn't point to the end of s, there was some trailing garbage in
2213      * the string. If x points to s, no conversion was done (empty string). */
2214     if (!x || *x || x == s || errno) {
2215         if (!errno)
2216             errno = EINVAL;
2217         return -1;
2218     }
2219
2220     if ((uint32_t) l != l) {
2221         errno = ERANGE;
2222         return -1;
2223     }
2224
2225     *ret_u = (uint32_t) l;
2226
2227     return 0;
2228 }
2229
2230 /* Convert the string s to a signed long integer in *ret_l. */
2231 int pa_atol(const char *s, long *ret_l) {
2232     char *x = NULL;
2233     long l;
2234
2235     pa_assert(s);
2236     pa_assert(ret_l);
2237
2238     /* strtol() ignores leading spaces. We don't. */
2239     if (isspace((unsigned char)*s)) {
2240         errno = EINVAL;
2241         return -1;
2242     }
2243
2244     /* strtol() accepts leading plus signs, but that's ugly, so we don't allow
2245      * that. */
2246     if (*s == '+') {
2247         errno = EINVAL;
2248         return -1;
2249     }
2250
2251     errno = 0;
2252     l = strtol(s, &x, 0);
2253
2254     /* If x doesn't point to the end of s, there was some trailing garbage in
2255      * the string. If x points to s, no conversion was done (at least an empty
2256      * string can trigger this). */
2257     if (!x || *x || x == s || errno) {
2258         if (!errno)
2259             errno = EINVAL;
2260         return -1;
2261     }
2262
2263     *ret_l = l;
2264
2265     return 0;
2266 }
2267
2268 #ifdef HAVE_STRTOD_L
2269 static locale_t c_locale = NULL;
2270
2271 static void c_locale_destroy(void) {
2272     freelocale(c_locale);
2273 }
2274 #endif
2275
2276 int pa_atod(const char *s, double *ret_d) {
2277     char *x = NULL;
2278     double f;
2279
2280     pa_assert(s);
2281     pa_assert(ret_d);
2282
2283     /* strtod() ignores leading spaces. We don't. */
2284     if (isspace((unsigned char)*s)) {
2285         errno = EINVAL;
2286         return -1;
2287     }
2288
2289     /* strtod() accepts leading plus signs, but that's ugly, so we don't allow
2290      * that. */
2291     if (*s == '+') {
2292         errno = EINVAL;
2293         return -1;
2294     }
2295
2296     /* This should be locale independent */
2297
2298 #ifdef HAVE_STRTOD_L
2299
2300     PA_ONCE_BEGIN {
2301
2302         if ((c_locale = newlocale(LC_ALL_MASK, "C", NULL)))
2303             atexit(c_locale_destroy);
2304
2305     } PA_ONCE_END;
2306
2307     if (c_locale) {
2308         errno = 0;
2309         f = strtod_l(s, &x, c_locale);
2310     } else
2311 #endif
2312     {
2313         errno = 0;
2314         f = strtod(s, &x);
2315     }
2316
2317     /* If x doesn't point to the end of s, there was some trailing garbage in
2318      * the string. If x points to s, no conversion was done (at least an empty
2319      * string can trigger this). */
2320     if (!x || *x || x == s || errno) {
2321         if (!errno)
2322             errno = EINVAL;
2323         return -1;
2324     }
2325
2326     if (isnan(f)) {
2327         errno = EINVAL;
2328         return -1;
2329     }
2330
2331     *ret_d = f;
2332
2333     return 0;
2334 }
2335
2336 /* Same as snprintf, but guarantees NUL-termination on every platform */
2337 size_t pa_snprintf(char *str, size_t size, const char *format, ...) {
2338     size_t ret;
2339     va_list ap;
2340
2341     pa_assert(str);
2342     pa_assert(size > 0);
2343     pa_assert(format);
2344
2345     va_start(ap, format);
2346     ret = pa_vsnprintf(str, size, format, ap);
2347     va_end(ap);
2348
2349     return ret;
2350 }
2351
2352 /* Same as vsnprintf, but guarantees NUL-termination on every platform */
2353 size_t pa_vsnprintf(char *str, size_t size, const char *format, va_list ap) {
2354     int ret;
2355
2356     pa_assert(str);
2357     pa_assert(size > 0);
2358     pa_assert(format);
2359
2360     ret = vsnprintf(str, size, format, ap);
2361
2362     str[size-1] = 0;
2363
2364     if (ret < 0)
2365         return strlen(str);
2366
2367     if ((size_t) ret > size-1)
2368         return size-1;
2369
2370     return (size_t) ret;
2371 }
2372
2373 /* Truncate the specified string, but guarantee that the string
2374  * returned still validates as UTF8 */
2375 char *pa_truncate_utf8(char *c, size_t l) {
2376     pa_assert(c);
2377     pa_assert(pa_utf8_valid(c));
2378
2379     if (strlen(c) <= l)
2380         return c;
2381
2382     c[l] = 0;
2383
2384     while (l > 0 && !pa_utf8_valid(c))
2385         c[--l] = 0;
2386
2387     return c;
2388 }
2389
2390 char *pa_getcwd(void) {
2391     size_t l = 128;
2392
2393     for (;;) {
2394         char *p = pa_xmalloc(l);
2395         if (getcwd(p, l))
2396             return p;
2397
2398         if (errno != ERANGE) {
2399             pa_xfree(p);
2400             return NULL;
2401         }
2402
2403         pa_xfree(p);
2404         l *= 2;
2405     }
2406 }
2407
2408 void *pa_will_need(const void *p, size_t l) {
2409 #ifdef RLIMIT_MEMLOCK
2410     struct rlimit rlim;
2411 #endif
2412     const void *a;
2413     size_t size;
2414     int r = ENOTSUP;
2415     size_t bs;
2416     const size_t page_size = pa_page_size();
2417
2418     pa_assert(p);
2419     pa_assert(l > 0);
2420
2421     a = PA_PAGE_ALIGN_PTR(p);
2422     size = (size_t) ((const uint8_t*) p + l - (const uint8_t*) a);
2423
2424 #ifdef HAVE_POSIX_MADVISE
2425     if ((r = posix_madvise((void*) a, size, POSIX_MADV_WILLNEED)) == 0) {
2426         pa_log_debug("posix_madvise() worked fine!");
2427         return (void*) p;
2428     }
2429 #endif
2430
2431     /* Most likely the memory was not mmap()ed from a file and thus
2432      * madvise() didn't work, so let's misuse mlock() do page this
2433      * stuff back into RAM. Yeah, let's fuck with the MM!  It's so
2434      * inviting, the man page of mlock() tells us: "All pages that
2435      * contain a part of the specified address range are guaranteed to
2436      * be resident in RAM when the call returns successfully." */
2437
2438 #ifdef RLIMIT_MEMLOCK
2439     pa_assert_se(getrlimit(RLIMIT_MEMLOCK, &rlim) == 0);
2440
2441     if (rlim.rlim_cur < page_size) {
2442         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));
2443         errno = EPERM;
2444         return (void*) p;
2445     }
2446
2447     bs = PA_PAGE_ALIGN((size_t) rlim.rlim_cur);
2448 #else
2449     bs = page_size*4;
2450 #endif
2451
2452     pa_log_debug("posix_madvise() failed (or doesn't exist), trying mlock(): %s", pa_cstrerror(r));
2453
2454 #ifdef HAVE_MLOCK
2455     while (size > 0 && bs > 0) {
2456
2457         if (bs > size)
2458             bs = size;
2459
2460         if (mlock(a, bs) < 0) {
2461             bs = PA_PAGE_ALIGN(bs / 2);
2462             continue;
2463         }
2464
2465         pa_assert_se(munlock(a, bs) == 0);
2466
2467         a = (const uint8_t*) a + bs;
2468         size -= bs;
2469     }
2470 #endif
2471
2472     if (bs <= 0)
2473         pa_log_debug("mlock() failed too (or doesn't exist), giving up: %s", pa_cstrerror(errno));
2474     else
2475         pa_log_debug("mlock() worked fine!");
2476
2477     return (void*) p;
2478 }
2479
2480 void pa_close_pipe(int fds[2]) {
2481     pa_assert(fds);
2482
2483     if (fds[0] >= 0)
2484         pa_assert_se(pa_close(fds[0]) == 0);
2485
2486     if (fds[1] >= 0)
2487         pa_assert_se(pa_close(fds[1]) == 0);
2488
2489     fds[0] = fds[1] = -1;
2490 }
2491
2492 char *pa_readlink(const char *p) {
2493 #ifdef HAVE_READLINK
2494     size_t l = 100;
2495
2496     for (;;) {
2497         char *c;
2498         ssize_t n;
2499
2500         c = pa_xmalloc(l);
2501
2502         if ((n = readlink(p, c, l-1)) < 0) {
2503             pa_xfree(c);
2504             return NULL;
2505         }
2506
2507         if ((size_t) n < l-1) {
2508             c[n] = 0;
2509             return c;
2510         }
2511
2512         pa_xfree(c);
2513         l *= 2;
2514     }
2515 #else
2516     return NULL;
2517 #endif
2518 }
2519
2520 int pa_close_all(int except_fd, ...) {
2521     va_list ap;
2522     unsigned n = 0, i;
2523     int r, *p;
2524
2525     va_start(ap, except_fd);
2526
2527     if (except_fd >= 0)
2528         for (n = 1; va_arg(ap, int) >= 0; n++)
2529             ;
2530
2531     va_end(ap);
2532
2533     p = pa_xnew(int, n+1);
2534
2535     va_start(ap, except_fd);
2536
2537     i = 0;
2538     if (except_fd >= 0) {
2539         int fd;
2540         p[i++] = except_fd;
2541
2542         while ((fd = va_arg(ap, int)) >= 0)
2543             p[i++] = fd;
2544     }
2545     p[i] = -1;
2546
2547     va_end(ap);
2548
2549     r = pa_close_allv(p);
2550     pa_xfree(p);
2551
2552     return r;
2553 }
2554
2555 int pa_close_allv(const int except_fds[]) {
2556 #ifndef OS_IS_WIN32
2557     struct rlimit rl;
2558     int maxfd, fd;
2559
2560 #if defined(__linux__) || defined(__sun)
2561     int saved_errno;
2562     DIR *d;
2563
2564     if ((d = opendir("/proc/self/fd"))) {
2565
2566         struct dirent *de;
2567
2568         while ((de = readdir(d))) {
2569             bool found;
2570             long l;
2571             char *e = NULL;
2572             int i;
2573
2574             if (de->d_name[0] == '.')
2575                 continue;
2576
2577             errno = 0;
2578             l = strtol(de->d_name, &e, 10);
2579             if (errno != 0 || !e || *e) {
2580                 closedir(d);
2581                 errno = EINVAL;
2582                 return -1;
2583             }
2584
2585             fd = (int) l;
2586
2587             if ((long) fd != l) {
2588                 closedir(d);
2589                 errno = EINVAL;
2590                 return -1;
2591             }
2592
2593             if (fd < 3)
2594                 continue;
2595
2596             if (fd == dirfd(d))
2597                 continue;
2598
2599             found = false;
2600             for (i = 0; except_fds[i] >= 0; i++)
2601                 if (except_fds[i] == fd) {
2602                     found = true;
2603                     break;
2604                 }
2605
2606             if (found)
2607                 continue;
2608
2609             if (pa_close(fd) < 0) {
2610                 saved_errno = errno;
2611                 closedir(d);
2612                 errno = saved_errno;
2613
2614                 return -1;
2615             }
2616         }
2617
2618         closedir(d);
2619         return 0;
2620     }
2621
2622 #endif
2623
2624     if (getrlimit(RLIMIT_NOFILE, &rl) >= 0)
2625         maxfd = (int) rl.rlim_max;
2626     else
2627         maxfd = sysconf(_SC_OPEN_MAX);
2628
2629     for (fd = 3; fd < maxfd; fd++) {
2630         int i;
2631         bool found;
2632
2633         found = false;
2634         for (i = 0; except_fds[i] >= 0; i++)
2635             if (except_fds[i] == fd) {
2636                 found = true;
2637                 break;
2638             }
2639
2640         if (found)
2641             continue;
2642
2643         if (pa_close(fd) < 0 && errno != EBADF)
2644             return -1;
2645     }
2646 #endif  /* !OS_IS_WIN32 */
2647
2648     return 0;
2649 }
2650
2651 int pa_unblock_sigs(int except, ...) {
2652     va_list ap;
2653     unsigned n = 0, i;
2654     int r, *p;
2655
2656     va_start(ap, except);
2657
2658     if (except >= 1)
2659         for (n = 1; va_arg(ap, int) >= 0; n++)
2660             ;
2661
2662     va_end(ap);
2663
2664     p = pa_xnew(int, n+1);
2665
2666     va_start(ap, except);
2667
2668     i = 0;
2669     if (except >= 1) {
2670         int sig;
2671         p[i++] = except;
2672
2673         while ((sig = va_arg(ap, int)) >= 0)
2674             p[i++] = sig;
2675     }
2676     p[i] = -1;
2677
2678     va_end(ap);
2679
2680     r = pa_unblock_sigsv(p);
2681     pa_xfree(p);
2682
2683     return r;
2684 }
2685
2686 int pa_unblock_sigsv(const int except[]) {
2687 #ifndef OS_IS_WIN32
2688     int i;
2689     sigset_t ss;
2690
2691     if (sigemptyset(&ss) < 0)
2692         return -1;
2693
2694     for (i = 0; except[i] > 0; i++)
2695         if (sigaddset(&ss, except[i]) < 0)
2696             return -1;
2697
2698     return sigprocmask(SIG_SETMASK, &ss, NULL);
2699 #else
2700     return 0;
2701 #endif
2702 }
2703
2704 int pa_reset_sigs(int except, ...) {
2705     va_list ap;
2706     unsigned n = 0, i;
2707     int *p, r;
2708
2709     va_start(ap, except);
2710
2711     if (except >= 1)
2712         for (n = 1; va_arg(ap, int) >= 0; n++)
2713             ;
2714
2715     va_end(ap);
2716
2717     p = pa_xnew(int, n+1);
2718
2719     va_start(ap, except);
2720
2721     i = 0;
2722     if (except >= 1) {
2723         int sig;
2724         p[i++] = except;
2725
2726         while ((sig = va_arg(ap, int)) >= 0)
2727             p[i++] = sig;
2728     }
2729     p[i] = -1;
2730
2731     va_end(ap);
2732
2733     r = pa_reset_sigsv(p);
2734     pa_xfree(p);
2735
2736     return r;
2737 }
2738
2739 int pa_reset_sigsv(const int except[]) {
2740 #ifndef OS_IS_WIN32
2741     int sig;
2742
2743     for (sig = 1; sig < NSIG; sig++) {
2744         bool reset = true;
2745
2746         switch (sig) {
2747             case SIGKILL:
2748             case SIGSTOP:
2749                 reset = false;
2750                 break;
2751
2752             default: {
2753                 int i;
2754
2755                 for (i = 0; except[i] > 0; i++) {
2756                     if (sig == except[i]) {
2757                         reset = false;
2758                         break;
2759                     }
2760                 }
2761             }
2762         }
2763
2764         if (reset) {
2765             struct sigaction sa;
2766
2767             memset(&sa, 0, sizeof(sa));
2768             sa.sa_handler = SIG_DFL;
2769
2770             /* On Linux the first two RT signals are reserved by
2771              * glibc, and sigaction() will return EINVAL for them. */
2772             if ((sigaction(sig, &sa, NULL) < 0))
2773                 if (errno != EINVAL)
2774                     return -1;
2775         }
2776     }
2777 #endif
2778
2779     return 0;
2780 }
2781
2782 void pa_set_env(const char *key, const char *value) {
2783     pa_assert(key);
2784     pa_assert(value);
2785
2786     /* This is not thread-safe */
2787
2788 #ifdef OS_IS_WIN32
2789     SetEnvironmentVariable(key, value);
2790 #else
2791     setenv(key, value, 1);
2792 #endif
2793 }
2794
2795 void pa_unset_env(const char *key) {
2796     pa_assert(key);
2797
2798     /* This is not thread-safe */
2799
2800 #ifdef OS_IS_WIN32
2801     SetEnvironmentVariable(key, NULL);
2802 #else
2803     unsetenv(key);
2804 #endif
2805 }
2806
2807 void pa_set_env_and_record(const char *key, const char *value) {
2808     pa_assert(key);
2809     pa_assert(value);
2810
2811     /* This is not thread-safe */
2812
2813     pa_set_env(key, value);
2814     recorded_env = pa_strlist_prepend(recorded_env, key);
2815 }
2816
2817 void pa_unset_env_recorded(void) {
2818
2819     /* This is not thread-safe */
2820
2821     for (;;) {
2822         char *s;
2823
2824         recorded_env = pa_strlist_pop(recorded_env, &s);
2825
2826         if (!s)
2827             break;
2828
2829         pa_unset_env(s);
2830         pa_xfree(s);
2831     }
2832 }
2833
2834 bool pa_in_system_mode(void) {
2835     const char *e;
2836
2837     if (!(e = getenv("PULSE_SYSTEM")))
2838         return false;
2839
2840     return !!atoi(e);
2841 }
2842
2843 /* Checks a delimiters-separated list of words in haystack for needle */
2844 bool pa_str_in_list(const char *haystack, const char *delimiters, const char *needle) {
2845     char *s;
2846     const char *state = NULL;
2847
2848     if (!haystack || !needle)
2849         return false;
2850
2851     while ((s = pa_split(haystack, delimiters, &state))) {
2852         if (pa_streq(needle, s)) {
2853             pa_xfree(s);
2854             return true;
2855         }
2856
2857         pa_xfree(s);
2858     }
2859
2860     return false;
2861 }
2862
2863 /* Checks a whitespace-separated list of words in haystack for needle */
2864 bool pa_str_in_list_spaces(const char *haystack, const char *needle) {
2865     const char *s;
2866     size_t n;
2867     const char *state = NULL;
2868
2869     if (!haystack || !needle)
2870         return false;
2871
2872     while ((s = pa_split_spaces_in_place(haystack, &n, &state))) {
2873         if (pa_strneq(needle, s, n))
2874             return true;
2875     }
2876
2877     return false;
2878 }
2879
2880 char *pa_get_user_name_malloc(void) {
2881     ssize_t k;
2882     char *u;
2883
2884 #ifdef _SC_LOGIN_NAME_MAX
2885     k = (ssize_t) sysconf(_SC_LOGIN_NAME_MAX);
2886
2887     if (k <= 0)
2888 #endif
2889         k = 32;
2890
2891     u = pa_xnew(char, k+1);
2892
2893     if (!(pa_get_user_name(u, k))) {
2894         pa_xfree(u);
2895         return NULL;
2896     }
2897
2898     return u;
2899 }
2900
2901 char *pa_get_host_name_malloc(void) {
2902     size_t l;
2903
2904     l = 100;
2905     for (;;) {
2906         char *c;
2907
2908         c = pa_xmalloc(l);
2909
2910         if (!pa_get_host_name(c, l)) {
2911
2912             if (errno != EINVAL && errno != ENAMETOOLONG)
2913                 break;
2914
2915         } else if (strlen(c) < l-1) {
2916             char *u;
2917
2918             if (*c == 0) {
2919                 pa_xfree(c);
2920                 break;
2921             }
2922
2923             u = pa_utf8_filter(c);
2924             pa_xfree(c);
2925             return u;
2926         }
2927
2928         /* Hmm, the hostname is as long the space we offered the
2929          * function, we cannot know if it fully fit in, so let's play
2930          * safe and retry. */
2931
2932         pa_xfree(c);
2933         l *= 2;
2934     }
2935
2936     return NULL;
2937 }
2938
2939 char *pa_machine_id(void) {
2940     FILE *f;
2941     char *h;
2942
2943     /* The returned value is supposed be some kind of ascii identifier
2944      * that is unique and stable across reboots. First we try if the machine-id
2945      * file is available. If it's available, that's great, since it provides an
2946      * identifier that suits our needs perfectly. If it's not, we fall back to
2947      * the hostname, which is not as good, since it can change over time. */
2948
2949     /* We search for the machine-id file from four locations. The first two are
2950      * relative to the configured installation prefix, but if we're installed
2951      * under /usr/local, for example, it's likely that the machine-id won't be
2952      * found there, so we also try the hardcoded paths.
2953      *
2954      * PA_MACHINE_ID or PA_MACHINE_ID_FALLBACK might exist on a Windows system,
2955      * but the last two hardcoded paths certainly don't, hence we don't try
2956      * them on Windows. */
2957     if ((f = pa_fopen_cloexec(PA_MACHINE_ID, "r")) ||
2958         (f = pa_fopen_cloexec(PA_MACHINE_ID_FALLBACK, "r")) ||
2959 #if !defined(OS_IS_WIN32)
2960         (f = pa_fopen_cloexec("/etc/machine-id", "r")) ||
2961         (f = pa_fopen_cloexec("/var/lib/dbus/machine-id", "r"))
2962 #else
2963         false
2964 #endif
2965         ) {
2966         char ln[34] = "", *r;
2967
2968         r = fgets(ln, sizeof(ln)-1, f);
2969         fclose(f);
2970
2971         pa_strip_nl(ln);
2972
2973         if (r && ln[0])
2974             return pa_utf8_filter(ln);
2975     }
2976
2977     if ((h = pa_get_host_name_malloc()))
2978         return h;
2979
2980 #if !defined(OS_IS_WIN32) && !defined(__ANDROID__)
2981     /* If no hostname was set we use the POSIX hostid. It's usually
2982      * the IPv4 address.  Might not be that stable. */
2983     return pa_sprintf_malloc("%08lx", (unsigned long) gethostid());
2984 #else
2985     return NULL;
2986 #endif
2987 }
2988
2989 char *pa_session_id(void) {
2990     const char *e;
2991
2992     e = getenv("XDG_SESSION_ID");
2993     if (!e)
2994         return NULL;
2995
2996     return pa_utf8_filter(e);
2997 }
2998
2999 char *pa_uname_string(void) {
3000 #ifdef HAVE_UNAME
3001     struct utsname u;
3002
3003     pa_assert_se(uname(&u) >= 0);
3004
3005     return pa_sprintf_malloc("%s %s %s %s", u.sysname, u.machine, u.release, u.version);
3006 #endif
3007 #ifdef OS_IS_WIN32
3008     OSVERSIONINFO i;
3009
3010     pa_zero(i);
3011     i.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
3012     pa_assert_se(GetVersionEx(&i));
3013
3014     return pa_sprintf_malloc("Windows %d.%d (%d) %s", i.dwMajorVersion, i.dwMinorVersion, i.dwBuildNumber, i.szCSDVersion);
3015 #endif
3016 }
3017
3018 #ifdef HAVE_VALGRIND_MEMCHECK_H
3019 bool pa_in_valgrind(void) {
3020     static int b = 0;
3021
3022     /* To make heisenbugs a bit simpler to find we check for $VALGRIND
3023      * here instead of really checking whether we run in valgrind or
3024      * not. */
3025
3026     if (b < 1)
3027         b = getenv("VALGRIND") ? 2 : 1;
3028
3029     return b > 1;
3030 }
3031 #endif
3032
3033 unsigned pa_gcd(unsigned a, unsigned b) {
3034
3035     while (b > 0) {
3036         unsigned t = b;
3037         b = a % b;
3038         a = t;
3039     }
3040
3041     return a;
3042 }
3043
3044 void pa_reduce(unsigned *num, unsigned *den) {
3045
3046     unsigned gcd = pa_gcd(*num, *den);
3047
3048     if (gcd <= 0)
3049         return;
3050
3051     *num /= gcd;
3052     *den /= gcd;
3053
3054     pa_assert(pa_gcd(*num, *den) == 1);
3055 }
3056
3057 unsigned pa_ncpus(void) {
3058     long ncpus;
3059
3060 #ifdef _SC_NPROCESSORS_ONLN
3061     ncpus = sysconf(_SC_NPROCESSORS_ONLN);
3062 #else
3063     ncpus = 1;
3064 #endif
3065
3066     return ncpus <= 0 ? 1 : (unsigned) ncpus;
3067 }
3068
3069 char *pa_replace(const char*s, const char*a, const char *b) {
3070     pa_strbuf *sb;
3071     size_t an;
3072
3073     pa_assert(s);
3074     pa_assert(a);
3075     pa_assert(*a);
3076     pa_assert(b);
3077
3078     an = strlen(a);
3079     sb = pa_strbuf_new();
3080
3081     for (;;) {
3082         const char *p;
3083
3084         if (!(p = strstr(s, a)))
3085             break;
3086
3087         pa_strbuf_putsn(sb, s, p-s);
3088         pa_strbuf_puts(sb, b);
3089         s = p + an;
3090     }
3091
3092     pa_strbuf_puts(sb, s);
3093
3094     return pa_strbuf_to_string_free(sb);
3095 }
3096
3097 char *pa_escape(const char *p, const char *chars) {
3098     const char *s;
3099     const char *c;
3100     char *out_string, *output;
3101     int char_count = strlen(p);
3102
3103     /* Maximum number of characters in output string
3104      * including trailing 0. */
3105     char_count = 2 * char_count + 1;
3106
3107     /* allocate output string */
3108     out_string = pa_xmalloc(char_count);
3109     output = out_string;
3110
3111     /* write output string */
3112     for (s = p; *s; ++s) {
3113         if (*s == '\\')
3114             *output++ = '\\';
3115         else if (chars) {
3116             for (c = chars; *c; ++c) {
3117                 if (*s == *c) {
3118                     *output++ = '\\';
3119                     break;
3120                 }
3121             }
3122         }
3123         *output++ = *s;
3124     }
3125
3126     *output = 0;
3127
3128     /* Remove trailing garbage */
3129     output = pa_xstrdup(out_string);
3130
3131     pa_xfree(out_string);
3132     return output;
3133 }
3134
3135 char *pa_unescape(char *p) {
3136     char *s, *d;
3137     bool escaped = false;
3138
3139     for (s = p, d = p; *s; s++) {
3140         if (!escaped && *s == '\\') {
3141             escaped = true;
3142             continue;
3143         }
3144
3145         *(d++) = *s;
3146         escaped = false;
3147     }
3148
3149     *d = 0;
3150
3151     return p;
3152 }
3153
3154 char *pa_realpath(const char *path) {
3155     char *t;
3156     pa_assert(path);
3157
3158     /* We want only absolute paths */
3159     if (path[0] != '/') {
3160         errno = EINVAL;
3161         return NULL;
3162     }
3163
3164 #if defined(__GLIBC__)
3165     {
3166         char *r;
3167
3168         if (!(r = realpath(path, NULL)))
3169             return NULL;
3170
3171         /* We copy this here in case our pa_xmalloc() is not
3172          * implemented on top of libc malloc() */
3173         t = pa_xstrdup(r);
3174         pa_xfree(r);
3175     }
3176 #elif defined(PATH_MAX)
3177     {
3178         char *path_buf;
3179         path_buf = pa_xmalloc(PATH_MAX);
3180
3181 #if defined(OS_IS_WIN32)
3182         if (!(t = _fullpath(path_buf, path, _MAX_PATH))) {
3183             pa_xfree(path_buf);
3184             return NULL;
3185         }
3186 #else
3187         if (!(t = realpath(path, path_buf))) {
3188             pa_xfree(path_buf);
3189             return NULL;
3190         }
3191 #endif
3192     }
3193 #else
3194 #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."
3195 #endif
3196
3197     return t;
3198 }
3199
3200 void pa_disable_sigpipe(void) {
3201
3202 #ifdef SIGPIPE
3203     struct sigaction sa;
3204
3205     pa_zero(sa);
3206
3207     if (sigaction(SIGPIPE, NULL, &sa) < 0) {
3208         pa_log("sigaction(): %s", pa_cstrerror(errno));
3209         return;
3210     }
3211
3212     sa.sa_handler = SIG_IGN;
3213
3214     if (sigaction(SIGPIPE, &sa, NULL) < 0) {
3215         pa_log("sigaction(): %s", pa_cstrerror(errno));
3216         return;
3217     }
3218 #endif
3219 }
3220
3221 void pa_xfreev(void**a) {
3222     void **p;
3223
3224     if (!a)
3225         return;
3226
3227     for (p = a; *p; p++)
3228         pa_xfree(*p);
3229
3230     pa_xfree(a);
3231 }
3232
3233 char **pa_split_spaces_strv(const char *s) {
3234     char **t, *e;
3235     unsigned i = 0, n = 8;
3236     const char *state = NULL;
3237
3238     t = pa_xnew(char*, n);
3239     while ((e = pa_split_spaces(s, &state))) {
3240         t[i++] = e;
3241
3242         if (i >= n) {
3243             n *= 2;
3244             t = pa_xrenew(char*, t, n);
3245         }
3246     }
3247
3248     if (i <= 0) {
3249         pa_xfree(t);
3250         return NULL;
3251     }
3252
3253     t[i] = NULL;
3254     return t;
3255 }
3256
3257 char* pa_maybe_prefix_path(const char *path, const char *prefix) {
3258     pa_assert(path);
3259
3260     if (pa_is_path_absolute(path))
3261         return pa_xstrdup(path);
3262
3263     return pa_sprintf_malloc("%s" PA_PATH_SEP "%s", prefix, path);
3264 }
3265
3266 size_t pa_pipe_buf(int fd) {
3267
3268 #ifdef _PC_PIPE_BUF
3269     long n;
3270
3271     if ((n = fpathconf(fd, _PC_PIPE_BUF)) >= 0)
3272         return (size_t) n;
3273 #endif
3274
3275 #ifdef PIPE_BUF
3276     return PIPE_BUF;
3277 #else
3278     return 4096;
3279 #endif
3280 }
3281
3282 void pa_reset_personality(void) {
3283
3284 #if defined(__linux__) && !defined(__ANDROID__)
3285     if (personality(PER_LINUX) < 0)
3286         pa_log_warn("Uh, personality() failed: %s", pa_cstrerror(errno));
3287 #endif
3288
3289 }
3290
3291 bool pa_run_from_build_tree(void) {
3292     static bool b = false;
3293
3294 #ifdef HAVE_RUNNING_FROM_BUILD_TREE
3295     char *rp;
3296     PA_ONCE_BEGIN {
3297         if ((rp = pa_readlink("/proc/self/exe"))) {
3298             b = pa_startswith(rp, PA_BUILDDIR);
3299             pa_xfree(rp);
3300         }
3301     } PA_ONCE_END;
3302 #endif
3303
3304     return b;
3305 }
3306
3307 const char *pa_get_temp_dir(void) {
3308     const char *t;
3309
3310     if ((t = getenv("TMPDIR")) &&
3311         pa_is_path_absolute(t))
3312         return t;
3313
3314     if ((t = getenv("TMP")) &&
3315         pa_is_path_absolute(t))
3316         return t;
3317
3318     if ((t = getenv("TEMP")) &&
3319         pa_is_path_absolute(t))
3320         return t;
3321
3322     if ((t = getenv("TEMPDIR")) &&
3323         pa_is_path_absolute(t))
3324         return t;
3325
3326     return "/tmp";
3327 }
3328
3329 int pa_open_cloexec(const char *fn, int flags, mode_t mode) {
3330     int fd;
3331
3332 #ifdef O_NOCTTY
3333     flags |= O_NOCTTY;
3334 #endif
3335
3336 #ifdef O_CLOEXEC
3337     if ((fd = open(fn, flags|O_CLOEXEC, mode)) >= 0)
3338         goto finish;
3339
3340     if (errno != EINVAL)
3341         return fd;
3342 #endif
3343
3344     if ((fd = open(fn, flags, mode)) >= 0)
3345         goto finish;
3346
3347     /* return error */
3348     return fd;
3349
3350 finish:
3351     /* Some implementations might simply ignore O_CLOEXEC if it is not
3352      * understood, make sure FD_CLOEXEC is enabled anyway */
3353
3354     pa_make_fd_cloexec(fd);
3355     return fd;
3356 }
3357
3358 int pa_socket_cloexec(int domain, int type, int protocol) {
3359     int fd;
3360
3361 #ifdef SOCK_CLOEXEC
3362     if ((fd = socket(domain, type | SOCK_CLOEXEC, protocol)) >= 0)
3363         goto finish;
3364
3365     if (errno != EINVAL)
3366         return fd;
3367 #endif
3368
3369     if ((fd = socket(domain, type, protocol)) >= 0)
3370         goto finish;
3371
3372     /* return error */
3373     return fd;
3374
3375 finish:
3376     /* Some implementations might simply ignore SOCK_CLOEXEC if it is
3377      * not understood, make sure FD_CLOEXEC is enabled anyway */
3378
3379     pa_make_fd_cloexec(fd);
3380     return fd;
3381 }
3382
3383 int pa_pipe_cloexec(int pipefd[2]) {
3384     int r;
3385
3386 #ifdef HAVE_PIPE2
3387     if ((r = pipe2(pipefd, O_CLOEXEC)) >= 0)
3388         goto finish;
3389
3390     if (errno == EMFILE) {
3391         pa_log_error("The per-process limit on the number of open file descriptors has been reached.");
3392         return r;
3393     }
3394
3395     if (errno == ENFILE) {
3396         pa_log_error("The system-wide limit on the total number of open files has been reached.");
3397         return r;
3398     }
3399
3400     if (errno != EINVAL && errno != ENOSYS)
3401         return r;
3402
3403 #endif
3404
3405     if ((r = pipe(pipefd)) >= 0)
3406         goto finish;
3407
3408     if (errno == EMFILE) {
3409         pa_log_error("The per-process limit on the number of open file descriptors has been reached.");
3410         return r;
3411     }
3412
3413     if (errno == ENFILE) {
3414         pa_log_error("The system-wide limit on the total number of open files has been reached.");
3415         return r;
3416     }
3417
3418     /* return error */
3419     return r;
3420
3421 finish:
3422     pa_make_fd_cloexec(pipefd[0]);
3423     pa_make_fd_cloexec(pipefd[1]);
3424
3425     return 0;
3426 }
3427
3428 int pa_accept_cloexec(int sockfd, struct sockaddr *addr, socklen_t *addrlen) {
3429     int fd;
3430
3431     errno = 0;
3432
3433 #ifdef HAVE_ACCEPT4
3434     if ((fd = accept4(sockfd, addr, addrlen, SOCK_CLOEXEC)) >= 0)
3435         goto finish;
3436
3437     if (errno != EINVAL && errno != ENOSYS)
3438         return fd;
3439
3440 #endif
3441
3442 #ifdef HAVE_PACCEPT
3443     if ((fd = paccept(sockfd, addr, addrlen, NULL, SOCK_CLOEXEC)) >= 0)
3444         goto finish;
3445 #endif
3446
3447     if ((fd = accept(sockfd, addr, addrlen)) >= 0)
3448         goto finish;
3449
3450     /* return error */
3451     return fd;
3452
3453 finish:
3454     pa_make_fd_cloexec(fd);
3455     return fd;
3456 }
3457
3458 FILE* pa_fopen_cloexec(const char *path, const char *mode) {
3459     FILE *f;
3460     char *m;
3461
3462     m = pa_sprintf_malloc("%se", mode);
3463
3464     errno = 0;
3465     if ((f = fopen(path, m))) {
3466         pa_xfree(m);
3467         goto finish;
3468     }
3469
3470     pa_xfree(m);
3471
3472     if (errno != EINVAL)
3473         return NULL;
3474
3475     if (!(f = fopen(path, mode)))
3476         return NULL;
3477
3478 finish:
3479     pa_make_fd_cloexec(fileno(f));
3480     return f;
3481 }
3482
3483 void pa_nullify_stdfds(void) {
3484
3485 #ifndef OS_IS_WIN32
3486         pa_close(STDIN_FILENO);
3487         pa_close(STDOUT_FILENO);
3488         pa_close(STDERR_FILENO);
3489
3490         pa_assert_se(open("/dev/null", O_RDONLY) == STDIN_FILENO);
3491         pa_assert_se(open("/dev/null", O_WRONLY) == STDOUT_FILENO);
3492         pa_assert_se(open("/dev/null", O_WRONLY) == STDERR_FILENO);
3493 #else
3494         FreeConsole();
3495 #endif
3496
3497 }
3498
3499 char *pa_read_line_from_file(const char *fn) {
3500     FILE *f;
3501     char ln[256] = "", *r;
3502
3503     if (!(f = pa_fopen_cloexec(fn, "r")))
3504         return NULL;
3505
3506     r = fgets(ln, sizeof(ln)-1, f);
3507     fclose(f);
3508
3509     if (!r) {
3510         errno = EIO;
3511         return NULL;
3512     }
3513
3514     pa_strip_nl(ln);
3515     return pa_xstrdup(ln);
3516 }
3517
3518 bool pa_running_in_vm(void) {
3519
3520 #if defined(__i386__) || defined(__x86_64__)
3521
3522     /* Both CPUID and DMI are x86 specific interfaces... */
3523
3524 #ifdef HAVE_CPUID_H
3525     unsigned int eax, ebx, ecx, edx;
3526 #endif
3527
3528 #ifdef __linux__
3529     const char *const dmi_vendors[] = {
3530         "/sys/class/dmi/id/sys_vendor",
3531         "/sys/class/dmi/id/board_vendor",
3532         "/sys/class/dmi/id/bios_vendor"
3533     };
3534
3535     unsigned i;
3536
3537     for (i = 0; i < PA_ELEMENTSOF(dmi_vendors); i++) {
3538         char *s;
3539
3540         if ((s = pa_read_line_from_file(dmi_vendors[i]))) {
3541
3542             if (pa_startswith(s, "QEMU") ||
3543                 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3544                 pa_startswith(s, "VMware") ||
3545                 pa_startswith(s, "VMW") ||
3546                 pa_startswith(s, "Microsoft Corporation") ||
3547                 pa_startswith(s, "innotek GmbH") ||
3548                 pa_startswith(s, "Xen")) {
3549
3550                 pa_xfree(s);
3551                 return true;
3552             }
3553
3554             pa_xfree(s);
3555         }
3556     }
3557
3558 #endif
3559
3560 #ifdef HAVE_CPUID_H
3561
3562     /* Hypervisors provide presence on 0x1 cpuid leaf.
3563      * http://lwn.net/Articles/301888/ */
3564     if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) == 0)
3565         return false;
3566
3567     if (ecx & 0x80000000)
3568         return true;
3569
3570 #endif /* HAVE_CPUID_H */
3571
3572 #endif /* defined(__i386__) || defined(__x86_64__) */
3573
3574     return false;
3575 }
3576
3577 size_t pa_page_size(void) {
3578 #if defined(PAGE_SIZE)
3579     return PAGE_SIZE;
3580 #elif defined(PAGESIZE)
3581     return PAGESIZE;
3582 #elif defined(HAVE_SYSCONF)
3583     static size_t page_size = 4096; /* Let's hope it's like x86. */
3584
3585     PA_ONCE_BEGIN {
3586         long ret = sysconf(_SC_PAGE_SIZE);
3587         if (ret > 0)
3588             page_size = ret;
3589     } PA_ONCE_END;
3590
3591     return page_size;
3592 #else
3593     return 4096;
3594 #endif
3595 }