]> code.delx.au - pulseaudio/blob - src/pulsecore/core-util.c
s/POLYP/PULSE/g
[pulseaudio] / src / pulsecore / core-util.c
1 /* $Id$ */
2
3 /***
4 This file is part of PulseAudio.
5
6 PulseAudio is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as
8 published by the Free Software Foundation; either version 2.1 of the
9 License, or (at your option) any later version.
10
11 PulseAudio is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public
17 License along with PulseAudio; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19 USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdarg.h>
27 #include <stdlib.h>
28 #include <signal.h>
29 #include <errno.h>
30 #include <assert.h>
31 #include <string.h>
32 #include <stdio.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35 #include <limits.h>
36 #include <time.h>
37 #include <ctype.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <sys/time.h>
41
42 #ifdef HAVE_SCHED_H
43 #include <sched.h>
44 #endif
45
46 #ifdef HAVE_SYS_RESOURCE_H
47 #include <sys/resource.h>
48 #endif
49
50 #ifdef HAVE_PTHREAD
51 #include <pthread.h>
52 #endif
53
54 #ifdef HAVE_NETDB_H
55 #include <netdb.h>
56 #endif
57
58 #ifdef HAVE_WINDOWS_H
59 #include <windows.h>
60 #endif
61
62 #ifdef HAVE_PWD_H
63 #include <pwd.h>
64 #endif
65
66 #ifdef HAVE_GRP_H
67 #include <grp.h>
68 #endif
69
70 #include <samplerate.h>
71
72 #include <pulse/xmalloc.h>
73 #include <pulse/util.h>
74
75 #include <pulsecore/core-error.h>
76 #include <pulsecore/winsock.h>
77 #include <pulsecore/log.h>
78
79 #include "core-util.h"
80
81 #ifndef OS_IS_WIN32
82 #define PA_RUNTIME_PATH_PREFIX "/tmp/pulse-"
83 #define PATH_SEP '/'
84 #else
85 #define PA_RUNTIME_PATH_PREFIX "%TEMP%\\pulse-"
86 #define PATH_SEP '\\'
87 #endif
88
89 #ifdef OS_IS_WIN32
90
91 #define PULSE_ROOTENV "PULSE_ROOT"
92
93 int pa_set_root(HANDLE handle) {
94 char library_path[MAX_PATH + sizeof(PULSE_ROOTENV) + 1], *sep;
95
96 strcpy(library_path, PULSE_ROOTENV "=");
97
98 if (!GetModuleFileName(handle, library_path + sizeof(PULSE_ROOTENV), MAX_PATH))
99 return 0;
100
101 sep = strrchr(library_path, '\\');
102 if (sep)
103 *sep = '\0';
104
105 if (_putenv(library_path) < 0)
106 return 0;
107
108 return 1;
109 }
110
111 #endif
112
113 /** Make a file descriptor nonblock. Doesn't do any error checking */
114 void pa_make_nonblock_fd(int fd) {
115 #ifdef O_NONBLOCK
116 int v;
117 assert(fd >= 0);
118
119 if ((v = fcntl(fd, F_GETFL)) >= 0)
120 if (!(v & O_NONBLOCK))
121 fcntl(fd, F_SETFL, v|O_NONBLOCK);
122 #elif defined(OS_IS_WIN32)
123 u_long arg = 1;
124 if (ioctlsocket(fd, FIONBIO, &arg) < 0) {
125 if (WSAGetLastError() == WSAENOTSOCK)
126 pa_log_warn(__FILE__": WARNING: Only sockets can be made non-blocking!");
127 }
128 #else
129 pa_log_warn(__FILE__": WARNING: Non-blocking I/O not supported.!");
130 #endif
131 }
132
133 /** Creates a directory securely */
134 int pa_make_secure_dir(const char* dir) {
135 struct stat st;
136 assert(dir);
137
138 #ifdef OS_IS_WIN32
139 if (mkdir(dir) < 0)
140 #else
141 if (mkdir(dir, 0700) < 0)
142 #endif
143 if (errno != EEXIST)
144 return -1;
145
146 #ifdef HAVE_CHOWN
147 chown(dir, getuid(), getgid());
148 #endif
149 #ifdef HAVE_CHMOD
150 chmod(dir, 0700);
151 #endif
152
153 #ifdef HAVE_LSTAT
154 if (lstat(dir, &st) < 0)
155 #else
156 if (stat(dir, &st) < 0)
157 #endif
158 goto fail;
159
160 #ifndef OS_IS_WIN32
161 if (!S_ISDIR(st.st_mode) || (st.st_uid != getuid()) || ((st.st_mode & 0777) != 0700))
162 goto fail;
163 #else
164 fprintf(stderr, "FIXME: pa_make_secure_dir()\n");
165 #endif
166
167 return 0;
168
169 fail:
170 rmdir(dir);
171 return -1;
172 }
173
174 /* Return a newly allocated sting containing the parent directory of the specified file */
175 char *pa_parent_dir(const char *fn) {
176 char *slash, *dir = pa_xstrdup(fn);
177
178 slash = (char*) pa_path_get_filename(dir);
179 if (slash == fn)
180 return NULL;
181
182 *(slash-1) = 0;
183 return dir;
184 }
185
186 /* Creates a the parent directory of the specified path securely */
187 int pa_make_secure_parent_dir(const char *fn) {
188 int ret = -1;
189 char *dir;
190
191 if (!(dir = pa_parent_dir(fn)))
192 goto finish;
193
194 if (pa_make_secure_dir(dir) < 0)
195 goto finish;
196
197 ret = 0;
198
199 finish:
200 pa_xfree(dir);
201 return ret;
202 }
203
204 /** Platform independent read function. Necessary since not all systems
205 * treat all file descriptors equal. */
206 ssize_t pa_read(int fd, void *buf, size_t count) {
207 ssize_t r;
208
209 #ifdef OS_IS_WIN32
210 r = recv(fd, buf, count, 0);
211 if (r < 0) {
212 if (WSAGetLastError() != WSAENOTSOCK) {
213 errno = WSAGetLastError();
214 return r;
215 }
216 }
217
218 if (r < 0)
219 #endif
220 r = read(fd, buf, count);
221
222 return r;
223 }
224
225 /** Similar to pa_read(), but handles writes */
226 ssize_t pa_write(int fd, const void *buf, size_t count) {
227 ssize_t r;
228
229 #ifdef OS_IS_WIN32
230 r = send(fd, buf, count, 0);
231 if (r < 0) {
232 if (WSAGetLastError() != WSAENOTSOCK) {
233 errno = WSAGetLastError();
234 return r;
235 }
236 }
237
238 if (r < 0)
239 #endif
240 r = write(fd, buf, count);
241
242 return r;
243 }
244
245 /** Calls read() in a loop. Makes sure that as much as 'size' bytes,
246 * unless EOF is reached or an error occured */
247 ssize_t pa_loop_read(int fd, void*data, size_t size) {
248 ssize_t ret = 0;
249 assert(fd >= 0 && data && size);
250
251 while (size > 0) {
252 ssize_t r;
253
254 if ((r = pa_read(fd, data, size)) < 0)
255 return r;
256
257 if (r == 0)
258 break;
259
260 ret += r;
261 data = (uint8_t*) data + r;
262 size -= r;
263 }
264
265 return ret;
266 }
267
268 /** Similar to pa_loop_read(), but wraps write() */
269 ssize_t pa_loop_write(int fd, const void*data, size_t size) {
270 ssize_t ret = 0;
271 assert(fd >= 0 && data && size);
272
273 while (size > 0) {
274 ssize_t r;
275
276 if ((r = pa_write(fd, data, size)) < 0)
277 return r;
278
279 if (r == 0)
280 break;
281
282 ret += r;
283 data = (const uint8_t*) data + r;
284 size -= r;
285 }
286
287 return ret;
288 }
289
290 /* Print a warning messages in case that the given signal is not
291 * blocked or trapped */
292 void pa_check_signal_is_blocked(int sig) {
293 #ifdef HAVE_SIGACTION
294 struct sigaction sa;
295 sigset_t set;
296
297 /* If POSIX threads are supported use thread-aware
298 * pthread_sigmask() function, to check if the signal is
299 * blocked. Otherwise fall back to sigprocmask() */
300
301 #ifdef HAVE_PTHREAD
302 if (pthread_sigmask(SIG_SETMASK, NULL, &set) < 0) {
303 #endif
304 if (sigprocmask(SIG_SETMASK, NULL, &set) < 0) {
305 pa_log(__FILE__": sigprocmask(): %s", pa_cstrerror(errno));
306 return;
307 }
308 #ifdef HAVE_PTHREAD
309 }
310 #endif
311
312 if (sigismember(&set, sig))
313 return;
314
315 /* Check whether the signal is trapped */
316
317 if (sigaction(sig, NULL, &sa) < 0) {
318 pa_log(__FILE__": sigaction(): %s", pa_cstrerror(errno));
319 return;
320 }
321
322 if (sa.sa_handler != SIG_DFL)
323 return;
324
325 pa_log(__FILE__": WARNING: %s is not trapped. This might cause malfunction!", pa_strsignal(sig));
326 #else /* HAVE_SIGACTION */
327 pa_log(__FILE__": WARNING: %s might not be trapped. This might cause malfunction!", pa_strsignal(sig));
328 #endif
329 }
330
331 /* The following function is based on an example from the GNU libc
332 * documentation. This function is similar to GNU's asprintf(). */
333 char *pa_sprintf_malloc(const char *format, ...) {
334 int size = 100;
335 char *c = NULL;
336
337 assert(format);
338
339 for(;;) {
340 int r;
341 va_list ap;
342
343 c = pa_xrealloc(c, size);
344
345 va_start(ap, format);
346 r = vsnprintf(c, size, format, ap);
347 va_end(ap);
348
349 if (r > -1 && r < size)
350 return c;
351
352 if (r > -1) /* glibc 2.1 */
353 size = r+1;
354 else /* glibc 2.0 */
355 size *= 2;
356 }
357 }
358
359 /* Same as the previous function, but use a va_list instead of an
360 * ellipsis */
361 char *pa_vsprintf_malloc(const char *format, va_list ap) {
362 int size = 100;
363 char *c = NULL;
364
365 assert(format);
366
367 for(;;) {
368 int r;
369 va_list aq;
370
371 va_copy(aq, ap);
372
373 c = pa_xrealloc(c, size);
374 r = vsnprintf(c, size, format, aq);
375
376 va_end(aq);
377
378 if (r > -1 && r < size)
379 return c;
380
381 if (r > -1) /* glibc 2.1 */
382 size = r+1;
383 else /* glibc 2.0 */
384 size *= 2;
385 }
386 }
387
388 /* Similar to OpenBSD's strlcpy() function */
389 char *pa_strlcpy(char *b, const char *s, size_t l) {
390 assert(b && s && l > 0);
391
392 strncpy(b, s, l);
393 b[l-1] = 0;
394 return b;
395 }
396
397 #define NICE_LEVEL (-15)
398
399 /* Raise the priority of the current process as much as possible and
400 sensible: set the nice level to -15 and enable realtime scheduling if
401 supported.*/
402 void pa_raise_priority(void) {
403
404 #ifdef HAVE_SYS_RESOURCE_H
405 if (setpriority(PRIO_PROCESS, 0, NICE_LEVEL) < 0)
406 pa_log_warn(__FILE__": setpriority(): %s", pa_cstrerror(errno));
407 else
408 pa_log_info(__FILE__": Successfully gained nice level %i.", NICE_LEVEL);
409 #endif
410
411 #ifdef _POSIX_PRIORITY_SCHEDULING
412 {
413 struct sched_param sp;
414
415 if (sched_getparam(0, &sp) < 0) {
416 pa_log(__FILE__": sched_getparam(): %s", pa_cstrerror(errno));
417 return;
418 }
419
420 sp.sched_priority = 1;
421 if (sched_setscheduler(0, SCHED_FIFO, &sp) < 0) {
422 pa_log_warn(__FILE__": sched_setscheduler(): %s", pa_cstrerror(errno));
423 return;
424 }
425
426 pa_log_info(__FILE__": Successfully enabled SCHED_FIFO scheduling.");
427 }
428 #endif
429
430 #ifdef OS_IS_WIN32
431 if (!SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS))
432 pa_log_warn(__FILE__": SetPriorityClass() failed: 0x%08X", GetLastError());
433 else
434 pa_log_info(__FILE__": Successfully gained high priority class.");
435 #endif
436 }
437
438 /* Reset the priority to normal, inverting the changes made by pa_raise_priority() */
439 void pa_reset_priority(void) {
440 #ifdef OS_IS_WIN32
441 SetPriorityClass(GetCurrentProcess(), NORMAL_PRIORITY_CLASS);
442 #endif
443
444 #ifdef _POSIX_PRIORITY_SCHEDULING
445 {
446 struct sched_param sp;
447 sched_getparam(0, &sp);
448 sp.sched_priority = 0;
449 sched_setscheduler(0, SCHED_OTHER, &sp);
450 }
451 #endif
452
453 #ifdef HAVE_SYS_RESOURCE_H
454 setpriority(PRIO_PROCESS, 0, 0);
455 #endif
456 }
457
458 /* Set the FD_CLOEXEC flag for a fd */
459 int pa_fd_set_cloexec(int fd, int b) {
460
461 #ifdef FD_CLOEXEC
462 int v;
463 assert(fd >= 0);
464
465 if ((v = fcntl(fd, F_GETFD, 0)) < 0)
466 return -1;
467
468 v = (v & ~FD_CLOEXEC) | (b ? FD_CLOEXEC : 0);
469
470 if (fcntl(fd, F_SETFD, v) < 0)
471 return -1;
472 #endif
473
474 return 0;
475 }
476
477 /* Try to parse a boolean string value.*/
478 int pa_parse_boolean(const char *v) {
479
480 if (!strcmp(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
481 return 1;
482 else if (!strcmp(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
483 return 0;
484
485 return -1;
486 }
487
488 /* Split the specified string wherever one of the strings in delimiter
489 * occurs. Each time it is called returns a newly allocated string
490 * with pa_xmalloc(). The variable state points to, should be
491 * initiallized to NULL before the first call. */
492 char *pa_split(const char *c, const char *delimiter, const char**state) {
493 const char *current = *state ? *state : c;
494 size_t l;
495
496 if (!*current)
497 return NULL;
498
499 l = strcspn(current, delimiter);
500 *state = current+l;
501
502 if (**state)
503 (*state)++;
504
505 return pa_xstrndup(current, l);
506 }
507
508 /* What is interpreted as whitespace? */
509 #define WHITESPACE " \t\n"
510
511 /* Split a string into words. Otherwise similar to pa_split(). */
512 char *pa_split_spaces(const char *c, const char **state) {
513 const char *current = *state ? *state : c;
514 size_t l;
515
516 if (!*current || *c == 0)
517 return NULL;
518
519 current += strspn(current, WHITESPACE);
520 l = strcspn(current, WHITESPACE);
521
522 *state = current+l;
523
524 return pa_xstrndup(current, l);
525 }
526
527 /* Return the name of an UNIX signal. Similar to GNU's strsignal() */
528 const char *pa_strsignal(int sig) {
529 switch(sig) {
530 case SIGINT: return "SIGINT";
531 case SIGTERM: return "SIGTERM";
532 #ifdef SIGUSR1
533 case SIGUSR1: return "SIGUSR1";
534 #endif
535 #ifdef SIGUSR2
536 case SIGUSR2: return "SIGUSR2";
537 #endif
538 #ifdef SIGXCPU
539 case SIGXCPU: return "SIGXCPU";
540 #endif
541 #ifdef SIGPIPE
542 case SIGPIPE: return "SIGPIPE";
543 #endif
544 #ifdef SIGCHLD
545 case SIGCHLD: return "SIGCHLD";
546 #endif
547 #ifdef SIGHUP
548 case SIGHUP: return "SIGHUP";
549 #endif
550 default: return "UNKNOWN SIGNAL";
551 }
552 }
553
554 #ifdef HAVE_GRP_H
555
556 /* Check whether the specified GID and the group name match */
557 static int is_group(gid_t gid, const char *name) {
558 struct group group, *result = NULL;
559 long n;
560 void *data;
561 int r = -1;
562
563 #ifdef HAVE_GETGRGID_R
564 #ifdef _SC_GETGR_R_SIZE_MAX
565 n = sysconf(_SC_GETGR_R_SIZE_MAX);
566 #else
567 n = -1;
568 #endif
569 if (n < 0) n = 512;
570 data = pa_xmalloc(n);
571
572 if (getgrgid_r(gid, &group, data, n, &result) < 0 || !result) {
573 pa_log(__FILE__": getgrgid_r(%u): %s", (unsigned)gid, pa_cstrerror(errno));
574 goto finish;
575 }
576
577 r = strcmp(name, result->gr_name) == 0;
578
579 finish:
580 pa_xfree(data);
581 #else
582 /* XXX Not thread-safe, but needed on OSes (e.g. FreeBSD 4.X) that do not
583 * support getgrgid_r. */
584 if ((result = getgrgid(gid)) == NULL) {
585 pa_log(__FILE__": getgrgid(%u): %s", gid, pa_cstrerror(errno));
586 goto finish;
587 }
588
589 r = strcmp(name, result->gr_name) == 0;
590
591 finish:
592 #endif
593
594 return r;
595 }
596
597 /* Check the current user is member of the specified group */
598 int pa_own_uid_in_group(const char *name, gid_t *gid) {
599 GETGROUPS_T *gids, tgid;
600 int n = sysconf(_SC_NGROUPS_MAX);
601 int r = -1, i;
602
603 assert(n > 0);
604
605 gids = pa_xmalloc(sizeof(GETGROUPS_T)*n);
606
607 if ((n = getgroups(n, gids)) < 0) {
608 pa_log(__FILE__": getgroups(): %s", pa_cstrerror(errno));
609 goto finish;
610 }
611
612 for (i = 0; i < n; i++) {
613 if (is_group(gids[i], name) > 0) {
614 *gid = gids[i];
615 r = 1;
616 goto finish;
617 }
618 }
619
620 if (is_group(tgid = getgid(), name) > 0) {
621 *gid = tgid;
622 r = 1;
623 goto finish;
624 }
625
626 r = 0;
627
628 finish:
629
630 pa_xfree(gids);
631 return r;
632 }
633
634 int pa_uid_in_group(uid_t uid, const char *name) {
635 char *g_buf, *p_buf;
636 long g_n, p_n;
637 struct group grbuf, *gr;
638 char **i;
639 int r = -1;
640
641 g_n = sysconf(_SC_GETGR_R_SIZE_MAX);
642 g_buf = pa_xmalloc(g_n);
643
644 p_n = sysconf(_SC_GETPW_R_SIZE_MAX);
645 p_buf = pa_xmalloc(p_n);
646
647 if (getgrnam_r(name, &grbuf, g_buf, (size_t) g_n, &gr) != 0 || !gr)
648 goto finish;
649
650 r = 0;
651 for (i = gr->gr_mem; *i; i++) {
652 struct passwd pwbuf, *pw;
653
654 if (getpwnam_r(*i, &pwbuf, p_buf, (size_t) p_n, &pw) != 0 || !pw)
655 continue;
656
657 if (pw->pw_uid == uid) {
658 r = 1;
659 break;
660 }
661 }
662
663 finish:
664 pa_xfree(g_buf);
665 pa_xfree(p_buf);
666
667 return r;
668 }
669
670 #else /* HAVE_GRP_H */
671
672 int pa_own_uid_in_group(const char *name, gid_t *gid) {
673 return -1;
674
675 }
676
677 int pa_uid_in_group(uid_t uid, const char *name) {
678 return -1;
679 }
680
681 #endif
682
683 /* Lock or unlock a file entirely.
684 (advisory on UNIX, mandatory on Windows) */
685 int pa_lock_fd(int fd, int b) {
686 #ifdef F_SETLKW
687 struct flock flock;
688
689 /* Try a R/W lock first */
690
691 flock.l_type = b ? F_WRLCK : F_UNLCK;
692 flock.l_whence = SEEK_SET;
693 flock.l_start = 0;
694 flock.l_len = 0;
695
696 if (fcntl(fd, F_SETLKW, &flock) >= 0)
697 return 0;
698
699 /* Perhaps the file descriptor qas opened for read only, than try again with a read lock. */
700 if (b && errno == EBADF) {
701 flock.l_type = F_RDLCK;
702 if (fcntl(fd, F_SETLKW, &flock) >= 0)
703 return 0;
704 }
705
706 pa_log(__FILE__": %slock: %s", !b? "un" : "",
707 pa_cstrerror(errno));
708 #endif
709
710 #ifdef OS_IS_WIN32
711 HANDLE h = (HANDLE)_get_osfhandle(fd);
712
713 if (b && LockFile(h, 0, 0, 0xFFFFFFFF, 0xFFFFFFFF))
714 return 0;
715 if (!b && UnlockFile(h, 0, 0, 0xFFFFFFFF, 0xFFFFFFFF))
716 return 0;
717
718 pa_log(__FILE__": %slock failed: 0x%08X", !b ? "un" : "", GetLastError());
719 #endif
720
721 return -1;
722 }
723
724 /* Remove trailing newlines from a string */
725 char* pa_strip_nl(char *s) {
726 assert(s);
727
728 s[strcspn(s, "\r\n")] = 0;
729 return s;
730 }
731
732 /* Create a temporary lock file and lock it. */
733 int pa_lock_lockfile(const char *fn) {
734 int fd = -1;
735 assert(fn);
736
737 for (;;) {
738 struct stat st;
739
740 if ((fd = open(fn, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR)) < 0) {
741 pa_log(__FILE__": failed to create lock file '%s': %s", fn,
742 pa_cstrerror(errno));
743 goto fail;
744 }
745
746 if (pa_lock_fd(fd, 1) < 0) {
747 pa_log(__FILE__": failed to lock file '%s'.", fn);
748 goto fail;
749 }
750
751 if (fstat(fd, &st) < 0) {
752 pa_log(__FILE__": failed to fstat() file '%s'.", fn);
753 goto fail;
754 }
755
756 /* Check wheter the file has been removed meanwhile. When yes, restart this loop, otherwise, we're done */
757 if (st.st_nlink >= 1)
758 break;
759
760 if (pa_lock_fd(fd, 0) < 0) {
761 pa_log(__FILE__": failed to unlock file '%s'.", fn);
762 goto fail;
763 }
764
765 if (close(fd) < 0) {
766 pa_log(__FILE__": failed to close file '%s'.", fn);
767 goto fail;
768 }
769
770 fd = -1;
771 }
772
773 return fd;
774
775 fail:
776
777 if (fd >= 0)
778 close(fd);
779
780 return -1;
781 }
782
783 /* Unlock a temporary lcok file */
784 int pa_unlock_lockfile(const char *fn, int fd) {
785 int r = 0;
786 assert(fn && fd >= 0);
787
788 if (unlink(fn) < 0) {
789 pa_log_warn(__FILE__": WARNING: unable to remove lock file '%s': %s",
790 fn, pa_cstrerror(errno));
791 r = -1;
792 }
793
794 if (pa_lock_fd(fd, 0) < 0) {
795 pa_log_warn(__FILE__": WARNING: failed to unlock file '%s'.", fn);
796 r = -1;
797 }
798
799 if (close(fd) < 0) {
800 pa_log_warn(__FILE__": WARNING: failed to close lock file '%s': %s",
801 fn, pa_cstrerror(errno));
802 r = -1;
803 }
804
805 return r;
806 }
807
808 /* Try to open a configuration file. If "env" is specified, open the
809 * value of the specified environment variable. Otherwise look for a
810 * file "local" in the home directory or a file "global" in global
811 * file system. If "result" is non-NULL, a pointer to a newly
812 * allocated buffer containing the used configuration file is
813 * stored there.*/
814 FILE *pa_open_config_file(const char *global, const char *local, const char *env, char **result, const char *mode) {
815 const char *fn;
816 char h[PATH_MAX];
817
818 #ifdef OS_IS_WIN32
819 char buf[PATH_MAX];
820
821 if (!getenv(PULSE_ROOTENV))
822 pa_set_root(NULL);
823 #endif
824
825 if (env && (fn = getenv(env))) {
826 #ifdef OS_IS_WIN32
827 if (!ExpandEnvironmentStrings(fn, buf, PATH_MAX))
828 return NULL;
829 fn = buf;
830 #endif
831
832 if (result)
833 *result = pa_xstrdup(fn);
834
835 return fopen(fn, mode);
836 }
837
838 if (local && pa_get_home_dir(h, sizeof(h))) {
839 FILE *f;
840 char *lfn;
841
842 fn = lfn = pa_sprintf_malloc("%s/%s", h, local);
843
844 #ifdef OS_IS_WIN32
845 if (!ExpandEnvironmentStrings(lfn, buf, PATH_MAX))
846 return NULL;
847 fn = buf;
848 #endif
849
850 f = fopen(fn, mode);
851
852 if (f || errno != ENOENT) {
853 if (result)
854 *result = pa_xstrdup(fn);
855 pa_xfree(lfn);
856 return f;
857 }
858
859 pa_xfree(lfn);
860 }
861
862 if (!global) {
863 if (result)
864 *result = NULL;
865 errno = ENOENT;
866 return NULL;
867 }
868
869 #ifdef OS_IS_WIN32
870 if (!ExpandEnvironmentStrings(global, buf, PATH_MAX))
871 return NULL;
872 global = buf;
873 #endif
874
875 if (result)
876 *result = pa_xstrdup(global);
877
878 return fopen(global, mode);
879 }
880
881 /* Format the specified data as a hexademical string */
882 char *pa_hexstr(const uint8_t* d, size_t dlength, char *s, size_t slength) {
883 size_t i = 0, j = 0;
884 const char hex[] = "0123456789abcdef";
885 assert(d && s && slength > 0);
886
887 while (i < dlength && j+3 <= slength) {
888 s[j++] = hex[*d >> 4];
889 s[j++] = hex[*d & 0xF];
890
891 d++;
892 i++;
893 }
894
895 s[j < slength ? j : slength] = 0;
896 return s;
897 }
898
899 /* Convert a hexadecimal digit to a number or -1 if invalid */
900 static int hexc(char c) {
901 if (c >= '0' && c <= '9')
902 return c - '0';
903
904 if (c >= 'A' && c <= 'F')
905 return c - 'A' + 10;
906
907 if (c >= 'a' && c <= 'f')
908 return c - 'a' + 10;
909
910 return -1;
911 }
912
913 /* Parse a hexadecimal string as created by pa_hexstr() to a BLOB */
914 size_t pa_parsehex(const char *p, uint8_t *d, size_t dlength) {
915 size_t j = 0;
916 assert(p && d);
917
918 while (j < dlength && *p) {
919 int b;
920
921 if ((b = hexc(*(p++))) < 0)
922 return (size_t) -1;
923
924 d[j] = (uint8_t) (b << 4);
925
926 if (!*p)
927 return (size_t) -1;
928
929 if ((b = hexc(*(p++))) < 0)
930 return (size_t) -1;
931
932 d[j] |= (uint8_t) b;
933 j++;
934 }
935
936 return j;
937 }
938
939 /* Returns nonzero when *s starts with *pfx */
940 int pa_startswith(const char *s, const char *pfx) {
941 size_t l;
942
943 assert(s);
944 assert(pfx);
945
946 l = strlen(pfx);
947
948 return strlen(s) >= l && strncmp(s, pfx, l) == 0;
949 }
950
951 /* Returns nonzero when *s ends with *sfx */
952 int pa_endswith(const char *s, const char *sfx) {
953 size_t l1, l2;
954
955 assert(s);
956 assert(sfx);
957
958 l1 = strlen(s);
959 l2 = strlen(sfx);
960
961 return l1 >= l2 && strcmp(s+l1-l2, sfx) == 0;
962 }
963
964 /* if fn is null return the PulseAudio run time path in s (/tmp/pulse)
965 * if fn is non-null and starts with / return fn in s
966 * otherwise append fn to the run time path and return it in s */
967 char *pa_runtime_path(const char *fn, char *s, size_t l) {
968 char u[256];
969
970 #ifndef OS_IS_WIN32
971 if (fn && *fn == '/')
972 #else
973 if (fn && strlen(fn) >= 3 && isalpha(fn[0]) && fn[1] == ':' && fn[2] == '\\')
974 #endif
975 return pa_strlcpy(s, fn, l);
976
977 if (fn)
978 snprintf(s, l, "%s%s%c%s", PA_RUNTIME_PATH_PREFIX, pa_get_user_name(u, sizeof(u)), PATH_SEP, fn);
979 else
980 snprintf(s, l, "%s%s", PA_RUNTIME_PATH_PREFIX, pa_get_user_name(u, sizeof(u)));
981
982 #ifdef OS_IS_WIN32
983 {
984 char buf[l];
985 strcpy(buf, s);
986 ExpandEnvironmentStrings(buf, s, l);
987 }
988 #endif
989
990 return s;
991 }
992
993 /* Convert the string s to a signed integer in *ret_i */
994 int pa_atoi(const char *s, int32_t *ret_i) {
995 char *x = NULL;
996 long l;
997 assert(s && ret_i);
998
999 l = strtol(s, &x, 0);
1000
1001 if (!x || *x)
1002 return -1;
1003
1004 *ret_i = (int32_t) l;
1005
1006 return 0;
1007 }
1008
1009 /* Convert the string s to an unsigned integer in *ret_u */
1010 int pa_atou(const char *s, uint32_t *ret_u) {
1011 char *x = NULL;
1012 unsigned long l;
1013 assert(s && ret_u);
1014
1015 l = strtoul(s, &x, 0);
1016
1017 if (!x || *x)
1018 return -1;
1019
1020 *ret_u = (uint32_t) l;
1021
1022 return 0;
1023 }