2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * See http://www.asterisk.org for more information about
7 * the Asterisk project. Please do not directly contact
8 * any of the maintainers of this project for assistance;
9 * the project provides a web site, mailing lists and IRC
10 * channels for your use.
12 * This program is free software, distributed under the terms of
13 * the GNU General Public License Version 2. See the LICENSE file
14 * at the top of the source tree.
19 * \brief Utility functions
21 * \note These are important for portability and security,
22 * so please use them in favour of other routines.
23 * Please consult the CODING GUIDELINES for more information.
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33 #ifdef HAVE_DEV_URANDOM
37 #include "asterisk/network.h"
39 #define AST_API_MODULE /* ensure that inlinable API functions will be built in lock.h if required */
40 #include "asterisk/lock.h"
41 #include "asterisk/io.h"
42 #include "asterisk/md5.h"
43 #include "asterisk/sha1.h"
44 #include "asterisk/cli.h"
45 #include "asterisk/linkedlists.h"
47 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
48 #include "asterisk/strings.h"
50 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
51 #include "asterisk/time.h"
53 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
54 #include "asterisk/stringfields.h"
56 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
57 #include "asterisk/utils.h"
59 #define AST_API_MODULE
60 #include "asterisk/threadstorage.h"
62 static char base64[64];
65 AST_THREADSTORAGE(inet_ntoa_buf);
67 #if !defined(HAVE_GETHOSTBYNAME_R_5) && !defined(HAVE_GETHOSTBYNAME_R_6)
69 #define ERANGE 34 /*!< duh? ERANGE value copied from web... */
72 AST_MUTEX_DEFINE_STATIC(__mutex);
74 /*! \brief Reentrant replacement for gethostbyname for BSD-based systems.
76 routine is derived from code originally written and placed in the public
77 domain by Enzo Michelangeli <em@em.no-ip.com> */
79 static int gethostbyname_r (const char *name, struct hostent *ret, char *buf,
80 size_t buflen, struct hostent **result,
85 ast_mutex_lock(&__mutex); /* begin critical area */
88 ph = gethostbyname(name);
89 *h_errnop = h_errno; /* copy h_errno to *h_herrnop */
96 int naddr=0, naliases=0;
97 /* determine if we have enough space in buf */
99 /* count how many addresses */
100 for (p = ph->h_addr_list; *p != 0; p++) {
101 nbytes += ph->h_length; /* addresses */
102 nbytes += sizeof(*p); /* pointers */
105 nbytes += sizeof(*p); /* one more for the terminating NULL */
107 /* count how many aliases, and total length of strings */
108 for (p = ph->h_aliases; *p != 0; p++) {
109 nbytes += (strlen(*p)+1); /* aliases */
110 nbytes += sizeof(*p); /* pointers */
113 nbytes += sizeof(*p); /* one more for the terminating NULL */
115 /* here nbytes is the number of bytes required in buffer */
116 /* as a terminator must be there, the minimum value is ph->h_length */
117 if (nbytes > buflen) {
119 ast_mutex_unlock(&__mutex); /* end critical area */
120 return ERANGE; /* not enough space in buf!! */
123 /* There is enough space. Now we need to do a deep copy! */
124 /* Allocation in buffer:
125 from [0] to [(naddr-1) * sizeof(*p)]:
126 pointers to addresses
127 at [naddr * sizeof(*p)]:
129 from [(naddr+1) * sizeof(*p)] to [(naddr+naliases) * sizeof(*p)] :
131 at [(naddr+naliases+1) * sizeof(*p)]:
133 then naddr addresses (fixed length), and naliases aliases (asciiz).
136 *ret = *ph; /* copy whole structure (not its address!) */
139 q = (char **)buf; /* pointer to pointers area (type: char **) */
140 ret->h_addr_list = q; /* update pointer to address list */
141 pbuf = buf + ((naddr + naliases + 2) * sizeof(*p)); /* skip that area */
142 for (p = ph->h_addr_list; *p != 0; p++) {
143 memcpy(pbuf, *p, ph->h_length); /* copy address bytes */
144 *q++ = pbuf; /* the pointer is the one inside buf... */
145 pbuf += ph->h_length; /* advance pbuf */
147 *q++ = NULL; /* address list terminator */
150 ret->h_aliases = q; /* update pointer to aliases list */
151 for (p = ph->h_aliases; *p != 0; p++) {
152 strcpy(pbuf, *p); /* copy alias strings */
153 *q++ = pbuf; /* the pointer is the one inside buf... */
154 pbuf += strlen(*p); /* advance pbuf */
155 *pbuf++ = 0; /* string terminator */
157 *q++ = NULL; /* terminator */
159 strcpy(pbuf, ph->h_name); /* copy alias strings */
161 pbuf += strlen(ph->h_name); /* advance pbuf */
162 *pbuf++ = 0; /* string terminator */
164 *result = ret; /* and let *result point to structure */
167 h_errno = hsave; /* restore h_errno */
168 ast_mutex_unlock(&__mutex); /* end critical area */
170 return (*result == NULL); /* return 0 on success, non-zero on error */
176 /*! \brief Re-entrant (thread safe) version of gethostbyname that replaces the
177 standard gethostbyname (which is not thread safe)
179 struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp)
185 struct hostent *result = NULL;
186 /* Although it is perfectly legitimate to lookup a pure integer, for
187 the sake of the sanity of people who like to name their peers as
188 integers, we break with tradition and refuse to look up a
195 else if (!isdigit(*s))
200 /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
203 memset(hp, 0, sizeof(struct ast_hostent));
204 hp->hp.h_addrtype = AF_INET;
205 hp->hp.h_addr_list = (void *) hp->buf;
206 hp->hp.h_addr = hp->buf + sizeof(void *);
207 if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
212 #ifdef HAVE_GETHOSTBYNAME_R_5
213 result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);
215 if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
218 res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
220 if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
228 AST_MUTEX_DEFINE_STATIC(test_lock);
229 AST_MUTEX_DEFINE_STATIC(test_lock2);
230 static pthread_t test_thread;
231 static int lock_count = 0;
232 static int test_errors = 0;
234 /*! \brief This is a regression test for recursive mutexes.
235 test_for_thread_safety() will return 0 if recursive mutex locks are
236 working properly, and non-zero if they are not working properly. */
237 static void *test_thread_body(void *data)
239 ast_mutex_lock(&test_lock);
241 if (lock_count != 10)
243 ast_mutex_lock(&test_lock);
245 if (lock_count != 20)
247 ast_mutex_lock(&test_lock2);
248 ast_mutex_unlock(&test_lock);
250 if (lock_count != 10)
252 ast_mutex_unlock(&test_lock);
254 ast_mutex_unlock(&test_lock2);
260 int test_for_thread_safety(void)
262 ast_mutex_lock(&test_lock2);
263 ast_mutex_lock(&test_lock);
265 ast_mutex_lock(&test_lock);
267 ast_pthread_create(&test_thread, NULL, test_thread_body, NULL);
271 ast_mutex_unlock(&test_lock);
276 ast_mutex_unlock(&test_lock);
280 ast_mutex_unlock(&test_lock2);
284 pthread_join(test_thread, NULL);
285 return(test_errors); /* return 0 on success. */
288 /*! \brief Produce 32 char MD5 hash of value. */
289 void ast_md5_hash(char *output, char *input)
291 struct MD5Context md5;
292 unsigned char digest[16];
297 MD5Update(&md5, (unsigned char *)input, strlen(input));
298 MD5Final(digest, &md5);
300 for (x = 0; x < 16; x++)
301 ptr += sprintf(ptr, "%2.2x", digest[x]);
304 /*! \brief Produce 40 char SHA1 hash of value. */
305 void ast_sha1_hash(char *output, char *input)
307 struct SHA1Context sha;
310 uint8_t Message_Digest[20];
314 SHA1Input(&sha, (const unsigned char *) input, strlen(input));
316 SHA1Result(&sha, Message_Digest);
318 for (x = 0; x < 20; x++)
319 ptr += sprintf(ptr, "%2.2x", Message_Digest[x]);
322 /*! \brief decode BASE64 encoded text */
323 int ast_base64decode(unsigned char *dst, const char *src, int max)
326 unsigned int byte = 0;
327 unsigned int bits = 0;
329 while (*src && (cnt < max)) {
330 /* Shift in 6 bits of input */
332 byte |= (b2a[(int)(*src)]) & 0x3f;
336 /* If we have at least 8 bits left over, take that character
340 *dst = (byte >> bits) & 0xff;
345 /* Dont worry about left over bits, they're extra anyway */
349 /*! \brief encode text to BASE64 coding */
350 int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
354 unsigned int byte = 0;
357 /* Reserve space for null byte at end of string */
359 while ((cntin < srclen) && (cnt < max)) {
364 if ((bits == 24) && (cnt + 4 <= max)) {
365 *dst++ = base64[(byte >> 18) & 0x3f];
366 *dst++ = base64[(byte >> 12) & 0x3f];
367 *dst++ = base64[(byte >> 6) & 0x3f];
368 *dst++ = base64[byte & 0x3f];
374 if (linebreaks && (cnt < max) && (col == 64)) {
380 if (bits && (cnt + 4 <= max)) {
381 /* Add one last character for the remaining bits,
382 padding the rest with 0 */
384 *dst++ = base64[(byte >> 18) & 0x3f];
385 *dst++ = base64[(byte >> 12) & 0x3f];
387 *dst++ = base64[(byte >> 6) & 0x3f];
393 if (linebreaks && (cnt < max)) {
401 int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
403 return ast_base64encode_full(dst, src, srclen, max, 0);
406 static void base64_init(void)
409 memset(b2a, -1, sizeof(b2a));
410 /* Initialize base-64 Conversion table */
411 for (x = 0; x < 26; x++) {
416 base64[x + 26] = 'a' + x;
417 b2a['a' + x] = x + 26;
420 base64[x + 52] = '0' + x;
421 b2a['0' + x] = x + 52;
430 /*! \brief ast_uri_encode: Turn text string to URI-encoded %XX version
431 \note At this point, we're converting from ISO-8859-x (8-bit), not UTF8
432 as in the SIP protocol spec
433 If doreserved == 1 we will convert reserved characters also.
434 RFC 2396, section 2.4
435 outbuf needs to have more memory allocated than the instring
436 to have room for the expansion. Every char that is converted
437 is replaced by three ASCII characters.
439 Note: The doreserved option is needed for replaces header in
442 char *ast_uri_encode(const char *string, char *outbuf, int buflen, int doreserved)
444 char *reserved = ";/?:@&=+$, "; /* Reserved chars */
446 const char *ptr = string; /* Start with the string */
450 ast_copy_string(outbuf, string, buflen);
452 /* If there's no characters to convert, just go through and don't do anything */
454 if (((unsigned char) *ptr) > 127 || (doreserved && strchr(reserved, *ptr)) ) {
455 /* Oops, we need to start working here */
458 out = buf + (ptr - string) ; /* Set output ptr */
460 out += sprintf(out, "%%%02x", (unsigned char) *ptr);
462 *out = *ptr; /* Continue copying the string */
472 /*! \brief ast_uri_decode: Decode SIP URI, URN, URL (overwrite the string) */
473 void ast_uri_decode(char *s)
478 for (o = s; *s; s++, o++) {
479 if (*s == '%' && strlen(s) > 2 && sscanf(s + 1, "%2x", &tmp) == 1) {
480 /* have '%', two chars and correct parsing */
482 s += 2; /* Will be incremented once more when we break out */
483 } else /* all other cases, just copy */
489 /*! \brief ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa */
490 const char *ast_inet_ntoa(struct in_addr ia)
494 if (!(buf = ast_threadstorage_get(&inet_ntoa_buf, INET_ADDRSTRLEN)))
497 return inet_ntop(AF_INET, &ia, buf, INET_ADDRSTRLEN);
500 #ifdef HAVE_DEV_URANDOM
501 static int dev_urandom_fd;
505 #undef pthread_create /* For ast_pthread_create function only */
506 #endif /* !__linux__ */
508 #if !defined(LOW_MEMORY)
512 /*! \brief A reasonable maximum number of locks a thread would be holding ... */
513 #define AST_MAX_LOCKS 32
515 /* Allow direct use of pthread_mutex_t and friends */
516 #undef pthread_mutex_t
517 #undef pthread_mutex_lock
518 #undef pthread_mutex_unlock
519 #undef pthread_mutex_init
520 #undef pthread_mutex_destroy
523 * \brief Keep track of which locks a thread holds
525 * There is an instance of this struct for every active thread
527 struct thr_lock_info {
528 /*! The thread's ID */
530 /*! The thread name which includes where the thread was started */
531 const char *thread_name;
532 /*! This is the actual container of info for what locks this thread holds */
537 const char *lock_name;
540 enum ast_lock_type type;
541 /*! This thread is waiting on this lock */
543 } locks[AST_MAX_LOCKS];
544 /*! This is the number of locks currently held by this thread.
545 * The index (num_locks - 1) has the info on the last one in the
547 unsigned int num_locks;
548 /*! Protects the contents of the locks member
549 * Intentionally not ast_mutex_t */
550 pthread_mutex_t lock;
551 AST_LIST_ENTRY(thr_lock_info) entry;
555 * \brief Locked when accessing the lock_infos list
557 AST_MUTEX_DEFINE_STATIC(lock_infos_lock);
559 * \brief A list of each thread's lock info
561 static AST_LIST_HEAD_NOLOCK_STATIC(lock_infos, thr_lock_info);
564 * \brief Destroy a thread's lock info
566 * This gets called automatically when the thread stops
568 static void lock_info_destroy(void *data)
570 struct thr_lock_info *lock_info = data;
572 pthread_mutex_lock(&lock_infos_lock.mutex);
573 AST_LIST_REMOVE(&lock_infos, lock_info, entry);
574 pthread_mutex_unlock(&lock_infos_lock.mutex);
576 pthread_mutex_destroy(&lock_info->lock);
577 if (lock_info->thread_name)
578 free((void *) lock_info->thread_name);
583 * \brief The thread storage key for per-thread lock info
585 AST_THREADSTORAGE_CUSTOM(thread_lock_info, NULL, lock_info_destroy);
587 void ast_store_lock_info(enum ast_lock_type type, const char *filename,
588 int line_num, const char *func, const char *lock_name, void *lock_addr)
590 struct thr_lock_info *lock_info;
593 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
596 pthread_mutex_lock(&lock_info->lock);
598 for (i = 0; i < lock_info->num_locks; i++) {
599 if (lock_info->locks[i].lock_addr == lock_addr) {
600 lock_info->locks[i].times_locked++;
601 pthread_mutex_unlock(&lock_info->lock);
606 if (lock_info->num_locks == AST_MAX_LOCKS) {
607 /* Can't use ast_log here, because it will cause infinite recursion */
608 fprintf(stderr, "XXX ERROR XXX A thread holds more locks than '%d'."
609 " Increase AST_MAX_LOCKS!\n", AST_MAX_LOCKS);
610 pthread_mutex_unlock(&lock_info->lock);
614 lock_info->locks[i].file = filename;
615 lock_info->locks[i].line_num = line_num;
616 lock_info->locks[i].func = func;
617 lock_info->locks[i].lock_name = lock_name;
618 lock_info->locks[i].lock_addr = lock_addr;
619 lock_info->locks[i].times_locked = 1;
620 lock_info->locks[i].type = type;
621 lock_info->locks[i].pending = 1;
622 lock_info->num_locks++;
624 pthread_mutex_unlock(&lock_info->lock);
627 void ast_mark_lock_acquired(void)
629 struct thr_lock_info *lock_info;
631 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
634 pthread_mutex_lock(&lock_info->lock);
635 lock_info->locks[lock_info->num_locks - 1].pending = 0;
636 pthread_mutex_unlock(&lock_info->lock);
639 void ast_mark_lock_failed(void)
641 struct thr_lock_info *lock_info;
643 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
646 pthread_mutex_lock(&lock_info->lock);
647 lock_info->locks[lock_info->num_locks - 1].pending = -1;
648 lock_info->locks[lock_info->num_locks - 1].times_locked--;
649 pthread_mutex_unlock(&lock_info->lock);
652 void ast_remove_lock_info(void *lock_addr)
654 struct thr_lock_info *lock_info;
657 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
660 pthread_mutex_lock(&lock_info->lock);
662 for (i = lock_info->num_locks - 1; i >= 0; i--) {
663 if (lock_info->locks[i].lock_addr == lock_addr)
668 /* Lock not found :( */
669 pthread_mutex_unlock(&lock_info->lock);
673 if (lock_info->locks[i].times_locked > 1) {
674 lock_info->locks[i].times_locked--;
675 pthread_mutex_unlock(&lock_info->lock);
679 if (i < lock_info->num_locks - 1) {
680 /* Not the last one ... *should* be rare! */
681 memmove(&lock_info->locks[i], &lock_info->locks[i + 1],
682 (lock_info->num_locks - (i + 1)) * sizeof(lock_info->locks[0]));
685 lock_info->num_locks--;
687 pthread_mutex_unlock(&lock_info->lock);
690 static const char *locktype2str(enum ast_lock_type type)
704 static char *handle_show_locks(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
706 struct thr_lock_info *lock_info;
709 if (!(str = ast_str_create(4096)))
714 e->command = "core show locks";
716 "Usage: core show locks\n"
717 " This command is for lock debugging. It prints out which locks\n"
718 "are owned by each active thread.\n";
725 ast_str_append(&str, 0, "\n"
726 "=======================================================================\n"
727 "=== Currently Held Locks ==============================================\n"
728 "=======================================================================\n"
730 "=== <file> <line num> <function> <lock name> <lock addr> (times locked)\n"
736 pthread_mutex_lock(&lock_infos_lock.mutex);
737 AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
739 ast_str_append(&str, 0, "=== Thread ID: %d (%s)\n", (int) lock_info->thread_id,
740 lock_info->thread_name);
741 pthread_mutex_lock(&lock_info->lock);
742 for (i = 0; str && i < lock_info->num_locks; i++) {
746 ast_str_append(&str, 0, "=== ---> %sLock #%d (%s): %s %d %s %s %p (%d)\n",
747 lock_info->locks[i].pending > 0 ? "Waiting for " :
748 lock_info->locks[i].pending < 0 ? "Tried and failed to get " : "", i,
749 lock_info->locks[i].file,
750 locktype2str(lock_info->locks[i].type),
751 lock_info->locks[i].line_num,
752 lock_info->locks[i].func, lock_info->locks[i].lock_name,
753 lock_info->locks[i].lock_addr,
754 lock_info->locks[i].times_locked);
756 if (!lock_info->locks[i].pending)
759 /* We only have further details for mutexes right now */
760 if (lock_info->locks[i].type != AST_MUTEX)
763 lock = lock_info->locks[i].lock_addr;
765 ast_reentrancy_lock(lock);
766 for (j = 0; str && j < lock->reentrancy; j++) {
767 ast_str_append(&str, 0, "=== --- ---> Locked Here: %s line %d (%s)\n",
768 lock->file[j], lock->lineno[j], lock->func[j]);
770 ast_reentrancy_unlock(lock);
772 pthread_mutex_unlock(&lock_info->lock);
775 ast_str_append(&str, 0, "=== -------------------------------------------------------------------\n"
780 pthread_mutex_unlock(&lock_infos_lock.mutex);
785 ast_str_append(&str, 0, "=======================================================================\n"
791 ast_cli(a->fd, "%s", str->str);
798 static struct ast_cli_entry utils_cli[] = {
799 AST_CLI_DEFINE(handle_show_locks, "Show which locks are held by which thread"),
802 #endif /* DEBUG_THREADS */
805 * support for 'show threads'. The start routine is wrapped by
806 * dummy_start(), so that ast_register_thread() and
807 * ast_unregister_thread() know the thread identifier.
810 void *(*start_routine)(void *);
816 * on OS/X, pthread_cleanup_push() and pthread_cleanup_pop()
817 * are odd macros which start and end a block, so they _must_ be
818 * used in pairs (the latter with a '1' argument to call the
820 * On BSD we don't need this, but we keep it for compatibility.
822 static void *dummy_start(void *data)
825 struct thr_arg a = *((struct thr_arg *) data); /* make a local copy */
827 struct thr_lock_info *lock_info;
828 pthread_mutexattr_t mutex_attr;
831 /* note that even though data->name is a pointer to allocated memory,
832 we are not freeing it here because ast_register_thread is going to
833 keep a copy of the pointer and then ast_unregister_thread will
837 ast_register_thread(a.name);
838 pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
841 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
844 lock_info->thread_id = pthread_self();
845 lock_info->thread_name = strdup(a.name);
847 pthread_mutexattr_init(&mutex_attr);
848 pthread_mutexattr_settype(&mutex_attr, AST_MUTEX_KIND);
849 pthread_mutex_init(&lock_info->lock, &mutex_attr);
850 pthread_mutexattr_destroy(&mutex_attr);
852 pthread_mutex_lock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
853 AST_LIST_INSERT_TAIL(&lock_infos, lock_info, entry);
854 pthread_mutex_unlock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
855 #endif /* DEBUG_THREADS */
857 ret = a.start_routine(a.data);
859 pthread_cleanup_pop(1);
864 #endif /* !LOW_MEMORY */
866 int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
867 void *data, size_t stacksize, const char *file, const char *caller,
868 int line, const char *start_fn)
870 #if !defined(LOW_MEMORY)
875 attr = alloca(sizeof(*attr));
876 pthread_attr_init(attr);
880 /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
881 which is kind of useless. Change this here to
882 PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
883 priority will propagate down to new threads by default.
884 This does mean that callers cannot set a different priority using
885 PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
886 the priority afterwards with pthread_setschedparam(). */
887 if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
888 ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
892 stacksize = AST_STACKSIZE;
894 if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
895 ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
897 #if !defined(LOW_MEMORY)
898 if ((a = ast_malloc(sizeof(*a)))) {
899 a->start_routine = start_routine;
901 start_routine = dummy_start;
902 asprintf(&a->name, "%-20s started at [%5d] %s %s()",
903 start_fn, line, file, caller);
906 #endif /* !LOW_MEMORY */
908 return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
912 int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
913 void *data, size_t stacksize, const char *file, const char *caller,
914 int line, const char *start_fn)
916 unsigned char attr_destroy = 0;
920 attr = alloca(sizeof(*attr));
921 pthread_attr_init(attr);
925 if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
926 ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
928 res = ast_pthread_create_stack(thread, attr, start_routine, data,
929 stacksize, file, caller, line, start_fn);
932 pthread_attr_destroy(attr);
937 int ast_wait_for_input(int fd, int ms)
939 struct pollfd pfd[1];
940 memset(pfd, 0, sizeof(pfd));
942 pfd[0].events = POLLIN|POLLPRI;
943 return poll(pfd, 1, ms);
947 * Try to write string, but wait no more than ms milliseconds before timing out.
949 * \note The code assumes that the file descriptor has NONBLOCK set,
950 * so there is only one system call made to do a write, unless we actually
951 * have a need to wait. This way, we get better performance.
952 * If the descriptor is blocking, all assumptions on the guaranteed
953 * detail do not apply anymore.
954 * Also note that in the current implementation, the delay is per-write,
955 * so you still have no guarantees, anyways.
956 * Fortunately the routine is only used in a few places (cli.c, manager.c,
957 * res_agi.c) so it is reasonably easy to check how it behaves there.
959 * XXX We either need to fix the code, or fix the documentation.
961 int ast_carefulwrite(int fd, char *s, int len, int timeoutms)
963 /* Try to write string, but wait no more than ms milliseconds
966 struct pollfd fds[1];
968 res = write(fd, s, len);
969 if ((res < 0) && (errno != EAGAIN)) {
979 fds[0].events = POLLOUT;
980 /* Wait until writable again */
981 res = poll(fds, 1, timeoutms);
989 char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
995 if ((q = strchr(beg_quotes, *s)) && *q != '\0') {
996 e = s + strlen(s) - 1;
997 if (*e == *(end_quotes + (q - beg_quotes))) {
1006 char *ast_unescape_semicolon(char *s)
1011 while ((e = strchr(work, ';'))) {
1012 if ((e > work) && (*(e-1) == '\\')) {
1013 memmove(e - 1, e, strlen(e) + 1);
1023 int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap)
1027 if (!buffer || !*buffer || !space || !*space)
1030 result = vsnprintf(*buffer, *space, fmt, ap);
1034 else if (result > *space)
1042 int ast_build_string(char **buffer, size_t *space, const char *fmt, ...)
1048 result = ast_build_string_va(buffer, space, fmt, ap);
1054 int ast_true(const char *s)
1056 if (ast_strlen_zero(s))
1059 /* Determine if this is a true value */
1060 if (!strcasecmp(s, "yes") ||
1061 !strcasecmp(s, "true") ||
1062 !strcasecmp(s, "y") ||
1063 !strcasecmp(s, "t") ||
1064 !strcasecmp(s, "1") ||
1065 !strcasecmp(s, "on"))
1071 int ast_false(const char *s)
1073 if (ast_strlen_zero(s))
1076 /* Determine if this is a false value */
1077 if (!strcasecmp(s, "no") ||
1078 !strcasecmp(s, "false") ||
1079 !strcasecmp(s, "n") ||
1080 !strcasecmp(s, "f") ||
1081 !strcasecmp(s, "0") ||
1082 !strcasecmp(s, "off"))
1088 #define ONE_MILLION 1000000
1090 * put timeval in a valid range. usec is 0..999999
1091 * negative values are not allowed and truncated.
1093 static struct timeval tvfix(struct timeval a)
1095 if (a.tv_usec >= ONE_MILLION) {
1096 ast_log(LOG_WARNING, "warning too large timestamp %ld.%ld\n",
1097 a.tv_sec, (long int) a.tv_usec);
1098 a.tv_sec += a.tv_usec / ONE_MILLION;
1099 a.tv_usec %= ONE_MILLION;
1100 } else if (a.tv_usec < 0) {
1101 ast_log(LOG_WARNING, "warning negative timestamp %ld.%ld\n",
1102 a.tv_sec, (long int) a.tv_usec);
1108 struct timeval ast_tvadd(struct timeval a, struct timeval b)
1110 /* consistency checks to guarantee usec in 0..999999 */
1113 a.tv_sec += b.tv_sec;
1114 a.tv_usec += b.tv_usec;
1115 if (a.tv_usec >= ONE_MILLION) {
1117 a.tv_usec -= ONE_MILLION;
1122 struct timeval ast_tvsub(struct timeval a, struct timeval b)
1124 /* consistency checks to guarantee usec in 0..999999 */
1127 a.tv_sec -= b.tv_sec;
1128 a.tv_usec -= b.tv_usec;
1129 if (a.tv_usec < 0) {
1131 a.tv_usec += ONE_MILLION;
1137 /*! \brief glibc puts a lock inside random(3), so that the results are thread-safe.
1138 * BSD libc (and others) do not. */
1141 AST_MUTEX_DEFINE_STATIC(randomlock);
1144 long int ast_random(void)
1147 #ifdef HAVE_DEV_URANDOM
1148 if (dev_urandom_fd >= 0) {
1149 int read_res = read(dev_urandom_fd, &res, sizeof(res));
1151 long int rm = RAND_MAX;
1152 res = res < 0 ? ~res : res;
1161 ast_mutex_lock(&randomlock);
1163 ast_mutex_unlock(&randomlock);
1168 char *ast_process_quotes_and_slashes(char *start, char find, char replace_with)
1170 char *dataPut = start;
1174 for (; *start; start++) {
1176 *dataPut++ = *start; /* Always goes verbatim */
1179 if (*start == '\\') {
1180 inEscape = 1; /* Do not copy \ into the data */
1181 } else if (*start == '\'') {
1182 inQuotes = 1 - inQuotes; /* Do not copy ' into the data */
1184 /* Replace , with |, unless in quotes */
1185 *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
1189 if (start != dataPut)
1194 void ast_join(char *s, size_t len, char * const w[])
1199 /* Join words into a string */
1202 for (x = 0; ofs < len && w[x]; x++) {
1205 for (src = w[x]; *src && ofs < len; src++)
1214 * stringfields support routines.
1217 const char __ast_string_field_empty[] = ""; /*!< the empty string */
1219 /*! \brief add a new block to the pool.
1220 * We can only allocate from the topmost pool, so the
1221 * fields in *mgr reflect the size of that only.
1223 static int add_string_pool(struct ast_string_field_mgr *mgr,
1224 struct ast_string_field_pool **pool_head, size_t size)
1226 struct ast_string_field_pool *pool;
1228 if (!(pool = ast_calloc(1, sizeof(*pool) + size)))
1231 pool->prev = *pool_head;
1240 * This is an internal API, code should not use it directly.
1241 * It initializes all fields as empty, then uses 'size' for 3 functions:
1242 * size > 0 means initialize the pool list with a pool of given size.
1243 * This must be called right after allocating the object.
1244 * size = 0 means release all pools except the most recent one.
1245 * This is useful to e.g. reset an object to the initial value.
1246 * size < 0 means release all pools.
1247 * This must be done before destroying the object.
1249 int __ast_string_field_init(struct ast_string_field_mgr *mgr,
1250 struct ast_string_field_pool **pool_head, int size)
1252 const char **p = (const char **)pool_head + 1;
1253 struct ast_string_field_pool *cur = *pool_head;
1255 /* clear fields - this is always necessary */
1256 while ((struct ast_string_field_mgr *)p != mgr)
1257 *p++ = __ast_string_field_empty;
1258 if (size > 0) { /* allocate the initial pool */
1260 return add_string_pool(mgr, pool_head, size);
1262 if (size < 0) { /* reset all pools */
1264 } else { /* preserve the first pool */
1266 ast_log(LOG_WARNING, "trying to reset empty pool\n");
1270 (*pool_head)->prev = NULL;
1274 struct ast_string_field_pool *prev = cur->prev;
1281 ast_string_field __ast_string_field_alloc_space(struct ast_string_field_mgr *mgr,
1282 struct ast_string_field_pool **pool_head, size_t needed)
1284 char *result = NULL;
1285 size_t space = mgr->size - mgr->used;
1287 if (__builtin_expect(needed > space, 0)) {
1288 size_t new_size = mgr->size * 2;
1290 while (new_size < needed)
1293 if (add_string_pool(mgr, pool_head, new_size))
1297 result = (*pool_head)->base + mgr->used;
1298 mgr->used += needed;
1302 void __ast_string_field_ptr_build_va(struct ast_string_field_mgr *mgr,
1303 struct ast_string_field_pool **pool_head,
1304 const ast_string_field *ptr, const char *format, va_list ap1, va_list ap2)
1307 char *dst = (*pool_head)->base + mgr->used;
1308 const char **p = (const char **)ptr;
1309 size_t space = mgr->size - mgr->used;
1311 /* try to write using available space */
1312 needed = vsnprintf(dst, space, format, ap1) + 1;
1316 if (needed > space) { /* if it fails, reallocate */
1317 size_t new_size = mgr->size * 2;
1319 while (new_size < needed)
1322 if (add_string_pool(mgr, pool_head, new_size))
1325 dst = (*pool_head)->base + mgr->used;
1326 vsprintf(dst, format, ap2);
1330 mgr->used += needed;
1333 void __ast_string_field_ptr_build(struct ast_string_field_mgr *mgr,
1334 struct ast_string_field_pool **pool_head,
1335 const ast_string_field *ptr, const char *format, ...)
1339 va_start(ap1, format);
1340 va_start(ap2, format); /* va_copy does not exist on FreeBSD */
1342 __ast_string_field_ptr_build_va(mgr, pool_head, ptr, format, ap1, ap2);
1347 /* end of stringfields support */
1349 AST_MUTEX_DEFINE_STATIC(fetchadd_m); /* used for all fetc&add ops */
1351 int ast_atomic_fetchadd_int_slow(volatile int *p, int v)
1354 ast_mutex_lock(&fetchadd_m);
1357 ast_mutex_unlock(&fetchadd_m);
1362 * get values from config variables.
1364 int ast_get_timeval(const char *src, struct timeval *dst, struct timeval _default, int *consumed)
1366 long double dtv = 0.0;
1374 if (ast_strlen_zero(src))
1377 /* only integer at the moment, but one day we could accept more formats */
1378 if (sscanf(src, "%Lf%n", &dtv, &scanned) > 0) {
1380 dst->tv_usec = (dtv - dst->tv_sec) * 1000000.0;
1382 *consumed = scanned;
1389 * get values from config variables.
1391 int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed)
1401 if (ast_strlen_zero(src))
1404 /* only integer at the moment, but one day we could accept more formats */
1405 if (sscanf(src, "%ld%n", &t, &scanned) == 1) {
1408 *consumed = scanned;
1415 * core handler for dynamic strings.
1416 * This is not meant to be called directly, but rather through the
1417 * various wrapper macros
1419 * ast_str_append(...)
1420 * ast_str_set_va(...)
1421 * ast_str_append_va(...)
1423 int __ast_str_helper(struct ast_str **buf, size_t max_len,
1424 int append, const char *fmt, va_list ap)
1427 int offset = (append && (*buf)->len) ? (*buf)->used : 0;
1430 max_len = (*buf)->len; /* don't exceed the allocated space */
1432 * Ask vsnprintf how much space we need. Remember that vsnprintf
1433 * does not count the final '\0' so we must add 1.
1435 res = vsnprintf((*buf)->str + offset, (*buf)->len - offset, fmt, ap);
1437 need = res + offset + 1;
1439 * If there is not enough space and we are below the max length,
1440 * reallocate the buffer and return a message telling to retry.
1442 if (need > (*buf)->len && (max_len == 0 || (*buf)->len < max_len) ) {
1443 if (max_len && max_len < need) /* truncate as needed */
1445 else if (max_len == 0) /* if unbounded, give more room for next time */
1446 need += 16 + need/4;
1447 if (0) /* debugging */
1448 ast_verbose("extend from %d to %d\n", (int)(*buf)->len, need);
1449 if (ast_str_make_space(buf, need)) {
1450 ast_verbose("failed to extend from %d to %d\n", (int)(*buf)->len, need);
1451 return AST_DYNSTR_BUILD_FAILED;
1453 (*buf)->str[offset] = '\0'; /* Truncate the partial write. */
1455 /* va_end() and va_start() must be done before calling
1456 * vsnprintf() again. */
1457 return AST_DYNSTR_BUILD_RETRY;
1459 /* update space used, keep in mind the truncation */
1460 (*buf)->used = (res + offset > (*buf)->len) ? (*buf)->len : res + offset;
1465 void ast_enable_packet_fragmentation(int sock)
1467 #if defined(HAVE_IP_MTU_DISCOVER)
1468 int val = IP_PMTUDISC_DONT;
1470 if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
1471 ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
1472 #endif /* HAVE_IP_MTU_DISCOVER */
1475 int ast_mkdir(const char *path, int mode)
1478 int len = strlen(path), count = 0, x, piececount = 0;
1479 char *tmp = ast_strdupa(path);
1481 char *fullpath = alloca(len + 1);
1484 for (ptr = tmp; *ptr; ptr++) {
1489 /* Count the components to the directory path */
1490 pieces = alloca(count * sizeof(*pieces));
1491 for (ptr = tmp; *ptr; ptr++) {
1494 pieces[piececount++] = ptr + 1;
1499 for (x = 0; x < piececount; x++) {
1500 /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
1501 strcat(fullpath, "/");
1502 strcat(fullpath, pieces[x]);
1503 res = mkdir(fullpath, mode);
1504 if (res && errno != EEXIST)
1510 int ast_utils_init(void)
1512 #ifdef HAVE_DEV_URANDOM
1513 dev_urandom_fd = open("/dev/urandom", O_RDONLY);
1516 #ifdef DEBUG_THREADS
1517 ast_cli_register_multiple(utils_cli, sizeof(utils_cli) / sizeof(utils_cli[0]));