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