]>
code.delx.au - pulseaudio/blob - src/pulsecore/core-util.c
2 This file is part of PulseAudio.
4 Copyright 2004-2006 Lennart Poettering
5 Copyright 2004 Joe Marcus Clarke
6 Copyright 2006-2007 Pierre Ossman <ossman@cendio.se> for Cendio AB
8 PulseAudio is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as
10 published by the Free Software Foundation; either version 2.1 of the
11 License, or (at your option) any later version.
13 PulseAudio is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public
19 License along with PulseAudio; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
39 #include <sys/types.h>
52 #ifdef HAVE_SYS_RESOURCE_H
53 #include <sys/resource.h>
56 #ifdef HAVE_SYS_CAPABILITY_H
57 #include <sys/capability.h>
60 #ifdef HAVE_SYS_MMAN_H
84 #ifdef HAVE_LIBSAMPLERATE
85 #include <samplerate.h>
88 #include <pulse/xmalloc.h>
89 #include <pulse/util.h>
90 #include <pulse/utf8.h>
92 #include <pulsecore/core-error.h>
93 #include <pulsecore/winsock.h>
94 #include <pulsecore/log.h>
95 #include <pulsecore/macro.h>
96 #include <pulsecore/thread.h>
98 #include "core-util.h"
100 /* Not all platforms have this */
102 #define MSG_NOSIGNAL 0
107 #define PULSE_ROOTENV "PULSE_ROOT"
109 int pa_set_root ( HANDLE handle
) {
110 char library_path
[ MAX_PATH
+ sizeof ( PULSE_ROOTENV
) + 1 ], * sep
;
112 strcpy ( library_path
, PULSE_ROOTENV
"=" );
114 if (! GetModuleFileName ( handle
, library_path
+ sizeof ( PULSE_ROOTENV
), MAX_PATH
))
117 sep
= strrchr ( library_path
, PA_PATH_SEP_CHAR
);
121 if ( _putenv ( library_path
) < 0 )
129 /** Make a file descriptor nonblock. Doesn't do any error checking */
130 void pa_make_fd_nonblock ( int fd
) {
136 pa_assert_se (( v
= fcntl ( fd
, F_GETFL
)) >= 0 );
138 if (!( v
& O_NONBLOCK
))
139 pa_assert_se ( fcntl ( fd
, F_SETFL
, v
| O_NONBLOCK
) >= 0 );
141 #elif defined(OS_IS_WIN32)
143 if ( ioctlsocket ( fd
, FIONBIO
, & arg
) < 0 ) {
144 pa_assert_se ( WSAGetLastError () == WSAENOTSOCK
);
145 pa_log_warn ( "Only sockets can be made non-blocking!" );
148 pa_log_warn ( "Non-blocking I/O not supported.!" );
153 /* Set the FD_CLOEXEC flag for a fd */
154 void pa_make_fd_cloexec ( int fd
) {
160 pa_assert_se (( v
= fcntl ( fd
, F_GETFD
, 0 )) >= 0 );
162 if (!( v
& FD_CLOEXEC
))
163 pa_assert_se ( fcntl ( fd
, F_SETFD
, v
| FD_CLOEXEC
) >= 0 );
168 /** Creates a directory securely */
169 int pa_make_secure_dir ( const char * dir
, mode_t m
, uid_t uid
, gid_t gid
) {
186 if ( r
< 0 && errno
!= EEXIST
)
190 if ( uid
== ( uid_t
)- 1 )
192 if ( gid
== ( gid_t
)- 1 )
194 ( void ) chown ( dir
, uid
, gid
);
202 if ( lstat ( dir
, & st
) < 0 )
204 if ( stat ( dir
, & st
) < 0 )
209 if (! S_ISDIR ( st
. st_mode
) ||
210 ( st
. st_uid
!= uid
) ||
211 ( st
. st_gid
!= gid
) ||
212 (( st
. st_mode
& 0777 ) != m
)) {
217 pa_log_warn ( "Secure directory creation not supported on Win32." );
227 /* Return a newly allocated sting containing the parent directory of the specified file */
228 char * pa_parent_dir ( const char * fn
) {
229 char * slash
, * dir
= pa_xstrdup ( fn
);
231 if (( slash
= ( char *) pa_path_get_filename ( dir
)) == dir
) {
240 /* Creates a the parent directory of the specified path securely */
241 int pa_make_secure_parent_dir ( const char * fn
, mode_t m
, uid_t uid
, gid_t gid
) {
245 if (!( dir
= pa_parent_dir ( fn
)))
248 if ( pa_make_secure_dir ( dir
, m
, uid
, gid
) < 0 )
258 /** Platform independent read function. Necessary since not all
259 * systems treat all file descriptors equal. If type is
260 * non-NULL it is used to cache the type of the fd. This is
261 * useful for making sure that only a single syscall is executed per
262 * function call. The variable pointed to should be initialized to 0
264 ssize_t
pa_read ( int fd
, void * buf
, size_t count
, int * type
) {
268 if (! type
|| * type
== 0 ) {
271 if (( r
= recv ( fd
, buf
, count
, 0 )) >= 0 )
274 if ( WSAGetLastError () != WSAENOTSOCK
) {
275 errno
= WSAGetLastError ();
285 return read ( fd
, buf
, count
);
288 /** Similar to pa_read(), but handles writes */
289 ssize_t
pa_write ( int fd
, const void * buf
, size_t count
, int * type
) {
291 if (! type
|| * type
== 0 ) {
294 if (( r
= send ( fd
, buf
, count
, MSG_NOSIGNAL
)) >= 0 )
298 if ( WSAGetLastError () != WSAENOTSOCK
) {
299 errno
= WSAGetLastError ();
303 if ( errno
!= ENOTSOCK
)
311 return write ( fd
, buf
, count
);
314 /** Calls read() in a loop. Makes sure that as much as 'size' bytes,
315 * unless EOF is reached or an error occured */
316 ssize_t
pa_loop_read ( int fd
, void * data
, size_t size
, int * type
) {
332 if (( r
= pa_read ( fd
, data
, size
, type
)) < 0 )
339 data
= ( uint8_t *) data
+ r
;
346 /** Similar to pa_loop_read(), but wraps write() */
347 ssize_t
pa_loop_write ( int fd
, const void * data
, size_t size
, int * type
) {
363 if (( r
= pa_write ( fd
, data
, size
, type
)) < 0 )
370 data
= ( const uint8_t *) data
+ r
;
377 /** Platform independent read function. Necessary since not all
378 * systems treat all file descriptors equal. */
379 int pa_close ( int fd
) {
384 if (( ret
= closesocket ( fd
)) == 0 )
387 if ( WSAGetLastError () != WSAENOTSOCK
) {
388 errno
= WSAGetLastError ();
396 /* Print a warning messages in case that the given signal is not
397 * blocked or trapped */
398 void pa_check_signal_is_blocked ( int sig
) {
399 #ifdef HAVE_SIGACTION
403 /* If POSIX threads are supported use thread-aware
404 * pthread_sigmask() function, to check if the signal is
405 * blocked. Otherwise fall back to sigprocmask() */
408 if ( pthread_sigmask ( SIG_SETMASK
, NULL
, & set
) < 0 ) {
410 if ( sigprocmask ( SIG_SETMASK
, NULL
, & set
) < 0 ) {
411 pa_log ( "sigprocmask(): %s" , pa_cstrerror ( errno
));
418 if ( sigismember (& set
, sig
))
421 /* Check whether the signal is trapped */
423 if ( sigaction ( sig
, NULL
, & sa
) < 0 ) {
424 pa_log ( "sigaction(): %s" , pa_cstrerror ( errno
));
428 if ( sa
. sa_handler
!= SIG_DFL
)
431 pa_log_warn ( "%s is not trapped. This might cause malfunction!" , pa_sig2str ( sig
));
432 #else /* HAVE_SIGACTION */
433 pa_log_warn ( "%s might not be trapped. This might cause malfunction!" , pa_sig2str ( sig
));
437 /* The following function is based on an example from the GNU libc
438 * documentation. This function is similar to GNU's asprintf(). */
439 char * pa_sprintf_malloc ( const char * format
, ...) {
449 c
= pa_xrealloc ( c
, size
);
451 va_start ( ap
, format
);
452 r
= vsnprintf ( c
, size
, format
, ap
);
457 if ( r
> - 1 && r
< size
)
460 if ( r
> - 1 ) /* glibc 2.1 */
467 /* Same as the previous function, but use a va_list instead of an
469 char * pa_vsprintf_malloc ( const char * format
, va_list ap
) {
479 c
= pa_xrealloc ( c
, size
);
482 r
= vsnprintf ( c
, size
, format
, aq
);
487 if ( r
> - 1 && r
< size
)
490 if ( r
> - 1 ) /* glibc 2.1 */
497 /* Similar to OpenBSD's strlcpy() function */
498 char * pa_strlcpy ( char * b
, const char * s
, size_t l
) {
508 /* Make the current thread a realtime thread, and acquire the highest
509 * rtprio we can get that is less or equal the specified parameter. If
510 * the thread is already realtime, don't do anything. */
511 int pa_make_realtime ( int rtprio
) {
513 #ifdef _POSIX_PRIORITY_SCHEDULING
514 struct sched_param sp
;
517 memset (& sp
, 0 , sizeof ( sp
));
520 if (( r
= pthread_getschedparam ( pthread_self (), & policy
, & sp
)) != 0 ) {
521 pa_log ( "pthread_getschedgetparam(): %s" , pa_cstrerror ( r
));
525 if ( policy
== SCHED_FIFO
&& sp
. sched_priority
>= rtprio
) {
526 pa_log_info ( "Thread already being scheduled with SCHED_FIFO with priority %i." , sp
. sched_priority
);
530 sp
. sched_priority
= rtprio
;
531 if (( r
= pthread_setschedparam ( pthread_self (), SCHED_FIFO
, & sp
)) != 0 ) {
533 while ( sp
. sched_priority
> 1 ) {
534 sp
. sched_priority
--;
536 if (( r
= pthread_setschedparam ( pthread_self (), SCHED_FIFO
, & sp
)) == 0 ) {
537 pa_log_info ( "Successfully enabled SCHED_FIFO scheduling for thread, with priority %i, which is lower than the requested %i." , sp
. sched_priority
, rtprio
);
542 pa_log_warn ( "pthread_setschedparam(): %s" , pa_cstrerror ( r
));
546 pa_log_info ( "Successfully enabled SCHED_FIFO scheduling for thread, with priority %i." , sp
. sched_priority
);
553 /* This is merely used for giving the user a hint. This is not correct
554 * for anything security related */
555 pa_bool_t
pa_can_realtime ( void ) {
560 #if defined(HAVE_SYS_RESOURCE_H) && defined(RLIMIT_RTPRIO)
564 if ( getrlimit ( RLIMIT_RTPRIO
, & rl
) >= 0 )
565 if ( rl
. rlim_cur
> 0 || rl
. rlim_cur
== RLIM_INFINITY
)
570 #if defined(HAVE_SYS_CAPABILITY_H) && defined(CAP_SYS_NICE)
574 if (( cap
= cap_get_proc ())) {
575 cap_flag_value_t flag
= CAP_CLEAR
;
577 if ( cap_get_flag ( cap
, CAP_SYS_NICE
, CAP_EFFECTIVE
, & flag
) >= 0 )
578 if ( flag
== CAP_SET
) {
591 /* This is merely used for giving the user a hint. This is not correct
592 * for anything security related */
593 pa_bool_t
pa_can_high_priority ( void ) {
598 #if defined(HAVE_SYS_RESOURCE_H) && defined(RLIMIT_RTPRIO)
602 if ( getrlimit ( RLIMIT_NICE
, & rl
) >= 0 )
603 if ( rl
. rlim_cur
>= 21 || rl
. rlim_cur
== RLIM_INFINITY
)
608 #if defined(HAVE_SYS_CAPABILITY_H) && defined(CAP_SYS_NICE)
612 if (( cap
= cap_get_proc ())) {
613 cap_flag_value_t flag
= CAP_CLEAR
;
615 if ( cap_get_flag ( cap
, CAP_SYS_NICE
, CAP_EFFECTIVE
, & flag
) >= 0 )
616 if ( flag
== CAP_SET
) {
629 /* Raise the priority of the current process as much as possible that
630 * is <= the specified nice level..*/
631 int pa_raise_priority ( int nice_level
) {
633 #ifdef HAVE_SYS_RESOURCE_H
634 if ( setpriority ( PRIO_PROCESS
, 0 , nice_level
) < 0 ) {
637 for ( n
= nice_level
+ 1 ; n
< 0 ; n
++) {
639 if ( setpriority ( PRIO_PROCESS
, 0 , n
) == 0 ) {
640 pa_log_info ( "Successfully acquired nice level %i, which is lower than the requested %i." , n
, nice_level
);
645 pa_log_warn ( "setpriority(): %s" , pa_cstrerror ( errno
));
649 pa_log_info ( "Successfully gained nice level %i." , nice_level
);
653 if ( nice_level
< 0 ) {
654 if (! SetPriorityClass ( GetCurrentProcess (), HIGH_PRIORITY_CLASS
)) {
655 pa_log_warn ( "SetPriorityClass() failed: 0x%08X" , GetLastError ());
658 pa_log_info ( "Successfully gained high priority class." );
665 /* Reset the priority to normal, inverting the changes made by
666 * pa_raise_priority() and pa_make_realtime()*/
667 void pa_reset_priority ( void ) {
668 #ifdef HAVE_SYS_RESOURCE_H
669 struct sched_param sp
;
671 setpriority ( PRIO_PROCESS
, 0 , 0 );
673 memset (& sp
, 0 , sizeof ( sp
));
674 pa_assert_se ( pthread_setschedparam ( pthread_self (), SCHED_OTHER
, & sp
) == 0 );
678 SetPriorityClass ( GetCurrentProcess (), NORMAL_PRIORITY_CLASS
);
682 /* Try to parse a boolean string value.*/
683 int pa_parse_boolean ( const char * v
) {
686 if (! strcmp ( v
, "1" ) || v
[ 0 ] == 'y' || v
[ 0 ] == 'Y' || v
[ 0 ] == 't' || v
[ 0 ] == 'T' || ! strcasecmp ( v
, "on" ))
688 else if (! strcmp ( v
, "0" ) || v
[ 0 ] == 'n' || v
[ 0 ] == 'N' || v
[ 0 ] == 'f' || v
[ 0 ] == 'F' || ! strcasecmp ( v
, "off" ))
694 /* Split the specified string wherever one of the strings in delimiter
695 * occurs. Each time it is called returns a newly allocated string
696 * with pa_xmalloc(). The variable state points to, should be
697 * initiallized to NULL before the first call. */
698 char * pa_split ( const char * c
, const char * delimiter
, const char ** state
) {
699 const char * current
= * state
? * state
: c
;
705 l
= strcspn ( current
, delimiter
);
711 return pa_xstrndup ( current
, l
);
714 /* What is interpreted as whitespace? */
715 #define WHITESPACE " \t\n "
717 /* Split a string into words. Otherwise similar to pa_split(). */
718 char * pa_split_spaces ( const char * c
, const char ** state
) {
719 const char * current
= * state
? * state
: c
;
722 if (!* current
|| * c
== 0 )
725 current
+= strspn ( current
, WHITESPACE
);
726 l
= strcspn ( current
, WHITESPACE
);
730 return pa_xstrndup ( current
, l
);
733 PA_STATIC_TLS_DECLARE ( signame
, pa_xfree
);
735 /* Return the name of an UNIX signal. Similar to Solaris sig2str() */
736 const char * pa_sig2str ( int sig
) {
749 char buf
[ SIG2STR_MAX
];
751 if ( sig2str ( sig
, buf
) == 0 ) {
752 pa_xfree ( PA_STATIC_TLS_GET ( signame
));
753 t
= pa_sprintf_malloc ( "SIG%s" , buf
);
754 PA_STATIC_TLS_SET ( signame
, t
);
762 case SIGHUP
: return "SIGHUP" ;
764 case SIGINT
: return "SIGINT" ;
766 case SIGQUIT
: return "SIGQUIT" ;
768 case SIGILL
: return "SIGULL" ;
770 case SIGTRAP
: return "SIGTRAP" ;
772 case SIGABRT
: return "SIGABRT" ;
774 case SIGBUS
: return "SIGBUS" ;
776 case SIGFPE
: return "SIGFPE" ;
778 case SIGKILL
: return "SIGKILL" ;
781 case SIGUSR1
: return "SIGUSR1" ;
783 case SIGSEGV
: return "SIGSEGV" ;
785 case SIGUSR2
: return "SIGUSR2" ;
788 case SIGPIPE
: return "SIGPIPE" ;
791 case SIGALRM
: return "SIGALRM" ;
793 case SIGTERM
: return "SIGTERM" ;
795 case SIGSTKFLT
: return "SIGSTKFLT" ;
798 case SIGCHLD
: return "SIGCHLD" ;
801 case SIGCONT
: return "SIGCONT" ;
804 case SIGSTOP
: return "SIGSTOP" ;
807 case SIGTSTP
: return "SIGTSTP" ;
810 case SIGTTIN
: return "SIGTTIN" ;
813 case SIGTTOU
: return "SIGTTOU" ;
816 case SIGURG
: return "SIGURG" ;
819 case SIGXCPU
: return "SIGXCPU" ;
822 case SIGXFSZ
: return "SIGXFSZ" ;
825 case SIGVTALRM
: return "SIGVTALRM" ;
828 case SIGPROF
: return "SIGPROF" ;
831 case SIGWINCH
: return "SIGWINCH" ;
834 case SIGIO
: return "SIGIO" ;
837 case SIGPWR
: return "SIGPWR" ;
840 case SIGSYS
: return "SIGSYS" ;
845 if ( sig
>= SIGRTMIN
&& sig
<= SIGRTMAX
) {
846 pa_xfree ( PA_STATIC_TLS_GET ( signame
));
847 t
= pa_sprintf_malloc ( "SIGRTMIN+%i" , sig
- SIGRTMIN
);
848 PA_STATIC_TLS_SET ( signame
, t
);
857 pa_xfree ( PA_STATIC_TLS_GET ( signame
));
858 t
= pa_sprintf_malloc ( "SIG%i" , sig
);
859 PA_STATIC_TLS_SET ( signame
, t
);
865 /* Check whether the specified GID and the group name match */
866 static int is_group ( gid_t gid
, const char * name
) {
867 struct group group
, * result
= NULL
;
872 #ifdef HAVE_GETGRGID_R
873 #ifdef _SC_GETGR_R_SIZE_MAX
874 n
= sysconf ( _SC_GETGR_R_SIZE_MAX
);
879 data
= pa_xmalloc ( n
);
881 if ( getgrgid_r ( gid
, & group
, data
, n
, & result
) < 0 || ! result
) {
882 pa_log ( "getgrgid_r(%u): %s" , ( unsigned ) gid
, pa_cstrerror ( errno
));
886 r
= strcmp ( name
, result
-> gr_name
) == 0 ;
891 /* XXX Not thread-safe, but needed on OSes (e.g. FreeBSD 4.X) that do not
892 * support getgrgid_r. */
893 if (( result
= getgrgid ( gid
)) == NULL
) {
894 pa_log ( "getgrgid(%u): %s" , gid
, pa_cstrerror ( errno
));
898 r
= strcmp ( name
, result
-> gr_name
) == 0 ;
906 /* Check the current user is member of the specified group */
907 int pa_own_uid_in_group ( const char * name
, gid_t
* gid
) {
908 GETGROUPS_T
* gids
, tgid
;
909 int n
= sysconf ( _SC_NGROUPS_MAX
);
914 gids
= pa_xmalloc ( sizeof ( GETGROUPS_T
)* n
);
916 if (( n
= getgroups ( n
, gids
)) < 0 ) {
917 pa_log ( "getgroups(): %s" , pa_cstrerror ( errno
));
921 for ( i
= 0 ; i
< n
; i
++) {
922 if ( is_group ( gids
[ i
], name
) > 0 ) {
929 if ( is_group ( tgid
= getgid (), name
) > 0 ) {
943 /* Check whether the specifc user id is a member of the specified group */
944 int pa_uid_in_group ( uid_t uid
, const char * name
) {
947 struct group grbuf
, * gr
;
951 g_n
= sysconf ( _SC_GETGR_R_SIZE_MAX
);
952 g_buf
= pa_xmalloc ( g_n
);
954 p_n
= sysconf ( _SC_GETPW_R_SIZE_MAX
);
955 p_buf
= pa_xmalloc ( p_n
);
957 if ( getgrnam_r ( name
, & grbuf
, g_buf
, ( size_t ) g_n
, & gr
) != 0 || ! gr
)
961 for ( i
= gr
-> gr_mem
; * i
; i
++) {
962 struct passwd pwbuf
, * pw
;
964 if ( getpwnam_r (* i
, & pwbuf
, p_buf
, ( size_t ) p_n
, & pw
) != 0 || ! pw
)
967 if ( pw
-> pw_uid
== uid
) {
980 /* Get the GID of a gfiven group, return (gid_t) -1 on failure. */
981 gid_t
pa_get_gid_of_group ( const char * name
) {
982 gid_t ret
= ( gid_t
) - 1 ;
985 struct group grbuf
, * gr
;
987 g_n
= sysconf ( _SC_GETGR_R_SIZE_MAX
);
988 g_buf
= pa_xmalloc ( g_n
);
990 if ( getgrnam_r ( name
, & grbuf
, g_buf
, ( size_t ) g_n
, & gr
) != 0 || ! gr
)
1000 int pa_check_in_group ( gid_t g
) {
1001 gid_t gids
[ NGROUPS_MAX
];
1004 if (( r
= getgroups ( NGROUPS_MAX
, gids
)) < 0 )
1014 #else /* HAVE_GRP_H */
1016 int pa_own_uid_in_group ( const char * name
, gid_t
* gid
) {
1021 int pa_uid_in_group ( uid_t uid
, const char * name
) {
1025 gid_t
pa_get_gid_of_group ( const char * name
) {
1029 int pa_check_in_group ( gid_t g
) {
1035 /* Lock or unlock a file entirely.
1036 (advisory on UNIX, mandatory on Windows) */
1037 int pa_lock_fd ( int fd
, int b
) {
1041 /* Try a R/W lock first */
1043 flock
. l_type
= b
? F_WRLCK
: F_UNLCK
;
1044 flock
. l_whence
= SEEK_SET
;
1048 if ( fcntl ( fd
, F_SETLKW
, & flock
) >= 0 )
1051 /* Perhaps the file descriptor qas opened for read only, than try again with a read lock. */
1052 if ( b
&& errno
== EBADF
) {
1053 flock
. l_type
= F_RDLCK
;
1054 if ( fcntl ( fd
, F_SETLKW
, & flock
) >= 0 )
1058 pa_log ( "%slock: %s" , ! b
? "un" : "" , pa_cstrerror ( errno
));
1062 HANDLE h
= ( HANDLE
) _get_osfhandle ( fd
);
1064 if ( b
&& LockFile ( h
, 0 , 0 , 0xFFFFFFFF , 0xFFFFFFFF ))
1066 if (! b
&& UnlockFile ( h
, 0 , 0 , 0xFFFFFFFF , 0xFFFFFFFF ))
1069 pa_log ( "%slock failed: 0x%08X" , ! b
? "un" : "" , GetLastError ());
1075 /* Remove trailing newlines from a string */
1076 char * pa_strip_nl ( char * s
) {
1079 s
[ strcspn ( s
, " \r\n " )] = 0 ;
1083 /* Create a temporary lock file and lock it. */
1084 int pa_lock_lockfile ( const char * fn
) {
1091 if (( fd
= open ( fn
, O_CREAT
| O_RDWR
1098 , S_IRUSR
| S_IWUSR
)) < 0 ) {
1099 pa_log_warn ( "Failed to create lock file '%s': %s" , fn
, pa_cstrerror ( errno
));
1103 if ( pa_lock_fd ( fd
, 1 ) < 0 ) {
1104 pa_log_warn ( "Failed to lock file '%s'." , fn
);
1108 if ( fstat ( fd
, & st
) < 0 ) {
1109 pa_log_warn ( "Failed to fstat() file '%s': %s" , fn
, pa_cstrerror ( errno
));
1113 /* Check wheter the file has been removed meanwhile. When yes,
1114 * restart this loop, otherwise, we're done */
1115 if ( st
. st_nlink
>= 1 )
1118 if ( pa_lock_fd ( fd
, 0 ) < 0 ) {
1119 pa_log_warn ( "Failed to unlock file '%s'." , fn
);
1123 if ( pa_close ( fd
) < 0 ) {
1124 pa_log_warn ( "Failed to close file '%s': %s" , fn
, pa_cstrerror ( errno
));
1142 /* Unlock a temporary lcok file */
1143 int pa_unlock_lockfile ( const char * fn
, int fd
) {
1148 if ( unlink ( fn
) < 0 ) {
1149 pa_log_warn ( "Unable to remove lock file '%s': %s" , fn
, pa_cstrerror ( errno
));
1154 if ( pa_lock_fd ( fd
, 0 ) < 0 ) {
1155 pa_log_warn ( "Failed to unlock file '%s'." , fn
);
1159 if ( pa_close ( fd
) < 0 ) {
1160 pa_log_warn ( "Failed to close '%s': %s" , fn
, pa_cstrerror ( errno
));
1167 static char * get_dir ( mode_t m
, const char * env_name
) {
1171 if (( e
= getenv ( env_name
)))
1177 if (! pa_get_home_dir ( h
, sizeof ( h
))) {
1178 pa_log_error ( "Failed to get home directory." );
1182 if ( stat ( h
, & st
) < 0 ) {
1183 pa_log_error ( "Failed to stat home directory %s: %s" , h
, pa_cstrerror ( errno
));
1187 if ( st
. st_uid
!= getuid ()) {
1188 pa_log_error ( "Home directory %s not ours." , d
);
1192 d
= pa_sprintf_malloc ( "%s" PA_PATH_SEP
".pulse" , h
);
1195 if ( pa_make_secure_dir ( d
, m
, ( pid_t
) - 1 , ( pid_t
) - 1 ) < 0 ) {
1196 pa_log_error ( "Failed to create secure directory: %s" , pa_cstrerror ( errno
));
1203 char * pa_get_runtime_dir ( void ) {
1204 return get_dir ( pa_in_system_mode () ? 0755 : 0700 , "PULSE_RUNTIME_PATH" );
1207 char * pa_get_state_dir ( void ) {
1208 return get_dir ( 0700 , "PULSE_STATE_PATH" );
1211 /* Try to open a configuration file. If "env" is specified, open the
1212 * value of the specified environment variable. Otherwise look for a
1213 * file "local" in the home directory or a file "global" in global
1214 * file system. If "result" is non-NULL, a pointer to a newly
1215 * allocated buffer containing the used configuration file is
1217 FILE * pa_open_config_file ( const char * global
, const char * local
, const char * env
, char ** result
) {
1222 if (! getenv ( PULSE_ROOTENV
))
1226 if ( env
&& ( fn
= getenv ( env
))) {
1230 if (! ExpandEnvironmentStrings ( fn
, buf
, PATH_MAX
))
1235 if (( f
= fopen ( fn
, "r" ))) {
1237 * result
= pa_xstrdup ( fn
);
1242 pa_log_warn ( "Failed to open configuration file '%s': %s" , fn
, pa_cstrerror ( errno
));
1252 if (( e
= getenv ( "PULSE_CONFIG_PATH" )))
1253 fn
= lfn
= pa_sprintf_malloc ( "%s" PA_PATH_SEP
"%s" , e
, local
);
1254 else if ( pa_get_home_dir ( h
, sizeof ( h
)))
1255 fn
= lfn
= pa_sprintf_malloc ( "%s" PA_PATH_SEP
".pulse" PA_PATH_SEP
"%s" , h
, local
);
1258 if (! ExpandEnvironmentStrings ( lfn
, buf
, PATH_MAX
)) {
1265 if (( f
= fopen ( fn
, "r" ))) {
1267 * result
= pa_xstrdup ( fn
);
1273 if ( errno
!= ENOENT
) {
1274 pa_log_warn ( "Failed to open configuration file '%s': %s" , fn
, pa_cstrerror ( errno
));
1286 if (! ExpandEnvironmentStrings ( global
, buf
, PATH_MAX
))
1291 if (( f
= fopen ( global
, "r" ))) {
1294 * result
= pa_xstrdup ( global
);
1304 char * pa_find_config_file ( const char * global
, const char * local
, const char * env
) {
1309 if (! getenv ( PULSE_ROOTENV
))
1313 if ( env
&& ( fn
= getenv ( env
))) {
1315 if (! ExpandEnvironmentStrings ( fn
, buf
, PATH_MAX
))
1320 if ( access ( fn
, R_OK
) == 0 )
1321 return pa_xstrdup ( fn
);
1323 pa_log_warn ( "Failed to access configuration file '%s': %s" , fn
, pa_cstrerror ( errno
));
1332 if (( e
= getenv ( "PULSE_CONFIG_PATH" )))
1333 fn
= lfn
= pa_sprintf_malloc ( "%s" PA_PATH_SEP
"%s" , e
, local
);
1334 else if ( pa_get_home_dir ( h
, sizeof ( h
)))
1335 fn
= lfn
= pa_sprintf_malloc ( "%s" PA_PATH_SEP
".pulse" PA_PATH_SEP
"%s" , h
, local
);
1338 if (! ExpandEnvironmentStrings ( lfn
, buf
, PATH_MAX
)) {
1345 if ( access ( fn
, R_OK
) == 0 ) {
1346 char * r
= pa_xstrdup ( fn
);
1351 if ( errno
!= ENOENT
) {
1352 pa_log_warn ( "Failed to access configuration file '%s': %s" , fn
, pa_cstrerror ( errno
));
1362 if (! ExpandEnvironmentStrings ( global
, buf
, PATH_MAX
))
1367 if ( access ( fn
, R_OK
) == 0 )
1368 return pa_xstrdup ( global
);
1375 /* Format the specified data as a hexademical string */
1376 char * pa_hexstr ( const uint8_t * d
, size_t dlength
, char * s
, size_t slength
) {
1377 size_t i
= 0 , j
= 0 ;
1378 const char hex
[] = "0123456789abcdef" ;
1382 pa_assert ( slength
> 0 );
1384 while ( i
< dlength
&& j
+ 3 <= slength
) {
1385 s
[ j
++] = hex
[* d
>> 4 ];
1386 s
[ j
++] = hex
[* d
& 0xF ];
1392 s
[ j
< slength
? j
: slength
] = 0 ;
1396 /* Convert a hexadecimal digit to a number or -1 if invalid */
1397 static int hexc ( char c
) {
1398 if ( c
>= '0' && c
<= '9' )
1401 if ( c
>= 'A' && c
<= 'F' )
1402 return c
- 'A' + 10 ;
1404 if ( c
>= 'a' && c
<= 'f' )
1405 return c
- 'a' + 10 ;
1410 /* Parse a hexadecimal string as created by pa_hexstr() to a BLOB */
1411 size_t pa_parsehex ( const char * p
, uint8_t * d
, size_t dlength
) {
1417 while ( j
< dlength
&& * p
) {
1420 if (( b
= hexc (*( p
++))) < 0 )
1423 d
[ j
] = ( uint8_t ) ( b
<< 4 );
1428 if (( b
= hexc (*( p
++))) < 0 )
1431 d
[ j
] |= ( uint8_t ) b
;
1438 /* Returns nonzero when *s starts with *pfx */
1439 pa_bool_t
pa_startswith ( const char * s
, const char * pfx
) {
1447 return strlen ( s
) >= l
&& strncmp ( s
, pfx
, l
) == 0 ;
1450 /* Returns nonzero when *s ends with *sfx */
1451 pa_bool_t
pa_endswith ( const char * s
, const char * sfx
) {
1460 return l1
>= l2
&& strcmp ( s
+ l1
- l2
, sfx
) == 0 ;
1463 pa_bool_t
pa_is_path_absolute ( const char * fn
) {
1469 return strlen ( fn
) >= 3 && isalpha ( fn
[ 0 ]) && fn
[ 1 ] == ':' && fn
[ 2 ] == ' \\ ' ;
1473 char * pa_make_path_absolute ( const char * p
) {
1479 if ( pa_is_path_absolute ( p
))
1480 return pa_xstrdup ( p
);
1482 if (!( cwd
= pa_getcwd ()))
1483 return pa_xstrdup ( p
);
1485 r
= pa_sprintf_malloc ( "%s" PA_PATH_SEP
"%s" , cwd
, p
);
1490 /* if fn is null return the PulseAudio run time path in s (~/.pulse)
1491 * if fn is non-null and starts with / return fn
1492 * otherwise append fn to the run time path and return it */
1493 static char * get_path ( const char * fn
, pa_bool_t rt
) {
1496 if ( pa_is_path_absolute ( fn
))
1497 return pa_xstrdup ( fn
);
1499 rtp
= rt
? pa_get_runtime_dir () : pa_get_state_dir ();
1506 r
= pa_sprintf_malloc ( "%s" PA_PATH_SEP
"%s" , rtp
, fn
);
1513 char * pa_runtime_path ( const char * fn
) {
1514 return get_path ( fn
, 1 );
1517 char * pa_state_path ( const char * fn
) {
1518 return get_path ( fn
, 0 );
1521 /* Convert the string s to a signed integer in *ret_i */
1522 int pa_atoi ( const char * s
, int32_t * ret_i
) {
1530 l
= strtol ( s
, & x
, 0 );
1532 if (! x
|| * x
|| errno
!= 0 )
1535 if (( int32_t ) l
!= l
)
1538 * ret_i
= ( int32_t ) l
;
1543 /* Convert the string s to an unsigned integer in *ret_u */
1544 int pa_atou ( const char * s
, uint32_t * ret_u
) {
1552 l
= strtoul ( s
, & x
, 0 );
1554 if (! x
|| * x
|| errno
!= 0 )
1557 if (( uint32_t ) l
!= l
)
1560 * ret_u
= ( uint32_t ) l
;
1565 #ifdef HAVE_STRTOF_L
1566 static locale_t c_locale
= NULL
;
1568 static void c_locale_destroy ( void ) {
1569 freelocale ( c_locale
);
1573 int pa_atod ( const char * s
, double * ret_d
) {
1581 /* This should be locale independent */
1583 #ifdef HAVE_STRTOF_L
1587 if (( c_locale
= newlocale ( LC_ALL_MASK
, "C" , NULL
)))
1588 atexit ( c_locale_destroy
);
1594 f
= strtod_l ( s
, & x
, c_locale
);
1602 if (! x
|| * x
|| errno
!= 0 )
1610 /* Same as snprintf, but guarantees NUL-termination on every platform */
1611 int pa_snprintf ( char * str
, size_t size
, const char * format
, ...) {
1616 pa_assert ( size
> 0 );
1619 va_start ( ap
, format
);
1620 ret
= pa_vsnprintf ( str
, size
, format
, ap
);
1626 /* Same as vsnprintf, but guarantees NUL-termination on every platform */
1627 int pa_vsnprintf ( char * str
, size_t size
, const char * format
, va_list ap
) {
1631 pa_assert ( size
> 0 );
1634 ret
= vsnprintf ( str
, size
, format
, ap
);
1641 return PA_MIN (( int ) size
- 1 , ret
);
1644 /* Truncate the specified string, but guarantee that the string
1645 * returned still validates as UTF8 */
1646 char * pa_truncate_utf8 ( char * c
, size_t l
) {
1648 pa_assert ( pa_utf8_valid ( c
));
1655 while ( l
> 0 && ! pa_utf8_valid ( c
))
1661 char * pa_getcwd ( void ) {
1665 char * p
= pa_xnew ( char , l
);
1669 if ( errno
!= ERANGE
)
1677 void * pa_will_need ( const void * p
, size_t l
) {
1678 #ifdef RLIMIT_MEMLOCK
1689 a
= PA_PAGE_ALIGN_PTR ( p
);
1690 size
= ( const uint8_t *) p
+ l
- ( const uint8_t *) a
;
1692 #ifdef HAVE_POSIX_MADVISE
1693 if (( r
= posix_madvise (( void *) a
, size
, POSIX_MADV_WILLNEED
)) == 0 ) {
1694 pa_log_debug ( "posix_madvise() worked fine!" );
1699 /* Most likely the memory was not mmap()ed from a file and thus
1700 * madvise() didn't work, so let's misuse mlock() do page this
1701 * stuff back into RAM. Yeah, let's fuck with the MM! It's so
1702 * inviting, the man page of mlock() tells us: "All pages that
1703 * contain a part of the specified address range are guaranteed to
1704 * be resident in RAM when the call returns successfully." */
1706 #ifdef RLIMIT_MEMLOCK
1707 pa_assert_se ( getrlimit ( RLIMIT_MEMLOCK
, & rlim
) == 0 );
1709 if ( rlim
. rlim_cur
< PA_PAGE_SIZE
) {
1710 pa_log_debug ( "posix_madvise() failed (or doesn't exist), resource limits don't allow mlock(), can't page in data: %s" , pa_cstrerror ( r
));
1714 bs
= PA_PAGE_ALIGN ( rlim
. rlim_cur
);
1716 bs
= PA_PAGE_SIZE
* 4 ;
1719 pa_log_debug ( "posix_madvise() failed (or doesn't exist), trying mlock(): %s" , pa_cstrerror ( r
));
1722 while ( size
> 0 && bs
> 0 ) {
1727 if ( mlock ( a
, bs
) < 0 ) {
1728 bs
= PA_PAGE_ALIGN ( bs
/ 2 );
1732 pa_assert_se ( munlock ( a
, bs
) == 0 );
1734 a
= ( const uint8_t *) a
+ bs
;
1740 pa_log_debug ( "mlock() failed too (or doesn't exist), giving up: %s" , pa_cstrerror ( errno
));
1742 pa_log_debug ( "mlock() worked fine!" );
1747 void pa_close_pipe ( int fds
[ 2 ]) {
1751 pa_assert_se ( pa_close ( fds
[ 0 ]) == 0 );
1754 pa_assert_se ( pa_close ( fds
[ 1 ]) == 0 );
1756 fds
[ 0 ] = fds
[ 1 ] = - 1 ;
1759 char * pa_readlink ( const char * p
) {
1766 c
= pa_xnew ( char , l
);
1768 if (( n
= readlink ( p
, c
, l
- 1 )) < 0 ) {
1773 if (( size_t ) n
< l
- 1 ) {
1783 int pa_close_all ( int except_fd
, ...) {
1788 va_start ( ap
, except_fd
);
1791 for ( n
= 1 ; va_arg ( ap
, int ) >= 0 ; n
++)
1796 p
= pa_xnew ( int , n
+ 1 );
1798 va_start ( ap
, except_fd
);
1801 if ( except_fd
>= 0 ) {
1805 while (( fd
= va_arg ( ap
, int )) >= 0 )
1812 r
= pa_close_allv ( p
);
1818 int pa_close_allv ( const int except_fds
[]) {
1827 if (( d
= opendir ( "/proc/self/fd" ))) {
1831 while (( de
= readdir ( d
))) {
1837 if ( de
-> d_name
[ 0 ] == '.' )
1841 l
= strtol ( de
-> d_name
, & e
, 10 );
1842 if ( errno
!= 0 || ! e
|| * e
) {
1850 if (( long ) fd
!= l
) {
1863 for ( i
= 0 ; except_fds
[ i
] >= 0 ; i
++)
1864 if ( except_fds
[ i
] == fd
) {
1872 if ( pa_close ( fd
) < 0 ) {
1873 saved_errno
= errno
;
1875 errno
= saved_errno
;
1887 if ( getrlimit ( RLIMIT_NOFILE
, & rl
) < 0 )
1890 for ( fd
= 3 ; fd
< ( int ) rl
. rlim_max
; fd
++) {
1895 for ( i
= 0 ; except_fds
[ i
] >= 0 ; i
++)
1896 if ( except_fds
[ i
] == fd
) {
1904 if ( pa_close ( fd
) < 0 && errno
!= EBADF
)
1911 int pa_unblock_sigs ( int except
, ...) {
1916 va_start ( ap
, except
);
1919 for ( n
= 1 ; va_arg ( ap
, int ) >= 0 ; n
++)
1924 p
= pa_xnew ( int , n
+ 1 );
1926 va_start ( ap
, except
);
1933 while (( sig
= va_arg ( ap
, int )) >= 0 )
1940 r
= pa_unblock_sigsv ( p
);
1946 int pa_unblock_sigsv ( const int except
[]) {
1950 if ( sigemptyset (& ss
) < 0 )
1953 for ( i
= 0 ; except
[ i
] > 0 ; i
++)
1954 if ( sigaddset (& ss
, except
[ i
]) < 0 )
1957 return sigprocmask ( SIG_SETMASK
, & ss
, NULL
);
1960 int pa_reset_sigs ( int except
, ...) {
1965 va_start ( ap
, except
);
1968 for ( n
= 1 ; va_arg ( ap
, int ) >= 0 ; n
++)
1973 p
= pa_xnew ( int , n
+ 1 );
1975 va_start ( ap
, except
);
1982 while (( sig
= va_arg ( ap
, int )) >= 0 )
1989 r
= pa_reset_sigsv ( p
);
1995 int pa_reset_sigsv ( const int except
[]) {
1998 for ( sig
= 1 ; sig
< _NSIG
; sig
++) {
1999 pa_bool_t reset
= TRUE
;
2010 for ( i
= 0 ; except
[ i
] > 0 ; i
++) {
2011 if ( sig
== except
[ i
]) {
2020 struct sigaction sa
;
2022 memset (& sa
, 0 , sizeof ( sa
));
2023 sa
. sa_handler
= SIG_DFL
;
2025 /* On Linux the first two RT signals are reserved by
2026 * glibc, and sigaction() will return EINVAL for them. */
2027 if (( sigaction ( sig
, & sa
, NULL
) < 0 ))
2028 if ( errno
!= EINVAL
)
2036 void pa_set_env ( const char * key
, const char * value
) {
2040 putenv ( pa_sprintf_malloc ( "%s=%s" , key
, value
));
2043 pa_bool_t
pa_in_system_mode ( void ) {
2046 if (!( e
= getenv ( "PULSE_SYSTEM" )))