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