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