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