]>
code.delx.au - pulseaudio/blob - src/polypcore/core-util.c
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 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.
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.
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
38 #include <sys/types.h>
46 #ifdef HAVE_SYS_RESOURCE_H
47 #include <sys/resource.h>
70 #include <samplerate.h>
72 #include <polyp/error.h>
73 #include <polyp/xmalloc.h>
74 #include <polyp/util.h>
76 #include <polypcore/winsock.h>
77 #include <polypcore/log.h>
79 #include "core-util.h"
82 #define PA_RUNTIME_PATH_PREFIX "/tmp/polypaudio-"
85 #define PA_RUNTIME_PATH_PREFIX "%TEMP%\\polypaudio-"
91 #define POLYP_ROOTENV "POLYP_ROOT"
93 int pa_set_root(HANDLE handle
) {
94 char library_path
[MAX_PATH
+ sizeof(POLYP_ROOTENV
) + 1], *sep
;
96 strcpy(library_path
, POLYP_ROOTENV
"=");
98 if (!GetModuleFileName(handle
, library_path
+ sizeof(POLYP_ROOTENV
), MAX_PATH
))
101 sep
= strrchr(library_path
, '\\');
105 if (_putenv(library_path
) < 0)
113 /** Make a file descriptor nonblock. Doesn't do any error checking */
114 void pa_make_nonblock_fd(int fd
) {
119 if ((v
= fcntl(fd
, F_GETFL
)) >= 0)
120 if (!(v
& O_NONBLOCK
))
121 fcntl(fd
, F_SETFL
, v
|O_NONBLOCK
);
122 #elif defined(OS_IS_WIN32)
124 if (ioctlsocket(fd
, FIONBIO
, &arg
) < 0) {
125 if (WSAGetLastError() == WSAENOTSOCK
)
126 pa_log_warn(__FILE__
": WARNING: Only sockets can be made non-blocking!");
129 pa_log_warn(__FILE__
": WARNING: Non-blocking I/O not supported.!");
133 /** Creates a directory securely */
134 int pa_make_secure_dir(const char* dir
) {
141 if (mkdir(dir
, 0700) < 0)
147 chown(dir
, getuid(), getgid());
154 if (lstat(dir
, &st
) < 0)
156 if (stat(dir
, &st
) < 0)
161 if (!S_ISDIR(st
.st_mode
) || (st
.st_uid
!= getuid()) || ((st
.st_mode
& 0777) != 0700))
164 fprintf(stderr
, "FIXME: pa_make_secure_dir()\n");
174 /* Return a newly allocated sting containing the parent directory of the specified file */
175 char *pa_parent_dir(const char *fn
) {
176 char *slash
, *dir
= pa_xstrdup(fn
);
178 slash
= (char*) pa_path_get_filename(dir
);
186 /* Creates a the parent directory of the specified path securely */
187 int pa_make_secure_parent_dir(const char *fn
) {
191 if (!(dir
= pa_parent_dir(fn
)))
194 if (pa_make_secure_dir(dir
) < 0)
204 /** Platform independent read function. Necessary since not all systems
205 * treat all file descriptors equal. */
206 ssize_t
pa_read(int fd
, void *buf
, size_t count
) {
210 r
= recv(fd
, buf
, count
, 0);
212 if (WSAGetLastError() != WSAENOTSOCK
) {
213 errno
= WSAGetLastError();
220 r
= read(fd
, buf
, count
);
225 /** Similar to pa_read(), but handles writes */
226 ssize_t
pa_write(int fd
, const void *buf
, size_t count
) {
230 r
= send(fd
, buf
, count
, 0);
232 if (WSAGetLastError() != WSAENOTSOCK
) {
233 errno
= WSAGetLastError();
240 r
= write(fd
, buf
, count
);
245 /** Calls read() in a loop. Makes sure that as much as 'size' bytes,
246 * unless EOF is reached or an error occured */
247 ssize_t
pa_loop_read(int fd
, void*data
, size_t size
) {
249 assert(fd
>= 0 && data
&& size
);
254 if ((r
= pa_read(fd
, data
, size
)) < 0)
261 data
= (uint8_t*) data
+ r
;
268 /** Similar to pa_loop_read(), but wraps write() */
269 ssize_t
pa_loop_write(int fd
, const void*data
, size_t size
) {
271 assert(fd
>= 0 && data
&& size
);
276 if ((r
= pa_write(fd
, data
, size
)) < 0)
283 data
= (const uint8_t*) data
+ r
;
290 /* Print a warning messages in case that the given signal is not
291 * blocked or trapped */
292 void pa_check_signal_is_blocked(int sig
) {
293 #ifdef HAVE_SIGACTION
297 /* If POSIX threads are supported use thread-aware
298 * pthread_sigmask() function, to check if the signal is
299 * blocked. Otherwise fall back to sigprocmask() */
302 if (pthread_sigmask(SIG_SETMASK
, NULL
, &set
) < 0) {
304 if (sigprocmask(SIG_SETMASK
, NULL
, &set
) < 0) {
305 pa_log(__FILE__
": sigprocmask(): %s", pa_cstrerror(errno
));
312 if (sigismember(&set
, sig
))
315 /* Check whether the signal is trapped */
317 if (sigaction(sig
, NULL
, &sa
) < 0) {
318 pa_log(__FILE__
": sigaction(): %s", pa_cstrerror(errno
));
322 if (sa
.sa_handler
!= SIG_DFL
)
325 pa_log(__FILE__
": WARNING: %s is not trapped. This might cause malfunction!", pa_strsignal(sig
));
326 #else /* HAVE_SIGACTION */
327 pa_log(__FILE__
": WARNING: %s might not be trapped. This might cause malfunction!", pa_strsignal(sig
));
331 /* The following function is based on an example from the GNU libc
332 * documentation. This function is similar to GNU's asprintf(). */
333 char *pa_sprintf_malloc(const char *format
, ...) {
343 c
= pa_xrealloc(c
, size
);
345 va_start(ap
, format
);
346 r
= vsnprintf(c
, size
, format
, ap
);
349 if (r
> -1 && r
< size
)
352 if (r
> -1) /* glibc 2.1 */
359 /* Same as the previous function, but use a va_list instead of an
361 char *pa_vsprintf_malloc(const char *format
, va_list ap
) {
369 c
= pa_xrealloc(c
, size
);
370 r
= vsnprintf(c
, size
, format
, ap
);
372 if (r
> -1 && r
< size
)
375 if (r
> -1) /* glibc 2.1 */
382 /* Similar to OpenBSD's strlcpy() function */
383 char *pa_strlcpy(char *b
, const char *s
, size_t l
) {
384 assert(b
&& s
&& l
> 0);
391 #define NICE_LEVEL (-15)
393 /* Raise the priority of the current process as much as possible and
394 sensible: set the nice level to -15 and enable realtime scheduling if
396 void pa_raise_priority(void) {
398 #ifdef HAVE_SYS_RESOURCE_H
399 if (setpriority(PRIO_PROCESS
, 0, NICE_LEVEL
) < 0)
400 pa_log_warn(__FILE__
": setpriority(): %s", pa_cstrerror(errno
));
402 pa_log_info(__FILE__
": Successfully gained nice level %i.", NICE_LEVEL
);
405 #ifdef _POSIX_PRIORITY_SCHEDULING
407 struct sched_param sp
;
409 if (sched_getparam(0, &sp
) < 0) {
410 pa_log(__FILE__
": sched_getparam(): %s", pa_cstrerror(errno
));
414 sp
.sched_priority
= 1;
415 if (sched_setscheduler(0, SCHED_FIFO
, &sp
) < 0) {
416 pa_log_warn(__FILE__
": sched_setscheduler(): %s", pa_cstrerror(errno
));
420 pa_log_info(__FILE__
": Successfully enabled SCHED_FIFO scheduling.");
425 if (!SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS
))
426 pa_log_warn(__FILE__
": SetPriorityClass() failed: 0x%08X", GetLastError());
428 pa_log_info(__FILE__
": Successfully gained high priority class.");
432 /* Reset the priority to normal, inverting the changes made by pa_raise_priority() */
433 void pa_reset_priority(void) {
435 SetPriorityClass(GetCurrentProcess(), NORMAL_PRIORITY_CLASS
);
438 #ifdef _POSIX_PRIORITY_SCHEDULING
440 struct sched_param sp
;
441 sched_getparam(0, &sp
);
442 sp
.sched_priority
= 0;
443 sched_setscheduler(0, SCHED_OTHER
, &sp
);
447 #ifdef HAVE_SYS_RESOURCE_H
448 setpriority(PRIO_PROCESS
, 0, 0);
452 /* Set the FD_CLOEXEC flag for a fd */
453 int pa_fd_set_cloexec(int fd
, int b
) {
459 if ((v
= fcntl(fd
, F_GETFD
, 0)) < 0)
462 v
= (v
& ~FD_CLOEXEC
) | (b
? FD_CLOEXEC
: 0);
464 if (fcntl(fd
, F_SETFD
, v
) < 0)
471 /* Try to parse a boolean string value.*/
472 int pa_parse_boolean(const char *v
) {
474 if (!strcmp(v
, "1") || v
[0] == 'y' || v
[0] == 'Y' || v
[0] == 't' || v
[0] == 'T' || !strcasecmp(v
, "on"))
476 else if (!strcmp(v
, "0") || v
[0] == 'n' || v
[0] == 'N' || v
[0] == 'f' || v
[0] == 'F' || !strcasecmp(v
, "off"))
482 /* Split the specified string wherever one of the strings in delimiter
483 * occurs. Each time it is called returns a newly allocated string
484 * with pa_xmalloc(). The variable state points to, should be
485 * initiallized to NULL before the first call. */
486 char *pa_split(const char *c
, const char *delimiter
, const char**state
) {
487 const char *current
= *state
? *state
: c
;
493 l
= strcspn(current
, delimiter
);
499 return pa_xstrndup(current
, l
);
502 /* What is interpreted as whitespace? */
503 #define WHITESPACE " \t\n"
505 /* Split a string into words. Otherwise similar to pa_split(). */
506 char *pa_split_spaces(const char *c
, const char **state
) {
507 const char *current
= *state
? *state
: c
;
510 if (!*current
|| *c
== 0)
513 current
+= strspn(current
, WHITESPACE
);
514 l
= strcspn(current
, WHITESPACE
);
518 return pa_xstrndup(current
, l
);
521 /* Return the name of an UNIX signal. Similar to GNU's strsignal() */
522 const char *pa_strsignal(int sig
) {
524 case SIGINT
: return "SIGINT";
525 case SIGTERM
: return "SIGTERM";
527 case SIGUSR1
: return "SIGUSR1";
530 case SIGUSR2
: return "SIGUSR2";
533 case SIGXCPU
: return "SIGXCPU";
536 case SIGPIPE
: return "SIGPIPE";
539 case SIGCHLD
: return "SIGCHLD";
542 case SIGHUP
: return "SIGHUP";
544 default: return "UNKNOWN SIGNAL";
550 /* Check whether the specified GID and the group name match */
551 static int is_group(gid_t gid
, const char *name
) {
552 struct group group
, *result
= NULL
;
557 #ifdef HAVE_GETGRGID_R
558 #ifdef _SC_GETGR_R_SIZE_MAX
559 n
= sysconf(_SC_GETGR_R_SIZE_MAX
);
564 data
= pa_xmalloc(n
);
566 if (getgrgid_r(gid
, &group
, data
, n
, &result
) < 0 || !result
) {
567 pa_log(__FILE__
": getgrgid_r(%u): %s", gid
, pa_cstrerror(errno
));
571 r
= strcmp(name
, result
->gr_name
) == 0;
576 /* XXX Not thread-safe, but needed on OSes (e.g. FreeBSD 4.X) that do not
577 * support getgrgid_r. */
578 if ((result
= getgrgid(gid
)) == NULL
) {
579 pa_log(__FILE__
": getgrgid(%u): %s", gid
, pa_cstrerror(errno
));
583 r
= strcmp(name
, result
->gr_name
) == 0;
591 /* Check the current user is member of the specified group */
592 int pa_own_uid_in_group(const char *name
, gid_t
*gid
) {
593 GETGROUPS_T
*gids
, tgid
;
594 int n
= sysconf(_SC_NGROUPS_MAX
);
599 gids
= pa_xmalloc(sizeof(GETGROUPS_T
)*n
);
601 if ((n
= getgroups(n
, gids
)) < 0) {
602 pa_log(__FILE__
": getgroups(): %s", pa_cstrerror(errno
));
606 for (i
= 0; i
< n
; i
++) {
607 if (is_group(gids
[i
], name
) > 0) {
614 if (is_group(tgid
= getgid(), name
) > 0) {
628 int pa_uid_in_group(uid_t uid
, const char *name
) {
631 struct group grbuf
, *gr
;
635 g_n
= sysconf(_SC_GETGR_R_SIZE_MAX
);
636 g_buf
= pa_xmalloc(g_n
);
638 p_n
= sysconf(_SC_GETPW_R_SIZE_MAX
);
639 p_buf
= pa_xmalloc(p_n
);
641 if (getgrnam_r(name
, &grbuf
, g_buf
, (size_t) g_n
, &gr
) != 0 || !gr
)
645 for (i
= gr
->gr_mem
; *i
; i
++) {
646 struct passwd pwbuf
, *pw
;
648 if (getpwnam_r(*i
, &pwbuf
, p_buf
, (size_t) p_n
, &pw
) != 0 || !pw
)
651 if (pw
->pw_uid
== uid
) {
664 #else /* HAVE_GRP_H */
666 int pa_own_uid_in_group(const char *name
, gid_t
*gid
) {
671 int pa_uid_in_group(uid_t uid
, const char *name
) {
677 /* Lock or unlock a file entirely.
678 (advisory on UNIX, mandatory on Windows) */
679 int pa_lock_fd(int fd
, int b
) {
683 /* Try a R/W lock first */
685 flock
.l_type
= b
? F_WRLCK
: F_UNLCK
;
686 flock
.l_whence
= SEEK_SET
;
690 if (fcntl(fd
, F_SETLKW
, &flock
) >= 0)
693 /* Perhaps the file descriptor qas opened for read only, than try again with a read lock. */
694 if (b
&& errno
== EBADF
) {
695 flock
.l_type
= F_RDLCK
;
696 if (fcntl(fd
, F_SETLKW
, &flock
) >= 0)
700 pa_log(__FILE__
": %slock: %s", !b
? "un" : "",
701 pa_cstrerror(errno
));
705 HANDLE h
= (HANDLE
)_get_osfhandle(fd
);
707 if (b
&& LockFile(h
, 0, 0, 0xFFFFFFFF, 0xFFFFFFFF))
709 if (!b
&& UnlockFile(h
, 0, 0, 0xFFFFFFFF, 0xFFFFFFFF))
712 pa_log(__FILE__
": %slock failed: 0x%08X", !b
? "un" : "", GetLastError());
718 /* Remove trailing newlines from a string */
719 char* pa_strip_nl(char *s
) {
722 s
[strcspn(s
, "\r\n")] = 0;
726 /* Create a temporary lock file and lock it. */
727 int pa_lock_lockfile(const char *fn
) {
734 if ((fd
= open(fn
, O_CREAT
|O_RDWR
, S_IRUSR
|S_IWUSR
)) < 0) {
735 pa_log(__FILE__
": failed to create lock file '%s': %s", fn
,
736 pa_cstrerror(errno
));
740 if (pa_lock_fd(fd
, 1) < 0) {
741 pa_log(__FILE__
": failed to lock file '%s'.", fn
);
745 if (fstat(fd
, &st
) < 0) {
746 pa_log(__FILE__
": failed to fstat() file '%s'.", fn
);
750 /* Check wheter the file has been removed meanwhile. When yes, restart this loop, otherwise, we're done */
751 if (st
.st_nlink
>= 1)
754 if (pa_lock_fd(fd
, 0) < 0) {
755 pa_log(__FILE__
": failed to unlock file '%s'.", fn
);
760 pa_log(__FILE__
": failed to close file '%s'.", fn
);
777 /* Unlock a temporary lcok file */
778 int pa_unlock_lockfile(const char *fn
, int fd
) {
780 assert(fn
&& fd
>= 0);
782 if (unlink(fn
) < 0) {
783 pa_log_warn(__FILE__
": WARNING: unable to remove lock file '%s': %s",
784 fn
, pa_cstrerror(errno
));
788 if (pa_lock_fd(fd
, 0) < 0) {
789 pa_log_warn(__FILE__
": WARNING: failed to unlock file '%s'.", fn
);
794 pa_log_warn(__FILE__
": WARNING: failed to close lock file '%s': %s",
795 fn
, pa_cstrerror(errno
));
802 /* Try to open a configuration file. If "env" is specified, open the
803 * value of the specified environment variable. Otherwise look for a
804 * file "local" in the home directory or a file "global" in global
805 * file system. If "result" is non-NULL, a pointer to a newly
806 * allocated buffer containing the used configuration file is
808 FILE *pa_open_config_file(const char *global
, const char *local
, const char *env
, char **result
, const char *mode
) {
815 if (!getenv(POLYP_ROOTENV
))
819 if (env
&& (fn
= getenv(env
))) {
821 if (!ExpandEnvironmentStrings(fn
, buf
, PATH_MAX
))
827 *result
= pa_xstrdup(fn
);
829 return fopen(fn
, mode
);
832 if (local
&& pa_get_home_dir(h
, sizeof(h
))) {
836 fn
= lfn
= pa_sprintf_malloc("%s/%s", h
, local
);
839 if (!ExpandEnvironmentStrings(lfn
, buf
, PATH_MAX
))
846 if (f
|| errno
!= ENOENT
) {
848 *result
= pa_xstrdup(fn
);
864 if (!ExpandEnvironmentStrings(global
, buf
, PATH_MAX
))
870 *result
= pa_xstrdup(global
);
872 return fopen(global
, mode
);
875 /* Format the specified data as a hexademical string */
876 char *pa_hexstr(const uint8_t* d
, size_t dlength
, char *s
, size_t slength
) {
878 const char hex
[] = "0123456789abcdef";
879 assert(d
&& s
&& slength
> 0);
881 while (i
< dlength
&& j
+3 <= slength
) {
882 s
[j
++] = hex
[*d
>> 4];
883 s
[j
++] = hex
[*d
& 0xF];
889 s
[j
< slength
? j
: slength
] = 0;
893 /* Convert a hexadecimal digit to a number or -1 if invalid */
894 static int hexc(char c
) {
895 if (c
>= '0' && c
<= '9')
898 if (c
>= 'A' && c
<= 'F')
901 if (c
>= 'a' && c
<= 'f')
907 /* Parse a hexadecimal string as created by pa_hexstr() to a BLOB */
908 size_t pa_parsehex(const char *p
, uint8_t *d
, size_t dlength
) {
912 while (j
< dlength
&& *p
) {
915 if ((b
= hexc(*(p
++))) < 0)
918 d
[j
] = (uint8_t) (b
<< 4);
923 if ((b
= hexc(*(p
++))) < 0)
933 /* Returns nonzero when *s starts with *pfx */
934 int pa_startswith(const char *s
, const char *pfx
) {
942 return strlen(s
) >= l
&& strncmp(s
, pfx
, l
) == 0;
945 /* Returns nonzero when *s ends with *sfx */
946 int pa_endswith(const char *s
, const char *sfx
) {
955 return l1
>= l2
&& strcmp(s
+l1
-l2
, sfx
) == 0;
958 /* if fn is null return the polypaudio run time path in s (/tmp/polypaudio)
959 * if fn is non-null and starts with / return fn in s
960 * otherwise append fn to the run time path and return it in s */
961 char *pa_runtime_path(const char *fn
, char *s
, size_t l
) {
965 if (fn
&& *fn
== '/')
967 if (fn
&& strlen(fn
) >= 3 && isalpha(fn
[0]) && fn
[1] == ':' && fn
[2] == '\\')
969 return pa_strlcpy(s
, fn
, l
);
972 snprintf(s
, l
, "%s%s%c%s", PA_RUNTIME_PATH_PREFIX
, pa_get_user_name(u
, sizeof(u
)), PATH_SEP
, fn
);
974 snprintf(s
, l
, "%s%s", PA_RUNTIME_PATH_PREFIX
, pa_get_user_name(u
, sizeof(u
)));
980 ExpandEnvironmentStrings(buf
, s
, l
);
987 /* Convert the string s to a signed integer in *ret_i */
988 int pa_atoi(const char *s
, int32_t *ret_i
) {
993 l
= strtol(s
, &x
, 0);
998 *ret_i
= (int32_t) l
;
1003 /* Convert the string s to an unsigned integer in *ret_u */
1004 int pa_atou(const char *s
, uint32_t *ret_u
) {
1009 l
= strtoul(s
, &x
, 0);
1014 *ret_u
= (uint32_t) l
;