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 ((*ptr < 32 || (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 64
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 if (i && lock_info->locks[i].pending == -1) {
615 /* The last lock on the list was one that this thread tried to lock but
616 * failed at doing so. It has now moved on to something else, so remove
617 * the old lock from the list. */
619 lock_info->num_locks--;
620 memset(&lock_info->locks[i], 0, sizeof(lock_info->locks[0]));
623 lock_info->locks[i].file = filename;
624 lock_info->locks[i].line_num = line_num;
625 lock_info->locks[i].func = func;
626 lock_info->locks[i].lock_name = lock_name;
627 lock_info->locks[i].lock_addr = lock_addr;
628 lock_info->locks[i].times_locked = 1;
629 lock_info->locks[i].type = type;
630 lock_info->locks[i].pending = 1;
631 lock_info->num_locks++;
633 pthread_mutex_unlock(&lock_info->lock);
636 void ast_mark_lock_acquired(void *lock_addr)
638 struct thr_lock_info *lock_info;
640 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
643 pthread_mutex_lock(&lock_info->lock);
644 if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
645 lock_info->locks[lock_info->num_locks - 1].pending = 0;
647 pthread_mutex_unlock(&lock_info->lock);
650 void ast_mark_lock_failed(void *lock_addr)
652 struct thr_lock_info *lock_info;
654 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
657 pthread_mutex_lock(&lock_info->lock);
658 if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
659 lock_info->locks[lock_info->num_locks - 1].pending = -1;
660 lock_info->locks[lock_info->num_locks - 1].times_locked--;
662 pthread_mutex_unlock(&lock_info->lock);
665 void ast_remove_lock_info(void *lock_addr)
667 struct thr_lock_info *lock_info;
670 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
673 pthread_mutex_lock(&lock_info->lock);
675 for (i = lock_info->num_locks - 1; i >= 0; i--) {
676 if (lock_info->locks[i].lock_addr == lock_addr)
681 /* Lock not found :( */
682 pthread_mutex_unlock(&lock_info->lock);
686 if (lock_info->locks[i].times_locked > 1) {
687 lock_info->locks[i].times_locked--;
688 pthread_mutex_unlock(&lock_info->lock);
692 if (i < lock_info->num_locks - 1) {
693 /* Not the last one ... *should* be rare! */
694 memmove(&lock_info->locks[i], &lock_info->locks[i + 1],
695 (lock_info->num_locks - (i + 1)) * sizeof(lock_info->locks[0]));
698 lock_info->num_locks--;
700 pthread_mutex_unlock(&lock_info->lock);
703 static const char *locktype2str(enum ast_lock_type type)
717 static char *handle_show_locks(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
719 struct thr_lock_info *lock_info;
722 if (!(str = ast_str_create(4096)))
727 e->command = "core show locks";
729 "Usage: core show locks\n"
730 " This command is for lock debugging. It prints out which locks\n"
731 "are owned by each active thread.\n";
738 ast_str_append(&str, 0, "\n"
739 "=======================================================================\n"
740 "=== Currently Held Locks ==============================================\n"
741 "=======================================================================\n"
743 "=== <file> <line num> <function> <lock name> <lock addr> (times locked)\n"
749 pthread_mutex_lock(&lock_infos_lock.mutex);
750 AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
752 ast_str_append(&str, 0, "=== Thread ID: %d (%s)\n", (int) lock_info->thread_id,
753 lock_info->thread_name);
754 pthread_mutex_lock(&lock_info->lock);
755 for (i = 0; str && i < lock_info->num_locks; i++) {
759 ast_str_append(&str, 0, "=== ---> %sLock #%d (%s): %s %d %s %s %p (%d)\n",
760 lock_info->locks[i].pending > 0 ? "Waiting for " :
761 lock_info->locks[i].pending < 0 ? "Tried and failed to get " : "", i,
762 lock_info->locks[i].file,
763 locktype2str(lock_info->locks[i].type),
764 lock_info->locks[i].line_num,
765 lock_info->locks[i].func, lock_info->locks[i].lock_name,
766 lock_info->locks[i].lock_addr,
767 lock_info->locks[i].times_locked);
769 if (!lock_info->locks[i].pending || lock_info->locks[i].pending == -1)
772 /* We only have further details for mutexes right now */
773 if (lock_info->locks[i].type != AST_MUTEX)
776 lock = lock_info->locks[i].lock_addr;
778 ast_reentrancy_lock(lock);
779 for (j = 0; str && j < lock->reentrancy; j++) {
780 ast_str_append(&str, 0, "=== --- ---> Locked Here: %s line %d (%s)\n",
781 lock->file[j], lock->lineno[j], lock->func[j]);
783 ast_reentrancy_unlock(lock);
785 pthread_mutex_unlock(&lock_info->lock);
788 ast_str_append(&str, 0, "=== -------------------------------------------------------------------\n"
793 pthread_mutex_unlock(&lock_infos_lock.mutex);
798 ast_str_append(&str, 0, "=======================================================================\n"
804 ast_cli(a->fd, "%s", str->str);
811 static struct ast_cli_entry utils_cli[] = {
812 AST_CLI_DEFINE(handle_show_locks, "Show which locks are held by which thread"),
815 #endif /* DEBUG_THREADS */
818 * support for 'show threads'. The start routine is wrapped by
819 * dummy_start(), so that ast_register_thread() and
820 * ast_unregister_thread() know the thread identifier.
823 void *(*start_routine)(void *);
829 * on OS/X, pthread_cleanup_push() and pthread_cleanup_pop()
830 * are odd macros which start and end a block, so they _must_ be
831 * used in pairs (the latter with a '1' argument to call the
833 * On BSD we don't need this, but we keep it for compatibility.
835 static void *dummy_start(void *data)
838 struct thr_arg a = *((struct thr_arg *) data); /* make a local copy */
840 struct thr_lock_info *lock_info;
841 pthread_mutexattr_t mutex_attr;
844 /* note that even though data->name is a pointer to allocated memory,
845 we are not freeing it here because ast_register_thread is going to
846 keep a copy of the pointer and then ast_unregister_thread will
850 ast_register_thread(a.name);
851 pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
854 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
857 lock_info->thread_id = pthread_self();
858 lock_info->thread_name = strdup(a.name);
860 pthread_mutexattr_init(&mutex_attr);
861 pthread_mutexattr_settype(&mutex_attr, AST_MUTEX_KIND);
862 pthread_mutex_init(&lock_info->lock, &mutex_attr);
863 pthread_mutexattr_destroy(&mutex_attr);
865 pthread_mutex_lock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
866 AST_LIST_INSERT_TAIL(&lock_infos, lock_info, entry);
867 pthread_mutex_unlock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
868 #endif /* DEBUG_THREADS */
870 ret = a.start_routine(a.data);
872 pthread_cleanup_pop(1);
877 #endif /* !LOW_MEMORY */
879 int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
880 void *data, size_t stacksize, const char *file, const char *caller,
881 int line, const char *start_fn)
883 #if !defined(LOW_MEMORY)
888 attr = alloca(sizeof(*attr));
889 pthread_attr_init(attr);
893 /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
894 which is kind of useless. Change this here to
895 PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
896 priority will propagate down to new threads by default.
897 This does mean that callers cannot set a different priority using
898 PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
899 the priority afterwards with pthread_setschedparam(). */
900 if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
901 ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
905 stacksize = AST_STACKSIZE;
907 if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
908 ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
910 #if !defined(LOW_MEMORY)
911 if ((a = ast_malloc(sizeof(*a)))) {
912 a->start_routine = start_routine;
914 start_routine = dummy_start;
915 asprintf(&a->name, "%-20s started at [%5d] %s %s()",
916 start_fn, line, file, caller);
919 #endif /* !LOW_MEMORY */
921 return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
925 int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
926 void *data, size_t stacksize, const char *file, const char *caller,
927 int line, const char *start_fn)
929 unsigned char attr_destroy = 0;
933 attr = alloca(sizeof(*attr));
934 pthread_attr_init(attr);
938 if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
939 ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
941 res = ast_pthread_create_stack(thread, attr, start_routine, data,
942 stacksize, file, caller, line, start_fn);
945 pthread_attr_destroy(attr);
950 int ast_wait_for_input(int fd, int ms)
952 struct pollfd pfd[1];
953 memset(pfd, 0, sizeof(pfd));
955 pfd[0].events = POLLIN|POLLPRI;
956 return poll(pfd, 1, ms);
960 * Try to write string, but wait no more than ms milliseconds before timing out.
962 * \note The code assumes that the file descriptor has NONBLOCK set,
963 * so there is only one system call made to do a write, unless we actually
964 * have a need to wait. This way, we get better performance.
965 * If the descriptor is blocking, all assumptions on the guaranteed
966 * detail do not apply anymore.
967 * Also note that in the current implementation, the delay is per-write,
968 * so you still have no guarantees, anyways.
969 * Fortunately the routine is only used in a few places (cli.c, manager.c,
970 * res_agi.c) so it is reasonably easy to check how it behaves there.
972 * XXX We either need to fix the code, or fix the documentation.
974 int ast_carefulwrite(int fd, char *s, int len, int timeoutms)
976 /* Try to write string, but wait no more than ms milliseconds
979 struct pollfd fds[1];
981 res = write(fd, s, len);
982 if ((res < 0) && (errno != EAGAIN)) {
992 fds[0].events = POLLOUT;
993 /* Wait until writable again */
994 res = poll(fds, 1, timeoutms);
1002 char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
1008 if ((q = strchr(beg_quotes, *s)) && *q != '\0') {
1009 e = s + strlen(s) - 1;
1010 if (*e == *(end_quotes + (q - beg_quotes))) {
1019 char *ast_unescape_semicolon(char *s)
1024 while ((e = strchr(work, ';'))) {
1025 if ((e > work) && (*(e-1) == '\\')) {
1026 memmove(e - 1, e, strlen(e) + 1);
1036 /* !\brief unescape some C sequences in place, return pointer to the original string.
1038 char *ast_unescape_c(char *src)
1044 for (ret = dst = src; (c = *src++); *dst++ = c ) {
1046 continue; /* copy char at the end of the loop */
1047 switch ((c = *src++)) {
1048 case '\0': /* special, trailing '\' */
1051 case 'b': /* backspace */
1054 case 'f': /* form feed */
1067 /* default, use the char literally */
1073 int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap)
1077 if (!buffer || !*buffer || !space || !*space)
1080 result = vsnprintf(*buffer, *space, fmt, ap);
1084 else if (result > *space)
1092 int ast_build_string(char **buffer, size_t *space, const char *fmt, ...)
1098 result = ast_build_string_va(buffer, space, fmt, ap);
1104 int ast_true(const char *s)
1106 if (ast_strlen_zero(s))
1109 /* Determine if this is a true value */
1110 if (!strcasecmp(s, "yes") ||
1111 !strcasecmp(s, "true") ||
1112 !strcasecmp(s, "y") ||
1113 !strcasecmp(s, "t") ||
1114 !strcasecmp(s, "1") ||
1115 !strcasecmp(s, "on"))
1121 int ast_false(const char *s)
1123 if (ast_strlen_zero(s))
1126 /* Determine if this is a false value */
1127 if (!strcasecmp(s, "no") ||
1128 !strcasecmp(s, "false") ||
1129 !strcasecmp(s, "n") ||
1130 !strcasecmp(s, "f") ||
1131 !strcasecmp(s, "0") ||
1132 !strcasecmp(s, "off"))
1138 #define ONE_MILLION 1000000
1140 * put timeval in a valid range. usec is 0..999999
1141 * negative values are not allowed and truncated.
1143 static struct timeval tvfix(struct timeval a)
1145 if (a.tv_usec >= ONE_MILLION) {
1146 ast_log(LOG_WARNING, "warning too large timestamp %ld.%ld\n",
1147 a.tv_sec, (long int) a.tv_usec);
1148 a.tv_sec += a.tv_usec / ONE_MILLION;
1149 a.tv_usec %= ONE_MILLION;
1150 } else if (a.tv_usec < 0) {
1151 ast_log(LOG_WARNING, "warning negative timestamp %ld.%ld\n",
1152 a.tv_sec, (long int) a.tv_usec);
1158 struct timeval ast_tvadd(struct timeval a, struct timeval b)
1160 /* consistency checks to guarantee usec in 0..999999 */
1163 a.tv_sec += b.tv_sec;
1164 a.tv_usec += b.tv_usec;
1165 if (a.tv_usec >= ONE_MILLION) {
1167 a.tv_usec -= ONE_MILLION;
1172 struct timeval ast_tvsub(struct timeval a, struct timeval b)
1174 /* consistency checks to guarantee usec in 0..999999 */
1177 a.tv_sec -= b.tv_sec;
1178 a.tv_usec -= b.tv_usec;
1179 if (a.tv_usec < 0) {
1181 a.tv_usec += ONE_MILLION;
1187 /*! \brief glibc puts a lock inside random(3), so that the results are thread-safe.
1188 * BSD libc (and others) do not. */
1191 AST_MUTEX_DEFINE_STATIC(randomlock);
1194 long int ast_random(void)
1197 #ifdef HAVE_DEV_URANDOM
1198 if (dev_urandom_fd >= 0) {
1199 int read_res = read(dev_urandom_fd, &res, sizeof(res));
1201 long int rm = RAND_MAX;
1202 res = res < 0 ? ~res : res;
1211 ast_mutex_lock(&randomlock);
1213 ast_mutex_unlock(&randomlock);
1218 char *ast_process_quotes_and_slashes(char *start, char find, char replace_with)
1220 char *dataPut = start;
1224 for (; *start; start++) {
1226 *dataPut++ = *start; /* Always goes verbatim */
1229 if (*start == '\\') {
1230 inEscape = 1; /* Do not copy \ into the data */
1231 } else if (*start == '\'') {
1232 inQuotes = 1 - inQuotes; /* Do not copy ' into the data */
1234 /* Replace , with |, unless in quotes */
1235 *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
1239 if (start != dataPut)
1244 void ast_join(char *s, size_t len, char * const w[])
1249 /* Join words into a string */
1252 for (x = 0; ofs < len && w[x]; x++) {
1255 for (src = w[x]; *src && ofs < len; src++)
1264 * stringfields support routines.
1267 const char __ast_string_field_empty[] = ""; /*!< the empty string */
1269 /*! \brief add a new block to the pool.
1270 * We can only allocate from the topmost pool, so the
1271 * fields in *mgr reflect the size of that only.
1273 static int add_string_pool(struct ast_string_field_mgr *mgr,
1274 struct ast_string_field_pool **pool_head, size_t size)
1276 struct ast_string_field_pool *pool;
1278 if (!(pool = ast_calloc(1, sizeof(*pool) + size)))
1281 pool->prev = *pool_head;
1290 * This is an internal API, code should not use it directly.
1291 * It initializes all fields as empty, then uses 'size' for 3 functions:
1292 * size > 0 means initialize the pool list with a pool of given size.
1293 * This must be called right after allocating the object.
1294 * size = 0 means release all pools except the most recent one.
1295 * This is useful to e.g. reset an object to the initial value.
1296 * size < 0 means release all pools.
1297 * This must be done before destroying the object.
1299 int __ast_string_field_init(struct ast_string_field_mgr *mgr,
1300 struct ast_string_field_pool **pool_head, int size)
1302 const char **p = (const char **)pool_head + 1;
1303 struct ast_string_field_pool *cur = *pool_head;
1305 /* clear fields - this is always necessary */
1306 while ((struct ast_string_field_mgr *)p != mgr)
1307 *p++ = __ast_string_field_empty;
1308 if (size > 0) { /* allocate the initial pool */
1310 return add_string_pool(mgr, pool_head, size);
1312 if (size < 0) { /* reset all pools */
1314 } else { /* preserve the first pool */
1316 ast_log(LOG_WARNING, "trying to reset empty pool\n");
1320 (*pool_head)->prev = NULL;
1324 struct ast_string_field_pool *prev = cur->prev;
1331 ast_string_field __ast_string_field_alloc_space(struct ast_string_field_mgr *mgr,
1332 struct ast_string_field_pool **pool_head, size_t needed)
1334 char *result = NULL;
1335 size_t space = mgr->size - mgr->used;
1337 if (__builtin_expect(needed > space, 0)) {
1338 size_t new_size = mgr->size * 2;
1340 while (new_size < needed)
1343 if (add_string_pool(mgr, pool_head, new_size))
1347 result = (*pool_head)->base + mgr->used;
1348 mgr->used += needed;
1352 void __ast_string_field_ptr_build_va(struct ast_string_field_mgr *mgr,
1353 struct ast_string_field_pool **pool_head,
1354 const ast_string_field *ptr, const char *format, va_list ap1, va_list ap2)
1357 char *dst = (*pool_head)->base + mgr->used;
1358 const char **p = (const char **)ptr;
1359 size_t space = mgr->size - mgr->used;
1361 /* try to write using available space */
1362 needed = vsnprintf(dst, space, format, ap1) + 1;
1366 if (needed > space) { /* if it fails, reallocate */
1367 size_t new_size = mgr->size * 2;
1369 while (new_size < needed)
1372 if (add_string_pool(mgr, pool_head, new_size))
1375 dst = (*pool_head)->base + mgr->used;
1376 vsprintf(dst, format, ap2);
1380 mgr->used += needed;
1383 void __ast_string_field_ptr_build(struct ast_string_field_mgr *mgr,
1384 struct ast_string_field_pool **pool_head,
1385 const ast_string_field *ptr, const char *format, ...)
1389 va_start(ap1, format);
1390 va_start(ap2, format); /* va_copy does not exist on FreeBSD */
1392 __ast_string_field_ptr_build_va(mgr, pool_head, ptr, format, ap1, ap2);
1397 /* end of stringfields support */
1399 AST_MUTEX_DEFINE_STATIC(fetchadd_m); /* used for all fetc&add ops */
1401 int ast_atomic_fetchadd_int_slow(volatile int *p, int v)
1404 ast_mutex_lock(&fetchadd_m);
1407 ast_mutex_unlock(&fetchadd_m);
1412 * get values from config variables.
1414 int ast_get_timeval(const char *src, struct timeval *dst, struct timeval _default, int *consumed)
1416 long double dtv = 0.0;
1424 if (ast_strlen_zero(src))
1427 /* only integer at the moment, but one day we could accept more formats */
1428 if (sscanf(src, "%Lf%n", &dtv, &scanned) > 0) {
1430 dst->tv_usec = (dtv - dst->tv_sec) * 1000000.0;
1432 *consumed = scanned;
1439 * get values from config variables.
1441 int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed)
1451 if (ast_strlen_zero(src))
1454 /* only integer at the moment, but one day we could accept more formats */
1455 if (sscanf(src, "%ld%n", &t, &scanned) == 1) {
1458 *consumed = scanned;
1465 * core handler for dynamic strings.
1466 * This is not meant to be called directly, but rather through the
1467 * various wrapper macros
1469 * ast_str_append(...)
1470 * ast_str_set_va(...)
1471 * ast_str_append_va(...)
1473 int __ast_str_helper(struct ast_str **buf, size_t max_len,
1474 int append, const char *fmt, va_list ap)
1477 int offset = (append && (*buf)->len) ? (*buf)->used : 0;
1480 max_len = (*buf)->len; /* don't exceed the allocated space */
1482 * Ask vsnprintf how much space we need. Remember that vsnprintf
1483 * does not count the final '\0' so we must add 1.
1485 res = vsnprintf((*buf)->str + offset, (*buf)->len - offset, fmt, ap);
1487 need = res + offset + 1;
1489 * If there is not enough space and we are below the max length,
1490 * reallocate the buffer and return a message telling to retry.
1492 if (need > (*buf)->len && (max_len == 0 || (*buf)->len < max_len) ) {
1493 if (max_len && max_len < need) /* truncate as needed */
1495 else if (max_len == 0) /* if unbounded, give more room for next time */
1496 need += 16 + need/4;
1497 if (0) /* debugging */
1498 ast_verbose("extend from %d to %d\n", (int)(*buf)->len, need);
1499 if (ast_str_make_space(buf, need)) {
1500 ast_verbose("failed to extend from %d to %d\n", (int)(*buf)->len, need);
1501 return AST_DYNSTR_BUILD_FAILED;
1503 (*buf)->str[offset] = '\0'; /* Truncate the partial write. */
1505 /* va_end() and va_start() must be done before calling
1506 * vsnprintf() again. */
1507 return AST_DYNSTR_BUILD_RETRY;
1509 /* update space used, keep in mind the truncation */
1510 (*buf)->used = (res + offset > (*buf)->len) ? (*buf)->len : res + offset;
1515 void ast_enable_packet_fragmentation(int sock)
1517 #if defined(HAVE_IP_MTU_DISCOVER)
1518 int val = IP_PMTUDISC_DONT;
1520 if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
1521 ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
1522 #endif /* HAVE_IP_MTU_DISCOVER */
1525 int ast_mkdir(const char *path, int mode)
1528 int len = strlen(path), count = 0, x, piececount = 0;
1529 char *tmp = ast_strdupa(path);
1531 char *fullpath = alloca(len + 1);
1534 for (ptr = tmp; *ptr; ptr++) {
1539 /* Count the components to the directory path */
1540 pieces = alloca(count * sizeof(*pieces));
1541 for (ptr = tmp; *ptr; ptr++) {
1544 pieces[piececount++] = ptr + 1;
1549 for (x = 0; x < piececount; x++) {
1550 /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
1551 strcat(fullpath, "/");
1552 strcat(fullpath, pieces[x]);
1553 res = mkdir(fullpath, mode);
1554 if (res && errno != EEXIST)
1560 int ast_utils_init(void)
1562 #ifdef HAVE_DEV_URANDOM
1563 dev_urandom_fd = open("/dev/urandom", O_RDONLY);
1566 #ifdef DEBUG_THREADS
1567 ast_cli_register_multiple(utils_cli, sizeof(utils_cli) / sizeof(utils_cli[0]));