4 This file is part of polypaudio.
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.
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.
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
35 #include <sys/types.h>
42 #include <sys/resource.h>
48 #include <samplerate.h>
54 /** Make a file descriptor nonblock. Doesn't do any error checking */
55 void pa_make_nonblock_fd(int fd) {
59 if ((v = fcntl(fd, F_GETFL)) >= 0)
60 if (!(v & O_NONBLOCK))
61 fcntl(fd, F_SETFL, v|O_NONBLOCK);
64 /** Creates a directory securely */
65 int pa_make_secure_dir(const char* dir) {
69 if (mkdir(dir, 0700) < 0)
73 if (lstat(dir, &st) < 0)
76 if (!S_ISDIR(st.st_mode) || (st.st_uid != getuid()) || ((st.st_mode & 0777) != 0700))
86 /** Calls read() in a loop. Makes sure that as much as 'size' bytes,
87 * unless EOF is reached or an error occured */
88 ssize_t pa_loop_read(int fd, void*data, size_t size) {
90 assert(fd >= 0 && data && size);
95 if ((r = read(fd, data, size)) < 0)
102 data = (uint8_t*) data + r;
109 /** Similar to pa_loop_read(), but wraps write() */
110 ssize_t pa_loop_write(int fd, const void*data, size_t size) {
112 assert(fd >= 0 && data && size);
117 if ((r = write(fd, data, size)) < 0)
124 data = (uint8_t*) data + r;
131 /* Print a warning messages in case that the given signal is not
132 * blocked or trapped */
133 void pa_check_signal_is_blocked(int sig) {
137 /* If POSIX threads are supported use thread-aware
138 * pthread_sigmask() function, to check if the signal is
139 * blocked. Otherwise fall back to sigprocmask() */
142 if (pthread_sigmask(SIG_SETMASK, NULL, &set) < 0) {
144 if (sigprocmask(SIG_SETMASK, NULL, &set) < 0) {
145 pa_log(__FILE__": sigprocmask() failed: %s\n", strerror(errno));
152 if (sigismember(&set, sig))
155 /* Check whether the signal is trapped */
157 if (sigaction(sig, NULL, &sa) < 0) {
158 pa_log(__FILE__": sigaction() failed: %s\n", strerror(errno));
162 if (sa.sa_handler != SIG_DFL)
165 pa_log(__FILE__": WARNING: %s is not trapped. This might cause malfunction!\n", pa_strsignal(sig));
168 /* The following function is based on an example from the GNU libc
169 * documentation. This function is similar to GNU's asprintf(). */
170 char *pa_sprintf_malloc(const char *format, ...) {
180 c = pa_xrealloc(c, size);
182 va_start(ap, format);
183 r = vsnprintf(c, size, format, ap);
186 if (r > -1 && r < size)
189 if (r > -1) /* glibc 2.1 */
196 /* Same as the previous function, but use a va_list instead of an
198 char *pa_vsprintf_malloc(const char *format, va_list ap) {
208 c = pa_xrealloc(c, size);
209 r = vsnprintf(c, size, format, ap);
211 if (r > -1 && r < size)
214 if (r > -1) /* glibc 2.1 */
221 /* Return the current username in the specified string buffer. */
222 char *pa_get_user_name(char *s, size_t l) {
223 struct passwd pw, *r;
228 if (!(p = getenv("USER")))
229 if (!(p = getenv("LOGNAME")))
230 if (!(p = getenv("USERNAME"))) {
232 #ifdef HAVE_GETPWUID_R
233 if (getpwuid_r(getuid(), &pw, buf, sizeof(buf), &r) != 0 || !r) {
235 /* XXX Not thread-safe, but needed on OSes (e.g. FreeBSD 4.X)
236 * that do not support getpwuid_r. */
237 if ((r = getpwuid(getuid())) == NULL) {
239 snprintf(s, l, "%lu", (unsigned long) getuid());
246 return pa_strlcpy(s, p, l);
249 /* Return the current hostname in the specified buffer. */
250 char *pa_get_host_name(char *s, size_t l) {
257 /* Return the home directory of the current user */
258 char *pa_get_home_dir(char *s, size_t l) {
261 struct passwd pw, *r;
264 if ((e = getenv("HOME")))
265 return pa_strlcpy(s, e, l);
267 if (getpwuid_r(getuid(), &pw, buf, sizeof(buf), &r) != 0 || !r)
270 return pa_strlcpy(s, r->pw_dir, l);
273 /* Similar to OpenBSD's strlcpy() function */
274 char *pa_strlcpy(char *b, const char *s, size_t l) {
275 assert(b && s && l > 0);
282 /* Calculate the difference between the two specfified timeval
284 pa_usec_t pa_timeval_diff(const struct timeval *a, const struct timeval *b) {
288 /* Check which whan is the earlier time and swap the two arguments if reuqired. */
289 if (pa_timeval_cmp(a, b) < 0) {
290 const struct timeval *c;
296 /* Calculate the second difference*/
297 r = ((pa_usec_t) a->tv_sec - b->tv_sec)* 1000000;
299 /* Calculate the microsecond difference */
300 if (a->tv_usec > b->tv_usec)
301 r += ((pa_usec_t) a->tv_usec - b->tv_usec);
302 else if (a->tv_usec < b->tv_usec)
303 r -= ((pa_usec_t) b->tv_usec - a->tv_usec);
308 /* Compare the two timeval structs and return 0 when equal, negative when a < b, positive otherwse */
309 int pa_timeval_cmp(const struct timeval *a, const struct timeval *b) {
312 if (a->tv_sec < b->tv_sec)
315 if (a->tv_sec > b->tv_sec)
318 if (a->tv_usec < b->tv_usec)
321 if (a->tv_usec > b->tv_usec)
327 /* Return the time difference between now and the specified timestamp */
328 pa_usec_t pa_timeval_age(const struct timeval *tv) {
331 gettimeofday(&now, NULL);
332 return pa_timeval_diff(&now, tv);
335 /* Add the specified time inmicroseconds to the specified timeval structure */
336 void pa_timeval_add(struct timeval *tv, pa_usec_t v) {
341 tv->tv_sec += (unsigned long) secs;
347 while (tv->tv_usec >= 1000000) {
349 tv->tv_usec -= 1000000;
353 #define NICE_LEVEL (-15)
355 /* Raise the priority of the current process as much as possible and
356 sensible: set the nice level to -15 and enable realtime scheduling if
358 void pa_raise_priority(void) {
360 if (setpriority(PRIO_PROCESS, 0, NICE_LEVEL) < 0)
361 pa_log(__FILE__": setpriority() failed: %s\n", strerror(errno));
362 else pa_log(__FILE__": Successfully gained nice level %i.\n", NICE_LEVEL);
364 #ifdef _POSIX_PRIORITY_SCHEDULING
366 struct sched_param sp;
368 if (sched_getparam(0, &sp) < 0) {
369 pa_log(__FILE__": sched_getparam() failed: %s\n", strerror(errno));
373 sp.sched_priority = 1;
374 if (sched_setscheduler(0, SCHED_FIFO, &sp) < 0) {
375 pa_log(__FILE__": sched_setscheduler() failed: %s\n", strerror(errno));
379 pa_log(__FILE__": Successfully enabled SCHED_FIFO scheduling.\n");
384 /* Reset the priority to normal, inverting the changes made by pa_raise_priority() */
385 void pa_reset_priority(void) {
386 #ifdef _POSIX_PRIORITY_SCHEDULING
388 struct sched_param sp;
389 sched_getparam(0, &sp);
390 sp.sched_priority = 0;
391 sched_setscheduler(0, SCHED_OTHER, &sp);
395 setpriority(PRIO_PROCESS, 0, 0);
398 /* Set the FD_CLOEXEC flag for a fd */
399 int pa_fd_set_cloexec(int fd, int b) {
403 if ((v = fcntl(fd, F_GETFD, 0)) < 0)
406 v = (v & ~FD_CLOEXEC) | (b ? FD_CLOEXEC : 0);
408 if (fcntl(fd, F_SETFD, v) < 0)
414 /* Return the binary file name of the current process. Works on Linux
415 * only. This shoul be used for eyecandy only, don't rely on return
417 char *pa_get_binary_name(char *s, size_t l) {
422 /* This works on Linux only */
424 snprintf(path, sizeof(path), "/proc/%u/exe", (unsigned) getpid());
425 if ((i = readlink(path, s, l-1)) < 0)
432 /* Return a pointer to the filename inside a path (which is the last
434 char *pa_path_get_filename(const char *p) {
437 if ((fn = strrchr(p, '/')))
443 /* Try to parse a boolean string value.*/
444 int pa_parse_boolean(const char *v) {
446 if (!strcmp(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
448 else if (!strcmp(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
454 /* Split the specified string wherever one of the strings in delimiter
455 * occurs. Each time it is called returns a newly allocated string
456 * with pa_xmalloc(). The variable state points to, should be
457 * initiallized to NULL before the first call. */
458 char *pa_split(const char *c, const char *delimiter, const char**state) {
459 const char *current = *state ? *state : c;
465 l = strcspn(current, delimiter);
471 return pa_xstrndup(current, l);
474 /* What is interpreted as whitespace? */
475 #define WHITESPACE " \t\n"
477 /* Split a string into words. Otherwise similar to pa_split(). */
478 char *pa_split_spaces(const char *c, const char **state) {
479 const char *current = *state ? *state : c;
485 current += strspn(current, WHITESPACE);
486 l = strcspn(current, WHITESPACE);
490 return pa_xstrndup(current, l);
493 /* Return the name of an UNIX signal. Similar to GNU's strsignal() */
494 const char *pa_strsignal(int sig) {
496 case SIGINT: return "SIGINT";
497 case SIGTERM: return "SIGTERM";
498 case SIGUSR1: return "SIGUSR1";
499 case SIGUSR2: return "SIGUSR2";
500 case SIGXCPU: return "SIGXCPU";
501 case SIGPIPE: return "SIGPIPE";
502 case SIGCHLD: return "SIGCHLD";
503 case SIGHUP: return "SIGHUP";
504 default: return "UNKNOWN SIGNAL";
508 /* Parse a libsamplrate compatible resampling implementation */
509 int pa_parse_resample_method(const char *string) {
512 if (!strcmp(string, "sinc-best-quality"))
513 return SRC_SINC_BEST_QUALITY;
514 else if (!strcmp(string, "sinc-medium-quality"))
515 return SRC_SINC_MEDIUM_QUALITY;
516 else if (!strcmp(string, "sinc-fastest"))
517 return SRC_SINC_FASTEST;
518 else if (!strcmp(string, "zero-order-hold"))
519 return SRC_ZERO_ORDER_HOLD;
520 else if (!strcmp(string, "linear"))
526 /* Check whether the specified GID and the group name match */
527 static int is_group(gid_t gid, const char *name) {
528 struct group group, *result = NULL;
533 #ifdef HAVE_GETGRGID_R
534 #ifdef _SC_GETGR_R_SIZE_MAX
535 n = sysconf(_SC_GETGR_R_SIZE_MAX);
540 data = pa_xmalloc(n);
542 if (getgrgid_r(gid, &group, data, n, &result) < 0 || !result) {
543 pa_log(__FILE__ ": getgrgid_r(%u) failed: %s\n", gid, strerror(errno));
548 r = strcmp(name, result->gr_name) == 0;
553 /* XXX Not thread-safe, but needed on OSes (e.g. FreeBSD 4.X) that do not
554 * support getgrgid_r. */
555 if ((result = getgrgid(gid)) == NULL) {
556 pa_log(__FILE__ ": getgrgid(%u) failed: %s\n", gid, strerror(errno));
560 r = strcmp(name, result->gr_name) == 0;
568 /* Check the current user is member of the specified group */
569 int pa_uid_in_group(const char *name, gid_t *gid) {
571 long n = sysconf(_SC_NGROUPS_MAX);
576 gids = pa_xmalloc(sizeof(gid_t)*n);
578 if ((n = getgroups(n, gids)) < 0) {
579 pa_log(__FILE__": getgroups() failed: %s\n", strerror(errno));
583 for (i = 0; i < n; i++) {
584 if (is_group(gids[i], name) > 0) {
591 if (is_group(tgid = getgid(), name) > 0) {
605 /* Lock or unlock a file entirely. (advisory) */
606 int pa_lock_fd(int fd, int b) {
610 flock.l_type = b ? F_WRLCK : F_UNLCK;
611 flock.l_whence = SEEK_SET;
615 if (fcntl(fd, F_SETLKW, &flock) < 0) {
616 pa_log(__FILE__": %slock failed: %s\n", !b ? "un" : "", strerror(errno));
623 /* Remove trailing newlines from a string */
624 char* pa_strip_nl(char *s) {
627 s[strcspn(s, "\r\n")] = 0;
631 /* Create a temporary lock file and lock it. */
632 int pa_lock_lockfile(const char *fn) {
636 if ((fd = open(fn, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR)) < 0) {
637 pa_log(__FILE__": failed to create lock file '%s'\n", fn);
641 if (pa_lock_fd(fd, 1) < 0)
654 /* Unlock a temporary lcok file */
655 int pa_unlock_lockfile(int fd) {
659 if (pa_lock_fd(fd, 0) < 0) {
660 pa_log(__FILE__": WARNING: failed to unlock file.\n");
665 pa_log(__FILE__": WARNING: failed to close lock file.\n");
672 /* Try to open a configuration file. If "env" is specified, open the
673 * value of the specified environment variable. Otherwise look for a
674 * file "local" in the home directory or a file "global" in global
675 * file system. If "result" is non-NULL, a pointer to a newly
676 * allocated buffer containing the used configuration file is
678 FILE *pa_open_config_file(const char *global, const char *local, const char *env, char **result) {
682 if (env && (e = getenv(env))) {
684 *result = pa_xstrdup(e);
685 return fopen(e, "r");
688 if (local && pa_get_home_dir(h, sizeof(h))) {
692 l = pa_sprintf_malloc("%s/%s", h, local);
695 if (f || errno != ENOENT) {
714 *result = pa_xstrdup(global);
716 return fopen(global, "r");
719 /* Format the specified data as a hexademical string */
720 char *pa_hexstr(const uint8_t* d, size_t dlength, char *s, size_t slength) {
722 const char hex[] = "0123456789abcdef";
723 assert(d && s && slength > 0);
725 while (i < dlength && j+3 <= slength) {
726 s[j++] = hex[*d >> 4];
727 s[j++] = hex[*d & 0xF];
733 s[j < slength ? j : slength] = 0;
737 /* Convert a hexadecimal digit to a number or -1 if invalid */
738 static int hexc(char c) {
739 if (c >= '0' && c <= '9')
742 if (c >= 'A' && c <= 'F')
745 if (c >= 'a' && c <= 'f')
751 /* Parse a hexadecimal string as created by pa_hexstr() to a BLOB */
752 size_t pa_parsehex(const char *p, uint8_t *d, size_t dlength) {
756 while (j < dlength && *p) {
759 if ((b = hexc(*(p++))) < 0)
762 d[j] = (uint8_t) (b << 4);
767 if ((b = hexc(*(p++))) < 0)
778 char *pa_get_fqdn(char *s, size_t l) {
780 struct addrinfo *a, hints;
782 if (!pa_get_host_name(hn, sizeof(hn)))
785 memset(&hints, 0, sizeof(hints));
786 hints.ai_family = AF_UNSPEC;
787 hints.ai_flags = AI_CANONNAME;
789 if (getaddrinfo(hn, NULL, &hints, &a) < 0 || !a || !a->ai_canonname || !*a->ai_canonname)
790 return pa_strlcpy(s, hn, l);
792 pa_strlcpy(s, a->ai_canonname, l);