]> code.delx.au - pulseaudio/blob - polyp/util.c
implemented pax11publish.c
[pulseaudio] / polyp / 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 General Public License as published
8 by the Free Software Foundation; either version 2 of the License,
9 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 General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 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 <sys/types.h>
36 #include <sys/stat.h>
37 #include <pwd.h>
38 #include <signal.h>
39 #include <pthread.h>
40 #include <sys/time.h>
41 #include <sched.h>
42 #include <sys/resource.h>
43 #include <limits.h>
44 #include <unistd.h>
45 #include <grp.h>
46
47 #include <samplerate.h>
48
49 #include "util.h"
50 #include "xmalloc.h"
51 #include "log.h"
52
53 /** Make a file descriptor nonblock. Doesn't do any error checking */
54 void pa_make_nonblock_fd(int fd) {
55 int v;
56 assert(fd >= 0);
57
58 if ((v = fcntl(fd, F_GETFL)) >= 0)
59 if (!(v & O_NONBLOCK))
60 fcntl(fd, F_SETFL, v|O_NONBLOCK);
61 }
62
63 /** Creates a directory securely */
64 int pa_make_secure_dir(const char* dir) {
65 struct stat st;
66 assert(dir);
67
68 if (mkdir(dir, 0700) < 0)
69 if (errno != EEXIST)
70 return -1;
71
72 if (lstat(dir, &st) < 0)
73 goto fail;
74
75 if (!S_ISDIR(st.st_mode) || (st.st_uid != getuid()) || ((st.st_mode & 0777) != 0700))
76 goto fail;
77
78 return 0;
79
80 fail:
81 rmdir(dir);
82 return -1;
83 }
84
85 /** Calls read() in a loop. Makes sure that as much as 'size' bytes,
86 * unless EOF is reached or an error occured */
87 ssize_t pa_loop_read(int fd, void*data, size_t size) {
88 ssize_t ret = 0;
89 assert(fd >= 0 && data && size);
90
91 while (size > 0) {
92 ssize_t r;
93
94 if ((r = read(fd, data, size)) < 0)
95 return r;
96
97 if (r == 0)
98 break;
99
100 ret += r;
101 data = (uint8_t*) data + r;
102 size -= r;
103 }
104
105 return ret;
106 }
107
108 /** Similar to pa_loop_read(), but wraps write() */
109 ssize_t pa_loop_write(int fd, const void*data, size_t size) {
110 ssize_t ret = 0;
111 assert(fd >= 0 && data && size);
112
113 while (size > 0) {
114 ssize_t r;
115
116 if ((r = write(fd, data, size)) < 0)
117 return r;
118
119 if (r == 0)
120 break;
121
122 ret += r;
123 data = (uint8_t*) data + r;
124 size -= r;
125 }
126
127 return ret;
128 }
129
130 /* Print a warning messages in case that the given signal is not
131 * blocked or trapped */
132 void pa_check_signal_is_blocked(int sig) {
133 struct sigaction sa;
134 sigset_t set;
135
136 /* If POSIX threads are supported use thread-aware
137 * pthread_sigmask() function, to check if the signal is
138 * blocked. Otherwise fall back to sigprocmask() */
139
140 #ifdef HAVE_PTHREAD
141 if (pthread_sigmask(SIG_SETMASK, NULL, &set) < 0) {
142 #endif
143 if (sigprocmask(SIG_SETMASK, NULL, &set) < 0) {
144 pa_log(__FILE__": sigprocmask() failed: %s\n", strerror(errno));
145 return;
146 }
147 #ifdef HAVE_PTHREAD
148 }
149 #endif
150
151 if (sigismember(&set, sig))
152 return;
153
154 /* Check whether the signal is trapped */
155
156 if (sigaction(sig, NULL, &sa) < 0) {
157 pa_log(__FILE__": sigaction() failed: %s\n", strerror(errno));
158 return;
159 }
160
161 if (sa.sa_handler != SIG_DFL)
162 return;
163
164 pa_log(__FILE__": WARNING: %s is not trapped. This might cause malfunction!\n", pa_strsignal(sig));
165 }
166
167 /* The following function is based on an example from the GNU libc
168 * documentation. This function is similar to GNU's asprintf(). */
169 char *pa_sprintf_malloc(const char *format, ...) {
170 int size = 100;
171 char *c = NULL;
172
173 assert(format);
174
175 for(;;) {
176 int r;
177 va_list ap;
178
179 c = pa_xrealloc(c, size);
180
181 va_start(ap, format);
182 r = vsnprintf(c, size, format, ap);
183 va_end(ap);
184
185 if (r > -1 && r < size)
186 return c;
187
188 if (r > -1) /* glibc 2.1 */
189 size = r+1;
190 else /* glibc 2.0 */
191 size *= 2;
192 }
193 }
194
195 /* Same as the previous function, but use a va_list instead of an
196 * ellipsis */
197 char *pa_vsprintf_malloc(const char *format, va_list ap) {
198 int size = 100;
199 char *c = NULL;
200
201 assert(format);
202
203 for(;;) {
204 int r;
205 va_list ap;
206
207 c = pa_xrealloc(c, size);
208 r = vsnprintf(c, size, format, ap);
209
210 if (r > -1 && r < size)
211 return c;
212
213 if (r > -1) /* glibc 2.1 */
214 size = r+1;
215 else /* glibc 2.0 */
216 size *= 2;
217 }
218 }
219
220 /* Return the current username in the specified string buffer. */
221 char *pa_get_user_name(char *s, size_t l) {
222 struct passwd pw, *r;
223 char buf[1024];
224 char *p;
225 assert(s && l > 0);
226
227 if (!(p = getenv("USER")))
228 if (!(p = getenv("LOGNAME")))
229 if (!(p = getenv("USERNAME"))) {
230
231 #ifdef HAVE_GETPWUID_R
232 if (getpwuid_r(getuid(), &pw, buf, sizeof(buf), &r) != 0 || !r) {
233 #else
234 /* XXX Not thread-safe, but needed on OSes (e.g. FreeBSD 4.X)
235 * that do not support getpwuid_r. */
236 if ((r = getpwuid(getuid())) == NULL) {
237 #endif
238 snprintf(s, l, "%lu", (unsigned long) getuid());
239 return s;
240 }
241
242 p = r->pw_name;
243 }
244
245 return pa_strlcpy(s, p, l);
246 }
247
248 /* Return the current hostname in the specified buffer. */
249 char *pa_get_host_name(char *s, size_t l) {
250 assert(s && l > 0);
251 gethostname(s, l);
252 s[l-1] = 0;
253 return s;
254 }
255
256 /* Return the home directory of the current user */
257 char *pa_get_home_dir(char *s, size_t l) {
258 char *e;
259 char buf[1024];
260 struct passwd pw, *r;
261 assert(s && l);
262
263 if ((e = getenv("HOME")))
264 return pa_strlcpy(s, e, l);
265
266 if (getpwuid_r(getuid(), &pw, buf, sizeof(buf), &r) != 0 || !r)
267 return NULL;
268
269 return pa_strlcpy(s, r->pw_dir, l);
270 }
271
272 /* Similar to OpenBSD's strlcpy() function */
273 char *pa_strlcpy(char *b, const char *s, size_t l) {
274 assert(b && s && l > 0);
275
276 strncpy(b, s, l);
277 b[l-1] = 0;
278 return b;
279 }
280
281 /* Calculate the difference between the two specfified timeval
282 * timestamsps. */
283 pa_usec_t pa_timeval_diff(const struct timeval *a, const struct timeval *b) {
284 pa_usec_t r;
285 assert(a && b);
286
287 /* Check which whan is the earlier time and swap the two arguments if reuqired. */
288 if (pa_timeval_cmp(a, b) < 0) {
289 const struct timeval *c;
290 c = a;
291 a = b;
292 b = c;
293 }
294
295 /* Calculate the second difference*/
296 r = ((pa_usec_t) a->tv_sec - b->tv_sec)* 1000000;
297
298 /* Calculate the microsecond difference */
299 if (a->tv_usec > b->tv_usec)
300 r += ((pa_usec_t) a->tv_usec - b->tv_usec);
301 else if (a->tv_usec < b->tv_usec)
302 r -= ((pa_usec_t) b->tv_usec - a->tv_usec);
303
304 return r;
305 }
306
307 /* Compare the two timeval structs and return 0 when equal, negative when a < b, positive otherwse */
308 int pa_timeval_cmp(const struct timeval *a, const struct timeval *b) {
309 assert(a && b);
310
311 if (a->tv_sec < b->tv_sec)
312 return -1;
313
314 if (a->tv_sec > b->tv_sec)
315 return 1;
316
317 if (a->tv_usec < b->tv_usec)
318 return -1;
319
320 if (a->tv_usec > b->tv_usec)
321 return 1;
322
323 return 0;
324 }
325
326 /* Return the time difference between now and the specified timestamp */
327 pa_usec_t pa_timeval_age(const struct timeval *tv) {
328 struct timeval now;
329 assert(tv);
330 gettimeofday(&now, NULL);
331 return pa_timeval_diff(&now, tv);
332 }
333
334 /* Add the specified time inmicroseconds to the specified timeval structure */
335 void pa_timeval_add(struct timeval *tv, pa_usec_t v) {
336 unsigned long secs;
337 assert(tv);
338
339 secs = (v/1000000);
340 tv->tv_sec += (unsigned long) secs;
341 v -= secs*1000000;
342
343 tv->tv_usec += v;
344
345 /* Normalize */
346 while (tv->tv_usec >= 1000000) {
347 tv->tv_sec++;
348 tv->tv_usec -= 1000000;
349 }
350 }
351
352 #define NICE_LEVEL (-15)
353
354 /* Raise the priority of the current process as much as possible and
355 sensible: set the nice level to -15 and enable realtime scheduling if
356 supported.*/
357 void pa_raise_priority(void) {
358
359 if (setpriority(PRIO_PROCESS, 0, NICE_LEVEL) < 0)
360 pa_log(__FILE__": setpriority() failed: %s\n", strerror(errno));
361 else pa_log(__FILE__": Successfully gained nice level %i.\n", NICE_LEVEL);
362
363 #ifdef _POSIX_PRIORITY_SCHEDULING
364 {
365 struct sched_param sp;
366
367 if (sched_getparam(0, &sp) < 0) {
368 pa_log(__FILE__": sched_getparam() failed: %s\n", strerror(errno));
369 return;
370 }
371
372 sp.sched_priority = 1;
373 if (sched_setscheduler(0, SCHED_FIFO, &sp) < 0) {
374 pa_log(__FILE__": sched_setscheduler() failed: %s\n", strerror(errno));
375 return;
376 }
377
378 pa_log(__FILE__": Successfully enabled SCHED_FIFO scheduling.\n");
379 }
380 #endif
381 }
382
383 /* Reset the priority to normal, inverting the changes made by pa_raise_priority() */
384 void pa_reset_priority(void) {
385 #ifdef _POSIX_PRIORITY_SCHEDULING
386 {
387 struct sched_param sp;
388 sched_getparam(0, &sp);
389 sp.sched_priority = 0;
390 sched_setscheduler(0, SCHED_OTHER, &sp);
391 }
392 #endif
393
394 setpriority(PRIO_PROCESS, 0, 0);
395 }
396
397 /* Set the FD_CLOEXEC flag for a fd */
398 int pa_fd_set_cloexec(int fd, int b) {
399 int v;
400 assert(fd >= 0);
401
402 if ((v = fcntl(fd, F_GETFD, 0)) < 0)
403 return -1;
404
405 v = (v & ~FD_CLOEXEC) | (b ? FD_CLOEXEC : 0);
406
407 if (fcntl(fd, F_SETFD, v) < 0)
408 return -1;
409
410 return 0;
411 }
412
413 /* Return the binary file name of the current process. Works on Linux
414 * only. This shoul be used for eyecandy only, don't rely on return
415 * non-NULL! */
416 char *pa_get_binary_name(char *s, size_t l) {
417 char path[PATH_MAX];
418 int i;
419 assert(s && l);
420
421 /* This works on Linux only */
422
423 snprintf(path, sizeof(path), "/proc/%u/exe", (unsigned) getpid());
424 if ((i = readlink(path, s, l-1)) < 0)
425 return NULL;
426
427 s[i] = 0;
428 return s;
429 }
430
431 /* Return a pointer to the filename inside a path (which is the last
432 * component). */
433 char *pa_path_get_filename(const char *p) {
434 char *fn;
435
436 if ((fn = strrchr(p, '/')))
437 return fn+1;
438
439 return (char*) p;
440 }
441
442 /* Try to parse a boolean string value.*/
443 int pa_parse_boolean(const char *v) {
444
445 if (!strcmp(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
446 return 1;
447 else if (!strcmp(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
448 return 0;
449
450 return -1;
451 }
452
453 /* Split the specified string wherever one of the strings in delimiter
454 * occurs. Each time it is called returns a newly allocated string
455 * with pa_xmalloc(). The variable state points to, should be
456 * initiallized to NULL before the first call. */
457 char *pa_split(const char *c, const char *delimiter, const char**state) {
458 const char *current = *state ? *state : c;
459 size_t l;
460
461 if (!*current)
462 return NULL;
463
464 l = strcspn(current, delimiter);
465 *state = current+l;
466
467 if (**state)
468 (*state)++;
469
470 return pa_xstrndup(current, l);
471 }
472
473 /* What is interpreted as whitespace? */
474 #define WHITESPACE " \t\n"
475
476 /* Split a string into words. Otherwise similar to pa_split(). */
477 char *pa_split_spaces(const char *c, const char **state) {
478 const char *current = *state ? *state : c;
479 size_t l;
480
481 if (!*current)
482 return NULL;
483
484 current += strspn(current, WHITESPACE);
485 l = strcspn(current, WHITESPACE);
486
487 *state = current+l;
488
489 return pa_xstrndup(current, l);
490 }
491
492 /* Return the name of an UNIX signal. Similar to GNU's strsignal() */
493 const char *pa_strsignal(int sig) {
494 switch(sig) {
495 case SIGINT: return "SIGINT";
496 case SIGTERM: return "SIGTERM";
497 case SIGUSR1: return "SIGUSR1";
498 case SIGUSR2: return "SIGUSR2";
499 case SIGXCPU: return "SIGXCPU";
500 case SIGPIPE: return "SIGPIPE";
501 case SIGCHLD: return "SIGCHLD";
502 case SIGHUP: return "SIGHUP";
503 default: return "UNKNOWN SIGNAL";
504 }
505 }
506
507 /* Parse a libsamplrate compatible resampling implementation */
508 int pa_parse_resample_method(const char *string) {
509 assert(string);
510
511 if (!strcmp(string, "sinc-best-quality"))
512 return SRC_SINC_BEST_QUALITY;
513 else if (!strcmp(string, "sinc-medium-quality"))
514 return SRC_SINC_MEDIUM_QUALITY;
515 else if (!strcmp(string, "sinc-fastest"))
516 return SRC_SINC_FASTEST;
517 else if (!strcmp(string, "zero-order-hold"))
518 return SRC_ZERO_ORDER_HOLD;
519 else if (!strcmp(string, "linear"))
520 return SRC_LINEAR;
521 else
522 return -1;
523 }
524
525 /* Check whether the specified GID and the group name match */
526 static int is_group(gid_t gid, const char *name) {
527 struct group group, *result = NULL;
528 long n;
529 void *data;
530 int r = -1;
531
532 #ifdef HAVE_GETGRGID_R
533 #ifdef _SC_GETGR_R_SIZE_MAX
534 n = sysconf(_SC_GETGR_R_SIZE_MAX);
535 #else
536 n = -1;
537 #endif
538 if (n < 0) n = 512;
539 data = pa_xmalloc(n);
540
541 if (getgrgid_r(gid, &group, data, n, &result) < 0 || !result) {
542 pa_log(__FILE__ ": getgrgid_r(%u) failed: %s\n", gid, strerror(errno));
543 goto finish;
544 }
545
546
547 r = strcmp(name, result->gr_name) == 0;
548
549 finish:
550 pa_xfree(data);
551 #else
552 /* XXX Not thread-safe, but needed on OSes (e.g. FreeBSD 4.X) that do not
553 * support getgrgid_r. */
554 if ((result = getgrgid(gid)) == NULL) {
555 pa_log(__FILE__ ": getgrgid(%u) failed: %s\n", gid, strerror(errno));
556 goto finish;
557 }
558
559 r = strcmp(name, result->gr_name) == 0;
560
561 finish:
562 #endif
563
564 return r;
565 }
566
567 /* Check the current user is member of the specified group */
568 int pa_uid_in_group(const char *name, gid_t *gid) {
569 gid_t *gids, tgid;
570 long n = sysconf(_SC_NGROUPS_MAX);
571 int r = -1, i;
572
573 assert(n > 0);
574
575 gids = pa_xmalloc(sizeof(gid_t)*n);
576
577 if ((n = getgroups(n, gids)) < 0) {
578 pa_log(__FILE__": getgroups() failed: %s\n", strerror(errno));
579 goto finish;
580 }
581
582 for (i = 0; i < n; i++) {
583 if (is_group(gids[i], name) > 0) {
584 *gid = gids[i];
585 r = 1;
586 goto finish;
587 }
588 }
589
590 if (is_group(tgid = getgid(), name) > 0) {
591 *gid = tgid;
592 r = 1;
593 goto finish;
594 }
595
596 r = 0;
597
598 finish:
599
600 pa_xfree(gids);
601 return r;
602 }
603
604 /* Lock or unlock a file entirely. (advisory) */
605 int pa_lock_fd(int fd, int b) {
606
607 struct flock flock;
608
609 flock.l_type = b ? F_WRLCK : F_UNLCK;
610 flock.l_whence = SEEK_SET;
611 flock.l_start = 0;
612 flock.l_len = 0;
613
614 if (fcntl(fd, F_SETLKW, &flock) < 0) {
615 pa_log(__FILE__": %slock failed: %s\n", !b ? "un" : "", strerror(errno));
616 return -1;
617 }
618
619 return 0;
620 }
621
622 /* Remove trailing newlines from a string */
623 char* pa_strip_nl(char *s) {
624 assert(s);
625
626 s[strcspn(s, "\r\n")] = 0;
627 return s;
628 }
629
630 /* Create a temporary lock file and lock it. */
631 int pa_lock_lockfile(const char *fn) {
632 int fd;
633 assert(fn);
634
635 if ((fd = open(fn, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR)) < 0) {
636 pa_log(__FILE__": failed to create lock file '%s'\n", fn);
637 goto fail;
638 }
639
640 if (pa_lock_fd(fd, 1) < 0)
641 goto fail;
642
643 return fd;
644
645 fail:
646
647 if (fd >= 0)
648 close(fd);
649
650 return -1;
651 }
652
653 /* Unlock a temporary lcok file */
654 int pa_unlock_lockfile(int fd) {
655 int r = 0;
656 assert(fd >= 0);
657
658 if (pa_lock_fd(fd, 0) < 0) {
659 pa_log(__FILE__": WARNING: failed to unlock file.\n");
660 r = -1;
661 }
662
663 if (close(fd) < 0) {
664 pa_log(__FILE__": WARNING: failed to close lock file.\n");
665 r = -1;
666 }
667
668 return r;
669 }
670
671 /* Try to open a configuration file. If "env" is specified, open the
672 * value of the specified environment variable. Otherwise look for a
673 * file "local" in the home directory or a file "global" in global
674 * file system. If "result" is non-NULL, a pointer to a newly
675 * allocated buffer containing the used configuration file is
676 * stored there.*/
677 FILE *pa_open_config_file(const char *global, const char *local, const char *env, char **result) {
678 const char *e;
679 char h[PATH_MAX];
680
681 if (env && (e = getenv(env))) {
682 if (result)
683 *result = pa_xstrdup(e);
684 return fopen(e, "r");
685 }
686
687 if (local && pa_get_home_dir(h, sizeof(h))) {
688 FILE *f;
689 char *l;
690
691 l = pa_sprintf_malloc("%s/%s", h, local);
692 f = fopen(l, "r");
693
694 if (f || errno != ENOENT) {
695 if (result)
696 *result = l;
697 else
698 pa_xfree(l);
699 return f;
700 }
701
702 pa_xfree(l);
703 }
704
705 if (!global) {
706 if (result)
707 *result = NULL;
708 errno = ENOENT;
709 return NULL;
710 }
711
712 if (result)
713 *result = pa_xstrdup(global);
714
715 return fopen(global, "r");
716 }
717
718 /* Format the specified data as a hexademical string */
719 char *pa_hexstr(const uint8_t* d, size_t dlength, char *s, size_t slength) {
720 size_t i = 0, j = 0;
721 const char hex[] = "0123456789abcdef";
722 assert(d && s && slength > 0);
723
724 while (i < dlength && j+3 <= slength) {
725 s[j++] = hex[*d >> 4];
726 s[j++] = hex[*d & 0xF];
727
728 d++;
729 i++;
730 }
731
732 s[j < slength ? j : slength] = 0;
733 return s;
734 }
735
736 /* Convert a hexadecimal digit to a number or -1 if invalid */
737 static int hexc(char c) {
738 if (c >= '0' && c <= '9')
739 return c - '0';
740
741 if (c >= 'A' && c <= 'F')
742 return c - 'A' + 10;
743
744 if (c >= 'a' && c <= 'f')
745 return c - 'a' + 10;
746
747 return -1;
748 }
749
750 /* Parse a hexadecimal string as created by pa_hexstr() to a BLOB */
751 size_t pa_parsehex(const char *p, uint8_t *d, size_t dlength) {
752 size_t j = 0;
753 assert(p && d);
754
755 while (j < dlength && *p) {
756 int b;
757
758 if ((b = hexc(*(p++))) < 0)
759 return (size_t) -1;
760
761 d[j] = (uint8_t) (b << 4);
762
763 if (!*p)
764 return (size_t) -1;
765
766 if ((b = hexc(*(p++))) < 0)
767 return (size_t) -1;
768
769 d[j] |= (uint8_t) b;
770
771 j++;
772 }
773
774 return j;
775 }