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