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.
27 <support_level>core</support_level>
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37 #include <sys/syscall.h>
39 #if defined(__APPLE__)
40 #include <mach/mach.h>
41 #elif defined(HAVE_SYS_THR_H)
45 #include "asterisk/network.h"
46 #include "asterisk/ast_version.h"
48 #define AST_API_MODULE /* ensure that inlinable API functions will be built in lock.h if required */
49 #include "asterisk/lock.h"
50 #include "asterisk/io.h"
51 #include "asterisk/md5.h"
52 #include "asterisk/sha1.h"
53 #include "asterisk/cli.h"
54 #include "asterisk/linkedlists.h"
56 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
57 #include "asterisk/strings.h"
59 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
60 #include "asterisk/time.h"
62 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
63 #include "asterisk/stringfields.h"
65 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
66 #include "asterisk/utils.h"
68 #define AST_API_MODULE
69 #include "asterisk/threadstorage.h"
71 #define AST_API_MODULE
72 #include "asterisk/config.h"
74 static char base64[64];
77 AST_THREADSTORAGE(inet_ntoa_buf);
79 #if !defined(HAVE_GETHOSTBYNAME_R_5) && !defined(HAVE_GETHOSTBYNAME_R_6)
81 #define ERANGE 34 /*!< duh? ERANGE value copied from web... */
84 AST_MUTEX_DEFINE_STATIC(__mutex);
86 /*! \brief Reentrant replacement for gethostbyname for BSD-based systems.
88 routine is derived from code originally written and placed in the public
89 domain by Enzo Michelangeli <em@em.no-ip.com> */
91 static int gethostbyname_r (const char *name, struct hostent *ret, char *buf,
92 size_t buflen, struct hostent **result,
97 ast_mutex_lock(&__mutex); /* begin critical area */
100 ph = gethostbyname(name);
101 *h_errnop = h_errno; /* copy h_errno to *h_herrnop */
108 int naddr = 0, naliases = 0;
109 /* determine if we have enough space in buf */
111 /* count how many addresses */
112 for (p = ph->h_addr_list; *p != 0; p++) {
113 nbytes += ph->h_length; /* addresses */
114 nbytes += sizeof(*p); /* pointers */
117 nbytes += sizeof(*p); /* one more for the terminating NULL */
119 /* count how many aliases, and total length of strings */
120 for (p = ph->h_aliases; *p != 0; p++) {
121 nbytes += (strlen(*p)+1); /* aliases */
122 nbytes += sizeof(*p); /* pointers */
125 nbytes += sizeof(*p); /* one more for the terminating NULL */
127 /* here nbytes is the number of bytes required in buffer */
128 /* as a terminator must be there, the minimum value is ph->h_length */
129 if (nbytes > buflen) {
131 ast_mutex_unlock(&__mutex); /* end critical area */
132 return ERANGE; /* not enough space in buf!! */
135 /* There is enough space. Now we need to do a deep copy! */
136 /* Allocation in buffer:
137 from [0] to [(naddr-1) * sizeof(*p)]:
138 pointers to addresses
139 at [naddr * sizeof(*p)]:
141 from [(naddr+1) * sizeof(*p)] to [(naddr+naliases) * sizeof(*p)] :
143 at [(naddr+naliases+1) * sizeof(*p)]:
145 then naddr addresses (fixed length), and naliases aliases (asciiz).
148 *ret = *ph; /* copy whole structure (not its address!) */
151 q = (char **)buf; /* pointer to pointers area (type: char **) */
152 ret->h_addr_list = q; /* update pointer to address list */
153 pbuf = buf + ((naddr + naliases + 2) * sizeof(*p)); /* skip that area */
154 for (p = ph->h_addr_list; *p != 0; p++) {
155 memcpy(pbuf, *p, ph->h_length); /* copy address bytes */
156 *q++ = pbuf; /* the pointer is the one inside buf... */
157 pbuf += ph->h_length; /* advance pbuf */
159 *q++ = NULL; /* address list terminator */
162 ret->h_aliases = q; /* update pointer to aliases list */
163 for (p = ph->h_aliases; *p != 0; p++) {
164 strcpy(pbuf, *p); /* copy alias strings */
165 *q++ = pbuf; /* the pointer is the one inside buf... */
166 pbuf += strlen(*p); /* advance pbuf */
167 *pbuf++ = 0; /* string terminator */
169 *q++ = NULL; /* terminator */
171 strcpy(pbuf, ph->h_name); /* copy alias strings */
173 pbuf += strlen(ph->h_name); /* advance pbuf */
174 *pbuf++ = 0; /* string terminator */
176 *result = ret; /* and let *result point to structure */
179 h_errno = hsave; /* restore h_errno */
180 ast_mutex_unlock(&__mutex); /* end critical area */
182 return (*result == NULL); /* return 0 on success, non-zero on error */
188 /*! \brief Re-entrant (thread safe) version of gethostbyname that replaces the
189 standard gethostbyname (which is not thread safe)
191 struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp)
197 struct hostent *result = NULL;
198 /* Although it is perfectly legitimate to lookup a pure integer, for
199 the sake of the sanity of people who like to name their peers as
200 integers, we break with tradition and refuse to look up a
207 else if (!isdigit(*s))
212 /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
215 memset(hp, 0, sizeof(struct ast_hostent));
216 hp->hp.h_addrtype = AF_INET;
217 hp->hp.h_addr_list = (void *) hp->buf;
218 hp->hp.h_addr = hp->buf + sizeof(void *);
219 /* For AF_INET, this will always be 4 */
221 if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
226 #ifdef HAVE_GETHOSTBYNAME_R_5
227 result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);
229 if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
232 res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
234 if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
240 /*! \brief Produce 32 char MD5 hash of value. */
241 void ast_md5_hash(char *output, const char *input)
243 struct MD5Context md5;
244 unsigned char digest[16];
249 MD5Update(&md5, (const unsigned char *) input, strlen(input));
250 MD5Final(digest, &md5);
252 for (x = 0; x < 16; x++)
253 ptr += sprintf(ptr, "%2.2x", digest[x]);
256 /*! \brief Produce 40 char SHA1 hash of value. */
257 void ast_sha1_hash(char *output, const char *input)
259 struct SHA1Context sha;
262 uint8_t Message_Digest[20];
266 SHA1Input(&sha, (const unsigned char *) input, strlen(input));
268 SHA1Result(&sha, Message_Digest);
270 for (x = 0; x < 20; x++)
271 ptr += sprintf(ptr, "%2.2x", Message_Digest[x]);
274 /*! \brief Produce a 20 byte SHA1 hash of value. */
275 void ast_sha1_hash_uint(uint8_t *digest, const char *input)
277 struct SHA1Context sha;
281 SHA1Input(&sha, (const unsigned char *) input, strlen(input));
283 SHA1Result(&sha, digest);
286 /*! \brief decode BASE64 encoded text */
287 int ast_base64decode(unsigned char *dst, const char *src, int max)
290 unsigned int byte = 0;
291 unsigned int bits = 0;
293 while(*src && *src != '=' && (cnt < max)) {
294 /* Shift in 6 bits of input */
296 byte |= (b2a[(int)(*src)]) & 0x3f;
300 /* If we have at least 8 bits left over, take that character
304 *dst = (byte >> bits) & 0xff;
309 /* Don't worry about left over bits, they're extra anyway */
313 /*! \brief encode text to BASE64 coding */
314 int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
318 unsigned int byte = 0;
321 /* Reserve space for null byte at end of string */
323 while ((cntin < srclen) && (cnt < max)) {
328 if ((bits == 24) && (cnt + 4 <= max)) {
329 *dst++ = base64[(byte >> 18) & 0x3f];
330 *dst++ = base64[(byte >> 12) & 0x3f];
331 *dst++ = base64[(byte >> 6) & 0x3f];
332 *dst++ = base64[byte & 0x3f];
338 if (linebreaks && (cnt < max) && (col == 64)) {
344 if (bits && (cnt + 4 <= max)) {
345 /* Add one last character for the remaining bits,
346 padding the rest with 0 */
348 *dst++ = base64[(byte >> 18) & 0x3f];
349 *dst++ = base64[(byte >> 12) & 0x3f];
351 *dst++ = base64[(byte >> 6) & 0x3f];
357 if (linebreaks && (cnt < max)) {
365 int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
367 return ast_base64encode_full(dst, src, srclen, max, 0);
370 static void base64_init(void)
373 memset(b2a, -1, sizeof(b2a));
374 /* Initialize base-64 Conversion table */
375 for (x = 0; x < 26; x++) {
380 base64[x + 26] = 'a' + x;
381 b2a['a' + x] = x + 26;
384 base64[x + 52] = '0' + x;
385 b2a['0' + x] = x + 52;
394 const struct ast_flags ast_uri_http = {AST_URI_UNRESERVED};
395 const struct ast_flags ast_uri_http_legacy = {AST_URI_LEGACY_SPACE | AST_URI_UNRESERVED};
396 const struct ast_flags ast_uri_sip_user = {AST_URI_UNRESERVED | AST_URI_SIP_USER_UNRESERVED};
398 char *ast_uri_encode(const char *string, char *outbuf, int buflen, struct ast_flags spec)
400 const char *ptr = string; /* Start with the string */
402 const char *mark = "-_.!~*'()"; /* no encode set, RFC 2396 section 2.3, RFC 3261 sec 25 */
403 const char *user_unreserved = "&=+$,;?/"; /* user-unreserved set, RFC 3261 sec 25 */
405 while (*ptr && out - outbuf < buflen - 1) {
406 if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *ptr == ' ') {
407 /* for legacy encoding, encode spaces as '+' */
410 } else if (!(ast_test_flag(&spec, AST_URI_MARK)
411 && strchr(mark, *ptr))
412 && !(ast_test_flag(&spec, AST_URI_ALPHANUM)
413 && ((*ptr >= '0' && *ptr <= '9')
414 || (*ptr >= 'A' && *ptr <= 'Z')
415 || (*ptr >= 'a' && *ptr <= 'z')))
416 && !(ast_test_flag(&spec, AST_URI_SIP_USER_UNRESERVED)
417 && strchr(user_unreserved, *ptr))) {
419 if (out - outbuf >= buflen - 3) {
422 out += sprintf(out, "%%%02X", (unsigned char) *ptr);
424 *out = *ptr; /* Continue copying the string */
437 void ast_uri_decode(char *s, struct ast_flags spec)
442 for (o = s; *s; s++, o++) {
443 if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *s == '+') {
444 /* legacy mode, decode '+' as space */
446 } else if (*s == '%' && s[1] != '\0' && s[2] != '\0' && sscanf(s + 1, "%2x", &tmp) == 1) {
447 /* have '%', two chars and correct parsing */
449 s += 2; /* Will be incremented once more when we break out */
450 } else /* all other cases, just copy */
456 char *ast_escape_quoted(const char *string, char *outbuf, int buflen)
458 const char *ptr = string;
460 char *allow = "\t\v !"; /* allow LWS (minus \r and \n) and "!" */
462 while (*ptr && out - outbuf < buflen - 1) {
463 if (!(strchr(allow, *ptr))
464 && !(*ptr >= '#' && *ptr <= '[') /* %x23 - %x5b */
465 && !(*ptr >= ']' && *ptr <= '~') /* %x5d - %x7e */
466 && !((unsigned char) *ptr > 0x7f)) { /* UTF8-nonascii */
468 if (out - outbuf >= buflen - 2) {
471 out += sprintf(out, "\\%c", (unsigned char) *ptr);
485 int ast_xml_escape(const char *string, char * const outbuf, const size_t buflen)
488 char *end = outbuf + buflen - 1; /* save one for the null terminator */
490 /* Handle the case for the empty output buffer */
495 /* Escaping rules from http://www.w3.org/TR/REC-xml/#syntax */
496 /* This also prevents partial entities at the end of a string */
497 while (*string && dst < end) {
498 const char *entity = NULL;
511 /* necessary if ]]> is in the string; easier to escape them all */
516 /* necessary in single-quoted strings; easier to escape them all */
521 /* necessary in double-quoted strings; easier to escape them all */
531 ast_assert(len == strlen(entity));
532 if (end - dst < len) {
533 /* no room for the entity; stop */
536 /* just checked for length; strcpy is fine */
542 /* Write null terminator */
544 /* If any chars are left in string, return failure */
545 return *string == '\0' ? 0 : -1;
548 /*! \brief ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa */
549 const char *ast_inet_ntoa(struct in_addr ia)
553 if (!(buf = ast_threadstorage_get(&inet_ntoa_buf, INET_ADDRSTRLEN)))
556 return inet_ntop(AF_INET, &ia, buf, INET_ADDRSTRLEN);
559 static int dev_urandom_fd;
562 #undef pthread_create /* For ast_pthread_create function only */
563 #endif /* !__linux__ */
565 #if !defined(LOW_MEMORY)
569 /*! \brief A reasonable maximum number of locks a thread would be holding ... */
570 #define AST_MAX_LOCKS 64
572 /* Allow direct use of pthread_mutex_t and friends */
573 #undef pthread_mutex_t
574 #undef pthread_mutex_lock
575 #undef pthread_mutex_unlock
576 #undef pthread_mutex_init
577 #undef pthread_mutex_destroy
580 * \brief Keep track of which locks a thread holds
582 * There is an instance of this struct for every active thread
584 struct thr_lock_info {
585 /*! The thread's ID */
587 /*! The thread name which includes where the thread was started */
588 const char *thread_name;
589 /*! This is the actual container of info for what locks this thread holds */
594 const char *lock_name;
597 enum ast_lock_type type;
598 /*! This thread is waiting on this lock */
600 /*! A condition has suspended this lock */
603 struct ast_bt *backtrace;
605 } locks[AST_MAX_LOCKS];
606 /*! This is the number of locks currently held by this thread.
607 * The index (num_locks - 1) has the info on the last one in the
609 unsigned int num_locks;
610 /*! Protects the contents of the locks member
611 * Intentionally not ast_mutex_t */
612 pthread_mutex_t lock;
613 AST_LIST_ENTRY(thr_lock_info) entry;
617 * \brief Locked when accessing the lock_infos list
619 AST_MUTEX_DEFINE_STATIC(lock_infos_lock);
621 * \brief A list of each thread's lock info
623 static AST_LIST_HEAD_NOLOCK_STATIC(lock_infos, thr_lock_info);
626 * \brief Destroy a thread's lock info
628 * This gets called automatically when the thread stops
630 static void lock_info_destroy(void *data)
632 struct thr_lock_info *lock_info = data;
635 pthread_mutex_lock(&lock_infos_lock.mutex);
636 AST_LIST_REMOVE(&lock_infos, lock_info, entry);
637 pthread_mutex_unlock(&lock_infos_lock.mutex);
640 for (i = 0; i < lock_info->num_locks; i++) {
641 if (lock_info->locks[i].pending == -1) {
642 /* This just means that the last lock this thread went for was by
643 * using trylock, and it failed. This is fine. */
648 "Thread '%s' still has a lock! - '%s' (%p) from '%s' in %s:%d!\n",
649 lock_info->thread_name,
650 lock_info->locks[i].lock_name,
651 lock_info->locks[i].lock_addr,
652 lock_info->locks[i].func,
653 lock_info->locks[i].file,
654 lock_info->locks[i].line_num
658 pthread_mutex_destroy(&lock_info->lock);
659 if (lock_info->thread_name) {
660 ast_free((void *) lock_info->thread_name);
666 * \brief The thread storage key for per-thread lock info
668 AST_THREADSTORAGE_CUSTOM(thread_lock_info, NULL, lock_info_destroy);
670 void ast_store_lock_info(enum ast_lock_type type, const char *filename,
671 int line_num, const char *func, const char *lock_name, void *lock_addr, struct ast_bt *bt)
673 void ast_store_lock_info(enum ast_lock_type type, const char *filename,
674 int line_num, const char *func, const char *lock_name, void *lock_addr)
677 struct thr_lock_info *lock_info;
680 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
683 pthread_mutex_lock(&lock_info->lock);
685 for (i = 0; i < lock_info->num_locks; i++) {
686 if (lock_info->locks[i].lock_addr == lock_addr) {
687 lock_info->locks[i].times_locked++;
689 lock_info->locks[i].backtrace = bt;
691 pthread_mutex_unlock(&lock_info->lock);
696 if (lock_info->num_locks == AST_MAX_LOCKS) {
697 /* Can't use ast_log here, because it will cause infinite recursion */
698 fprintf(stderr, "XXX ERROR XXX A thread holds more locks than '%d'."
699 " Increase AST_MAX_LOCKS!\n", AST_MAX_LOCKS);
700 pthread_mutex_unlock(&lock_info->lock);
704 if (i && lock_info->locks[i - 1].pending == -1) {
705 /* The last lock on the list was one that this thread tried to lock but
706 * failed at doing so. It has now moved on to something else, so remove
707 * the old lock from the list. */
709 lock_info->num_locks--;
710 memset(&lock_info->locks[i], 0, sizeof(lock_info->locks[0]));
713 lock_info->locks[i].file = filename;
714 lock_info->locks[i].line_num = line_num;
715 lock_info->locks[i].func = func;
716 lock_info->locks[i].lock_name = lock_name;
717 lock_info->locks[i].lock_addr = lock_addr;
718 lock_info->locks[i].times_locked = 1;
719 lock_info->locks[i].type = type;
720 lock_info->locks[i].pending = 1;
722 lock_info->locks[i].backtrace = bt;
724 lock_info->num_locks++;
726 pthread_mutex_unlock(&lock_info->lock);
729 void ast_mark_lock_acquired(void *lock_addr)
731 struct thr_lock_info *lock_info;
733 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
736 pthread_mutex_lock(&lock_info->lock);
737 if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
738 lock_info->locks[lock_info->num_locks - 1].pending = 0;
740 pthread_mutex_unlock(&lock_info->lock);
743 void ast_mark_lock_failed(void *lock_addr)
745 struct thr_lock_info *lock_info;
747 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
750 pthread_mutex_lock(&lock_info->lock);
751 if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
752 lock_info->locks[lock_info->num_locks - 1].pending = -1;
753 lock_info->locks[lock_info->num_locks - 1].times_locked--;
755 pthread_mutex_unlock(&lock_info->lock);
758 int ast_find_lock_info(void *lock_addr, char *filename, size_t filename_size, int *lineno, char *func, size_t func_size, char *mutex_name, size_t mutex_name_size)
760 struct thr_lock_info *lock_info;
763 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
766 pthread_mutex_lock(&lock_info->lock);
768 for (i = lock_info->num_locks - 1; i >= 0; i--) {
769 if (lock_info->locks[i].lock_addr == lock_addr)
774 /* Lock not found :( */
775 pthread_mutex_unlock(&lock_info->lock);
779 ast_copy_string(filename, lock_info->locks[i].file, filename_size);
780 *lineno = lock_info->locks[i].line_num;
781 ast_copy_string(func, lock_info->locks[i].func, func_size);
782 ast_copy_string(mutex_name, lock_info->locks[i].lock_name, mutex_name_size);
784 pthread_mutex_unlock(&lock_info->lock);
789 void ast_suspend_lock_info(void *lock_addr)
791 struct thr_lock_info *lock_info;
794 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info)))) {
798 pthread_mutex_lock(&lock_info->lock);
800 for (i = lock_info->num_locks - 1; i >= 0; i--) {
801 if (lock_info->locks[i].lock_addr == lock_addr)
806 /* Lock not found :( */
807 pthread_mutex_unlock(&lock_info->lock);
811 lock_info->locks[i].suspended = 1;
813 pthread_mutex_unlock(&lock_info->lock);
816 void ast_restore_lock_info(void *lock_addr)
818 struct thr_lock_info *lock_info;
821 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
824 pthread_mutex_lock(&lock_info->lock);
826 for (i = lock_info->num_locks - 1; i >= 0; i--) {
827 if (lock_info->locks[i].lock_addr == lock_addr)
832 /* Lock not found :( */
833 pthread_mutex_unlock(&lock_info->lock);
837 lock_info->locks[i].suspended = 0;
839 pthread_mutex_unlock(&lock_info->lock);
844 void ast_remove_lock_info(void *lock_addr, struct ast_bt *bt)
846 void ast_remove_lock_info(void *lock_addr)
849 struct thr_lock_info *lock_info;
852 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
855 pthread_mutex_lock(&lock_info->lock);
857 for (i = lock_info->num_locks - 1; i >= 0; i--) {
858 if (lock_info->locks[i].lock_addr == lock_addr)
863 /* Lock not found :( */
864 pthread_mutex_unlock(&lock_info->lock);
868 if (lock_info->locks[i].times_locked > 1) {
869 lock_info->locks[i].times_locked--;
871 lock_info->locks[i].backtrace = bt;
873 pthread_mutex_unlock(&lock_info->lock);
877 if (i < lock_info->num_locks - 1) {
878 /* Not the last one ... *should* be rare! */
879 memmove(&lock_info->locks[i], &lock_info->locks[i + 1],
880 (lock_info->num_locks - (i + 1)) * sizeof(lock_info->locks[0]));
883 lock_info->num_locks--;
885 pthread_mutex_unlock(&lock_info->lock);
888 static const char *locktype2str(enum ast_lock_type type)
903 static void append_backtrace_information(struct ast_str **str, struct ast_bt *bt)
909 ast_str_append(str, 0, "\tNo backtrace to print\n");
913 /* store frame count locally to avoid the memory corruption that
914 * sometimes happens on virtualized CentOS 6.x systems */
915 num_frames = bt->num_frames;
916 if ((symbols = ast_bt_get_symbols(bt->addresses, num_frames))) {
919 for (frame_iterator = 0; frame_iterator < num_frames; ++frame_iterator) {
920 ast_str_append(str, 0, "\t%s\n", symbols[frame_iterator]);
923 ast_std_free(symbols);
925 ast_str_append(str, 0, "\tCouldn't retrieve backtrace symbols\n");
930 static void append_lock_information(struct ast_str **str, struct thr_lock_info *lock_info, int i)
934 struct ast_lock_track *lt;
936 ast_str_append(str, 0, "=== ---> %sLock #%d (%s): %s %d %s %s %p (%d%s)\n",
937 lock_info->locks[i].pending > 0 ? "Waiting for " :
938 lock_info->locks[i].pending < 0 ? "Tried and failed to get " : "", i,
939 lock_info->locks[i].file,
940 locktype2str(lock_info->locks[i].type),
941 lock_info->locks[i].line_num,
942 lock_info->locks[i].func, lock_info->locks[i].lock_name,
943 lock_info->locks[i].lock_addr,
944 lock_info->locks[i].times_locked,
945 lock_info->locks[i].suspended ? " - suspended" : "");
947 append_backtrace_information(str, lock_info->locks[i].backtrace);
950 if (!lock_info->locks[i].pending || lock_info->locks[i].pending == -1)
953 /* We only have further details for mutexes right now */
954 if (lock_info->locks[i].type != AST_MUTEX)
957 lock = lock_info->locks[i].lock_addr;
959 ast_reentrancy_lock(lt);
960 for (j = 0; *str && j < lt->reentrancy; j++) {
961 ast_str_append(str, 0, "=== --- ---> Locked Here: %s line %d (%s)\n",
962 lt->file[j], lt->lineno[j], lt->func[j]);
964 ast_reentrancy_unlock(lt);
968 /*! This function can help you find highly temporal locks; locks that happen for a
969 short time, but at unexpected times, usually at times that create a deadlock,
970 Why is this thing locked right then? Who is locking it? Who am I fighting
973 To answer such questions, just call this routine before you would normally try
974 to aquire a lock. It doesn't do anything if the lock is not acquired. If the
975 lock is taken, it will publish a line or two to the console via ast_log().
977 Sometimes, the lock message is pretty uninformative. For instance, you might
978 find that the lock is being aquired deep within the astobj2 code; this tells
979 you little about higher level routines that call the astobj2 routines.
980 But, using gdb, you can set a break at the ast_log below, and for that
981 breakpoint, you can set the commands:
984 which will give a stack trace and continue. -- that aught to do the job!
987 void ast_log_show_lock(void *this_lock_addr)
989 struct thr_lock_info *lock_info;
992 if (!(str = ast_str_create(4096))) {
993 ast_log(LOG_NOTICE,"Could not create str\n");
998 pthread_mutex_lock(&lock_infos_lock.mutex);
999 AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
1001 pthread_mutex_lock(&lock_info->lock);
1002 for (i = 0; str && i < lock_info->num_locks; i++) {
1003 /* ONLY show info about this particular lock, if
1005 if (lock_info->locks[i].lock_addr == this_lock_addr) {
1006 append_lock_information(&str, lock_info, i);
1007 ast_log(LOG_NOTICE, "%s", ast_str_buffer(str));
1011 pthread_mutex_unlock(&lock_info->lock);
1013 pthread_mutex_unlock(&lock_infos_lock.mutex);
1018 struct ast_str *ast_dump_locks(void)
1020 struct thr_lock_info *lock_info;
1021 struct ast_str *str;
1023 if (!(str = ast_str_create(4096))) {
1027 ast_str_append(&str, 0, "\n"
1028 "=======================================================================\n"
1030 "=== Currently Held Locks\n"
1031 "=======================================================================\n"
1033 "=== <pending> <lock#> (<file>): <lock type> <line num> <function> <lock name> <lock addr> (times locked)\n"
1034 "===\n", ast_get_version());
1040 pthread_mutex_lock(&lock_infos_lock.mutex);
1041 AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
1043 int header_printed = 0;
1044 pthread_mutex_lock(&lock_info->lock);
1045 for (i = 0; str && i < lock_info->num_locks; i++) {
1046 /* Don't show suspended locks */
1047 if (lock_info->locks[i].suspended) {
1051 if (!header_printed) {
1052 ast_str_append(&str, 0, "=== Thread ID: 0x%lx (%s)\n", (long) lock_info->thread_id,
1053 lock_info->thread_name);
1057 append_lock_information(&str, lock_info, i);
1059 pthread_mutex_unlock(&lock_info->lock);
1063 if (header_printed) {
1064 ast_str_append(&str, 0, "=== -------------------------------------------------------------------\n"
1071 pthread_mutex_unlock(&lock_infos_lock.mutex);
1077 ast_str_append(&str, 0, "=======================================================================\n"
1083 static char *handle_show_locks(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1085 struct ast_str *str;
1089 e->command = "core show locks";
1091 "Usage: core show locks\n"
1092 " This command is for lock debugging. It prints out which locks\n"
1093 "are owned by each active thread.\n";
1100 str = ast_dump_locks();
1105 ast_cli(a->fd, "%s", ast_str_buffer(str));
1112 static struct ast_cli_entry utils_cli[] = {
1113 AST_CLI_DEFINE(handle_show_locks, "Show which locks are held by which thread"),
1116 #endif /* DEBUG_THREADS */
1119 * support for 'show threads'. The start routine is wrapped by
1120 * dummy_start(), so that ast_register_thread() and
1121 * ast_unregister_thread() know the thread identifier.
1124 void *(*start_routine)(void *);
1130 * on OS/X, pthread_cleanup_push() and pthread_cleanup_pop()
1131 * are odd macros which start and end a block, so they _must_ be
1132 * used in pairs (the latter with a '1' argument to call the
1134 * On BSD we don't need this, but we keep it for compatibility.
1136 static void *dummy_start(void *data)
1139 struct thr_arg a = *((struct thr_arg *) data); /* make a local copy */
1140 #ifdef DEBUG_THREADS
1141 struct thr_lock_info *lock_info;
1142 pthread_mutexattr_t mutex_attr;
1144 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
1147 lock_info->thread_id = pthread_self();
1148 lock_info->thread_name = strdup(a.name);
1150 pthread_mutexattr_init(&mutex_attr);
1151 pthread_mutexattr_settype(&mutex_attr, AST_MUTEX_KIND);
1152 pthread_mutex_init(&lock_info->lock, &mutex_attr);
1153 pthread_mutexattr_destroy(&mutex_attr);
1155 pthread_mutex_lock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
1156 AST_LIST_INSERT_TAIL(&lock_infos, lock_info, entry);
1157 pthread_mutex_unlock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
1158 #endif /* DEBUG_THREADS */
1160 /* note that even though data->name is a pointer to allocated memory,
1161 we are not freeing it here because ast_register_thread is going to
1162 keep a copy of the pointer and then ast_unregister_thread will
1166 ast_register_thread(a.name);
1167 pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
1169 ret = a.start_routine(a.data);
1171 pthread_cleanup_pop(1);
1176 #endif /* !LOW_MEMORY */
1178 int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
1179 void *data, size_t stacksize, const char *file, const char *caller,
1180 int line, const char *start_fn)
1182 #if !defined(LOW_MEMORY)
1187 attr = ast_alloca(sizeof(*attr));
1188 pthread_attr_init(attr);
1192 /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
1193 which is kind of useless. Change this here to
1194 PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
1195 priority will propagate down to new threads by default.
1196 This does mean that callers cannot set a different priority using
1197 PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
1198 the priority afterwards with pthread_setschedparam(). */
1199 if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
1200 ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
1204 stacksize = AST_STACKSIZE;
1206 if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
1207 ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
1209 #if !defined(LOW_MEMORY)
1210 if ((a = ast_malloc(sizeof(*a)))) {
1211 a->start_routine = start_routine;
1213 start_routine = dummy_start;
1214 if (ast_asprintf(&a->name, "%-20s started at [%5d] %s %s()",
1215 start_fn, line, file, caller) < 0) {
1220 #endif /* !LOW_MEMORY */
1222 return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
1226 int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
1227 void *data, size_t stacksize, const char *file, const char *caller,
1228 int line, const char *start_fn)
1230 unsigned char attr_destroy = 0;
1234 attr = ast_alloca(sizeof(*attr));
1235 pthread_attr_init(attr);
1239 if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
1240 ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
1242 res = ast_pthread_create_stack(thread, attr, start_routine, data,
1243 stacksize, file, caller, line, start_fn);
1246 pthread_attr_destroy(attr);
1251 int ast_wait_for_input(int fd, int ms)
1253 struct pollfd pfd[1];
1254 memset(pfd, 0, sizeof(pfd));
1256 pfd[0].events = POLLIN|POLLPRI;
1257 return ast_poll(pfd, 1, ms);
1260 static int ast_wait_for_output(int fd, int timeoutms)
1262 struct pollfd pfd = {
1267 struct timeval start = ast_tvnow();
1270 /* poll() until the fd is writable without blocking */
1271 while ((res = ast_poll(&pfd, 1, timeoutms - elapsed)) <= 0) {
1275 ast_debug(1, "Timed out trying to write\n");
1278 } else if (res == -1) {
1279 /* poll() returned an error, check to see if it was fatal */
1281 if (errno == EINTR || errno == EAGAIN) {
1282 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1283 if (elapsed >= timeoutms) {
1286 /* This was an acceptable error, go back into poll() */
1290 /* Fatal error, bail. */
1291 ast_log(LOG_ERROR, "poll returned error: %s\n", strerror(errno));
1295 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1296 if (elapsed >= timeoutms) {
1305 * Try to write string, but wait no more than ms milliseconds before timing out.
1307 * \note The code assumes that the file descriptor has NONBLOCK set,
1308 * so there is only one system call made to do a write, unless we actually
1309 * have a need to wait. This way, we get better performance.
1310 * If the descriptor is blocking, all assumptions on the guaranteed
1311 * detail do not apply anymore.
1313 int ast_carefulwrite(int fd, char *s, int len, int timeoutms)
1315 struct timeval start = ast_tvnow();
1320 if (ast_wait_for_output(fd, timeoutms - elapsed)) {
1324 res = write(fd, s, len);
1326 if (res < 0 && errno != EAGAIN && errno != EINTR) {
1327 /* fatal error from write() */
1328 ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
1333 /* It was an acceptable error */
1337 /* Update how much data we have left to write */
1342 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1343 if (elapsed >= timeoutms) {
1344 /* We've taken too long to write
1345 * This is only an error condition if we haven't finished writing. */
1354 int ast_careful_fwrite(FILE *f, int fd, const char *src, size_t len, int timeoutms)
1356 struct timeval start = ast_tvnow();
1361 if (ast_wait_for_output(fd, timeoutms - elapsed)) {
1362 /* poll returned a fatal error, so bail out immediately. */
1366 /* Clear any errors from a previous write */
1369 n = fwrite(src, 1, len, f);
1371 if (ferror(f) && errno != EINTR && errno != EAGAIN) {
1372 /* fatal error from fwrite() */
1374 /* Don't spam the logs if it was just that the connection is closed. */
1375 ast_log(LOG_ERROR, "fwrite() returned error: %s\n", strerror(errno));
1381 /* Update for data already written to the socket */
1385 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1386 if (elapsed >= timeoutms) {
1387 /* We've taken too long to write
1388 * This is only an error condition if we haven't finished writing. */
1395 if (errno == EAGAIN || errno == EINTR) {
1399 /* Don't spam the logs if it was just that the connection is closed. */
1400 ast_log(LOG_ERROR, "fflush() returned error: %s\n", strerror(errno));
1406 return n < 0 ? -1 : 0;
1409 char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
1415 if ((q = strchr(beg_quotes, *s)) && *q != '\0') {
1416 e = s + strlen(s) - 1;
1417 if (*e == *(end_quotes + (q - beg_quotes))) {
1426 char *ast_unescape_semicolon(char *s)
1431 while ((e = strchr(work, ';'))) {
1432 if ((e > work) && (*(e-1) == '\\')) {
1433 memmove(e - 1, e, strlen(e) + 1);
1443 /* !\brief unescape some C sequences in place, return pointer to the original string.
1445 char *ast_unescape_c(char *src)
1451 for (ret = dst = src; (c = *src++); *dst++ = c ) {
1453 continue; /* copy char at the end of the loop */
1454 switch ((c = *src++)) {
1455 case '\0': /* special, trailing '\' */
1458 case 'b': /* backspace */
1461 case 'f': /* form feed */
1474 /* default, use the char literally */
1480 int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap)
1484 if (!buffer || !*buffer || !space || !*space)
1487 result = vsnprintf(*buffer, *space, fmt, ap);
1491 else if (result > *space)
1499 int ast_build_string(char **buffer, size_t *space, const char *fmt, ...)
1505 result = ast_build_string_va(buffer, space, fmt, ap);
1511 int ast_regex_string_to_regex_pattern(const char *regex_string, struct ast_str **regex_pattern)
1513 int regex_len = strlen(regex_string);
1516 /* Chop off the leading / if there is one */
1517 if ((regex_len >= 1) && (regex_string[0] == '/')) {
1518 ast_str_set(regex_pattern, 0, "%s", regex_string + 1);
1522 /* Chop off the ending / if there is one */
1523 if ((regex_len > 1) && (regex_string[regex_len - 1] == '/')) {
1524 ast_str_truncate(*regex_pattern, -1);
1531 int ast_true(const char *s)
1533 if (ast_strlen_zero(s))
1536 /* Determine if this is a true value */
1537 if (!strcasecmp(s, "yes") ||
1538 !strcasecmp(s, "true") ||
1539 !strcasecmp(s, "y") ||
1540 !strcasecmp(s, "t") ||
1541 !strcasecmp(s, "1") ||
1542 !strcasecmp(s, "on"))
1548 int ast_false(const char *s)
1550 if (ast_strlen_zero(s))
1553 /* Determine if this is a false value */
1554 if (!strcasecmp(s, "no") ||
1555 !strcasecmp(s, "false") ||
1556 !strcasecmp(s, "n") ||
1557 !strcasecmp(s, "f") ||
1558 !strcasecmp(s, "0") ||
1559 !strcasecmp(s, "off"))
1565 #define ONE_MILLION 1000000
1567 * put timeval in a valid range. usec is 0..999999
1568 * negative values are not allowed and truncated.
1570 static struct timeval tvfix(struct timeval a)
1572 if (a.tv_usec >= ONE_MILLION) {
1573 ast_log(LOG_WARNING, "warning too large timestamp %ld.%ld\n",
1574 (long)a.tv_sec, (long int) a.tv_usec);
1575 a.tv_sec += a.tv_usec / ONE_MILLION;
1576 a.tv_usec %= ONE_MILLION;
1577 } else if (a.tv_usec < 0) {
1578 ast_log(LOG_WARNING, "warning negative timestamp %ld.%ld\n",
1579 (long)a.tv_sec, (long int) a.tv_usec);
1585 struct timeval ast_tvadd(struct timeval a, struct timeval b)
1587 /* consistency checks to guarantee usec in 0..999999 */
1590 a.tv_sec += b.tv_sec;
1591 a.tv_usec += b.tv_usec;
1592 if (a.tv_usec >= ONE_MILLION) {
1594 a.tv_usec -= ONE_MILLION;
1599 struct timeval ast_tvsub(struct timeval a, struct timeval b)
1601 /* consistency checks to guarantee usec in 0..999999 */
1604 a.tv_sec -= b.tv_sec;
1605 a.tv_usec -= b.tv_usec;
1606 if (a.tv_usec < 0) {
1608 a.tv_usec += ONE_MILLION;
1613 int ast_remaining_ms(struct timeval start, int max_ms)
1620 ms = max_ms - ast_tvdiff_ms(ast_tvnow(), start);
1629 void ast_format_duration_hh_mm_ss(int duration, char *buf, size_t length)
1631 int durh, durm, durs;
1632 durh = duration / 3600;
1633 durm = (duration % 3600) / 60;
1634 durs = duration % 60;
1635 snprintf(buf, length, "%02d:%02d:%02d", durh, durm, durs);
1641 AST_MUTEX_DEFINE_STATIC(randomlock);
1644 long int ast_random(void)
1648 if (dev_urandom_fd >= 0) {
1649 int read_res = read(dev_urandom_fd, &res, sizeof(res));
1651 long int rm = RAND_MAX;
1652 res = res < 0 ? ~res : res;
1658 /* XXX - Thread safety really depends on the libc, not the OS.
1660 * But... popular Linux libc's (uClibc, glibc, eglibc), all have a
1661 * somewhat thread safe random(3) (results are random, but not
1662 * reproducible). The libc's for other systems (BSD, et al.), not so
1668 ast_mutex_lock(&randomlock);
1670 ast_mutex_unlock(&randomlock);
1675 void ast_replace_subargument_delimiter(char *s)
1684 char *ast_process_quotes_and_slashes(char *start, char find, char replace_with)
1686 char *dataPut = start;
1690 for (; *start; start++) {
1692 *dataPut++ = *start; /* Always goes verbatim */
1695 if (*start == '\\') {
1696 inEscape = 1; /* Do not copy \ into the data */
1697 } else if (*start == '\'') {
1698 inQuotes = 1 - inQuotes; /* Do not copy ' into the data */
1700 /* Replace , with |, unless in quotes */
1701 *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
1705 if (start != dataPut)
1710 void ast_join_delim(char *s, size_t len, const char * const w[], unsigned int size, char delim)
1715 /* Join words into a string */
1718 for (x = 0; ofs < len && w[x] && x < size; x++) {
1721 for (src = w[x]; *src && ofs < len; src++)
1729 char *ast_to_camel_case_delim(const char *s, const char *delim)
1731 char *res = ast_strdup(s);
1732 char *front, *back, *buf = res;
1735 front = strtok_r(buf, delim, &back);
1738 size = strlen(front);
1739 *front = toupper(*front);
1740 ast_copy_string(buf, front, size + 1);
1742 front = strtok_r(NULL, delim, &back);
1749 * stringfields support routines.
1752 /* this is a little complex... string fields are stored with their
1753 allocated size in the bytes preceding the string; even the
1754 constant 'empty' string has to be this way, so the code that
1755 checks to see if there is enough room for a new string doesn't
1756 have to have any special case checks
1759 static const struct {
1760 ast_string_field_allocation allocation;
1762 } __ast_string_field_empty_buffer;
1764 ast_string_field __ast_string_field_empty = __ast_string_field_empty_buffer.string;
1766 #define ALLOCATOR_OVERHEAD 48
1768 static size_t optimal_alloc_size(size_t size)
1772 size += ALLOCATOR_OVERHEAD;
1774 for (count = 1; size; size >>= 1, count++);
1776 return (1 << count) - ALLOCATOR_OVERHEAD;
1779 /*! \brief add a new block to the pool.
1780 * We can only allocate from the topmost pool, so the
1781 * fields in *mgr reflect the size of that only.
1783 static int add_string_pool(struct ast_string_field_mgr *mgr, struct ast_string_field_pool **pool_head,
1784 size_t size, const char *file, int lineno, const char *func)
1786 struct ast_string_field_pool *pool;
1787 size_t alloc_size = optimal_alloc_size(sizeof(*pool) + size);
1789 #if defined(__AST_DEBUG_MALLOC)
1790 if (!(pool = __ast_calloc(1, alloc_size, file, lineno, func))) {
1794 if (!(pool = ast_calloc(1, alloc_size))) {
1799 pool->prev = *pool_head;
1800 pool->size = alloc_size - sizeof(*pool);
1802 mgr->last_alloc = NULL;
1808 * This is an internal API, code should not use it directly.
1809 * It initializes all fields as empty, then uses 'size' for 3 functions:
1810 * size > 0 means initialize the pool list with a pool of given size.
1811 * This must be called right after allocating the object.
1812 * size = 0 means release all pools except the most recent one.
1813 * If the first pool was allocated via embedding in another
1814 * object, that pool will be preserved instead.
1815 * This is useful to e.g. reset an object to the initial value.
1816 * size < 0 means release all pools.
1817 * This must be done before destroying the object.
1819 int __ast_string_field_init(struct ast_string_field_mgr *mgr, struct ast_string_field_pool **pool_head,
1820 int needed, const char *file, int lineno, const char *func)
1822 const char **p = (const char **) pool_head + 1;
1823 struct ast_string_field_pool *cur = NULL;
1824 struct ast_string_field_pool *preserve = NULL;
1826 /* clear fields - this is always necessary */
1827 while ((struct ast_string_field_mgr *) p != mgr) {
1828 *p++ = __ast_string_field_empty;
1831 mgr->last_alloc = NULL;
1832 #if defined(__AST_DEBUG_MALLOC)
1833 mgr->owner_file = file;
1834 mgr->owner_func = func;
1835 mgr->owner_line = lineno;
1837 if (needed > 0) { /* allocate the initial pool */
1839 mgr->embedded_pool = NULL;
1840 return add_string_pool(mgr, pool_head, needed, file, lineno, func);
1843 /* if there is an embedded pool, we can't actually release *all*
1844 * pools, we must keep the embedded one. if the caller is about
1845 * to free the structure that contains the stringfield manager
1846 * and embedded pool anyway, it will be freed as part of that
1849 if ((needed < 0) && mgr->embedded_pool) {
1853 if (needed < 0) { /* reset all pools */
1855 } else if (mgr->embedded_pool) { /* preserve the embedded pool */
1856 preserve = mgr->embedded_pool;
1858 } else { /* preserve the last pool */
1859 if (*pool_head == NULL) {
1860 ast_log(LOG_WARNING, "trying to reset empty pool\n");
1863 preserve = *pool_head;
1864 cur = preserve->prev;
1868 preserve->prev = NULL;
1869 preserve->used = preserve->active = 0;
1873 struct ast_string_field_pool *prev = cur->prev;
1875 if (cur != preserve) {
1881 *pool_head = preserve;
1886 ast_string_field __ast_string_field_alloc_space(struct ast_string_field_mgr *mgr,
1887 struct ast_string_field_pool **pool_head, size_t needed)
1889 char *result = NULL;
1890 size_t space = (*pool_head)->size - (*pool_head)->used;
1893 /* Make room for ast_string_field_allocation and make it a multiple of that. */
1894 to_alloc = ast_make_room_for(needed, ast_string_field_allocation);
1895 ast_assert(to_alloc % ast_alignof(ast_string_field_allocation) == 0);
1897 if (__builtin_expect(to_alloc > space, 0)) {
1898 size_t new_size = (*pool_head)->size;
1900 while (new_size < to_alloc) {
1904 #if defined(__AST_DEBUG_MALLOC)
1905 if (add_string_pool(mgr, pool_head, new_size, mgr->owner_file, mgr->owner_line, mgr->owner_func))
1908 if (add_string_pool(mgr, pool_head, new_size, __FILE__, __LINE__, __FUNCTION__))
1913 /* pool->base is always aligned (gcc aligned attribute). We ensure that
1914 * to_alloc is also a multiple of ast_alignof(ast_string_field_allocation)
1915 * causing result to always be aligned as well; which in turn fixes that
1916 * AST_STRING_FIELD_ALLOCATION(result) is aligned. */
1917 result = (*pool_head)->base + (*pool_head)->used;
1918 (*pool_head)->used += to_alloc;
1919 (*pool_head)->active += needed;
1920 result += ast_alignof(ast_string_field_allocation);
1921 AST_STRING_FIELD_ALLOCATION(result) = needed;
1922 mgr->last_alloc = result;
1927 int __ast_string_field_ptr_grow(struct ast_string_field_mgr *mgr,
1928 struct ast_string_field_pool **pool_head, size_t needed,
1929 const ast_string_field *ptr)
1931 ssize_t grow = needed - AST_STRING_FIELD_ALLOCATION(*ptr);
1932 size_t space = (*pool_head)->size - (*pool_head)->used;
1934 if (*ptr != mgr->last_alloc) {
1942 (*pool_head)->used += grow;
1943 (*pool_head)->active += grow;
1944 AST_STRING_FIELD_ALLOCATION(*ptr) += grow;
1949 void __ast_string_field_release_active(struct ast_string_field_pool *pool_head,
1950 const ast_string_field ptr)
1952 struct ast_string_field_pool *pool, *prev;
1954 if (ptr == __ast_string_field_empty) {
1958 for (pool = pool_head, prev = NULL; pool; prev = pool, pool = pool->prev) {
1959 if ((ptr >= pool->base) && (ptr <= (pool->base + pool->size))) {
1960 pool->active -= AST_STRING_FIELD_ALLOCATION(ptr);
1961 if ((pool->active == 0) && prev) {
1962 prev->prev = pool->prev;
1970 void __ast_string_field_ptr_build_va(struct ast_string_field_mgr *mgr,
1971 struct ast_string_field_pool **pool_head,
1972 ast_string_field *ptr, const char *format, va_list ap)
1976 size_t space = (*pool_head)->size - (*pool_head)->used;
1981 /* if the field already has space allocated, try to reuse it;
1982 otherwise, try to use the empty space at the end of the current
1985 if (*ptr != __ast_string_field_empty) {
1986 target = (char *) *ptr;
1987 available = AST_STRING_FIELD_ALLOCATION(*ptr);
1988 if (*ptr == mgr->last_alloc) {
1992 /* pool->used is always a multiple of ast_alignof(ast_string_field_allocation)
1993 * so we don't need to re-align anything here.
1995 target = (*pool_head)->base + (*pool_head)->used + ast_alignof(ast_string_field_allocation);
1996 available = space - ast_alignof(ast_string_field_allocation);
2000 needed = vsnprintf(target, available, format, ap2) + 1;
2003 if (needed > available) {
2004 /* the allocation could not be satisfied using the field's current allocation
2005 (if it has one), or the space available in the pool (if it does not). allocate
2006 space for it, adding a new string pool if necessary.
2008 if (!(target = (char *) __ast_string_field_alloc_space(mgr, pool_head, needed))) {
2011 vsprintf(target, format, ap);
2012 va_end(ap); /* XXX va_end without va_start? */
2013 __ast_string_field_release_active(*pool_head, *ptr);
2015 } else if (*ptr != target) {
2016 /* the allocation was satisfied using available space in the pool, but not
2017 using the space already allocated to the field
2019 __ast_string_field_release_active(*pool_head, *ptr);
2020 mgr->last_alloc = *ptr = target;
2021 AST_STRING_FIELD_ALLOCATION(target) = needed;
2022 (*pool_head)->used += ast_make_room_for(needed, ast_string_field_allocation);
2023 (*pool_head)->active += needed;
2024 } else if ((grow = (needed - AST_STRING_FIELD_ALLOCATION(*ptr))) > 0) {
2025 /* the allocation was satisfied by using available space in the pool *and*
2026 the field was the last allocated field from the pool, so it grew
2028 AST_STRING_FIELD_ALLOCATION(*ptr) += grow;
2029 (*pool_head)->used += ast_align_for(grow, ast_string_field_allocation);
2030 (*pool_head)->active += grow;
2034 void __ast_string_field_ptr_build(struct ast_string_field_mgr *mgr,
2035 struct ast_string_field_pool **pool_head,
2036 ast_string_field *ptr, const char *format, ...)
2040 va_start(ap, format);
2041 __ast_string_field_ptr_build_va(mgr, pool_head, ptr, format, ap);
2045 void *__ast_calloc_with_stringfields(unsigned int num_structs, size_t struct_size, size_t field_mgr_offset,
2046 size_t field_mgr_pool_offset, size_t pool_size, const char *file,
2047 int lineno, const char *func)
2049 struct ast_string_field_mgr *mgr;
2050 struct ast_string_field_pool *pool;
2051 struct ast_string_field_pool **pool_head;
2052 size_t pool_size_needed = sizeof(*pool) + pool_size;
2053 size_t size_to_alloc = optimal_alloc_size(struct_size + pool_size_needed);
2057 #if defined(__AST_DEBUG_MALLOC)
2058 if (!(allocation = __ast_calloc(num_structs, size_to_alloc, file, lineno, func))) {
2062 if (!(allocation = ast_calloc(num_structs, size_to_alloc))) {
2067 for (x = 0; x < num_structs; x++) {
2068 void *base = allocation + (size_to_alloc * x);
2071 mgr = base + field_mgr_offset;
2072 pool_head = base + field_mgr_pool_offset;
2073 pool = base + struct_size;
2075 p = (const char **) pool_head + 1;
2076 while ((struct ast_string_field_mgr *) p != mgr) {
2077 *p++ = __ast_string_field_empty;
2080 mgr->embedded_pool = pool;
2082 pool->size = size_to_alloc - struct_size - sizeof(*pool);
2083 #if defined(__AST_DEBUG_MALLOC)
2084 mgr->owner_file = file;
2085 mgr->owner_func = func;
2086 mgr->owner_line = lineno;
2093 /* end of stringfields support */
2095 AST_MUTEX_DEFINE_STATIC(fetchadd_m); /* used for all fetc&add ops */
2097 int ast_atomic_fetchadd_int_slow(volatile int *p, int v)
2100 ast_mutex_lock(&fetchadd_m);
2103 ast_mutex_unlock(&fetchadd_m);
2108 * get values from config variables.
2110 int ast_get_timeval(const char *src, struct timeval *dst, struct timeval _default, int *consumed)
2112 long double dtv = 0.0;
2120 if (ast_strlen_zero(src))
2123 /* only integer at the moment, but one day we could accept more formats */
2124 if (sscanf(src, "%30Lf%n", &dtv, &scanned) > 0) {
2126 dst->tv_usec = (dtv - dst->tv_sec) * 1000000.0;
2128 *consumed = scanned;
2135 * get values from config variables.
2137 int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed)
2147 if (ast_strlen_zero(src))
2150 /* only integer at the moment, but one day we could accept more formats */
2151 if (sscanf(src, "%30ld%n", &t, &scanned) == 1) {
2154 *consumed = scanned;
2160 void ast_enable_packet_fragmentation(int sock)
2162 #if defined(HAVE_IP_MTU_DISCOVER)
2163 int val = IP_PMTUDISC_DONT;
2165 if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
2166 ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
2167 #endif /* HAVE_IP_MTU_DISCOVER */
2170 int ast_mkdir(const char *path, int mode)
2173 int len = strlen(path), count = 0, x, piececount = 0;
2174 char *tmp = ast_strdupa(path);
2176 char *fullpath = ast_alloca(len + 1);
2179 for (ptr = tmp; *ptr; ptr++) {
2184 /* Count the components to the directory path */
2185 pieces = ast_alloca(count * sizeof(*pieces));
2186 for (ptr = tmp; *ptr; ptr++) {
2189 pieces[piececount++] = ptr + 1;
2194 for (x = 0; x < piececount; x++) {
2195 /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
2196 strcat(fullpath, "/");
2197 strcat(fullpath, pieces[x]);
2198 res = mkdir(fullpath, mode);
2199 if (res && errno != EEXIST)
2205 static int safe_mkdir(const char *base_path, char *path, int mode)
2207 RAII_VAR(char *, absolute_path, NULL, ast_std_free);
2209 absolute_path = realpath(path, NULL);
2211 if (absolute_path) {
2212 /* Path exists, but is it in the right place? */
2213 if (!ast_begins_with(absolute_path, base_path)) {
2217 /* It is in the right place! */
2220 /* Path doesn't exist. */
2222 /* The slash terminating the subpath we're checking */
2223 char *path_term = strchr(path, '/');
2224 /* True indicates the parent path is within base_path */
2225 int parent_is_safe = 0;
2229 RAII_VAR(char *, absolute_subpath, NULL, ast_std_free);
2231 /* Truncate the path one past the slash */
2232 char c = *(path_term + 1);
2233 *(path_term + 1) = '\0';
2234 absolute_subpath = realpath(path, NULL);
2236 if (absolute_subpath) {
2237 /* Subpath exists, but is it safe? */
2238 parent_is_safe = ast_begins_with(
2239 absolute_subpath, base_path);
2240 } else if (parent_is_safe) {
2241 /* Subpath does not exist, but parent is safe
2243 res = mkdir(path, mode);
2245 ast_assert(errno != EEXIST);
2249 /* Subpath did not exist, parent was not safe
2254 /* Restore the path */
2255 *(path_term + 1) = c;
2256 /* Move on to the next slash */
2257 path_term = strchr(path_term + 1, '/');
2260 /* Now to build the final path, but only if it's safe */
2261 if (!parent_is_safe) {
2266 res = mkdir(path, mode);
2267 if (res != 0 && errno != EEXIST) {
2275 int ast_safe_mkdir(const char *base_path, const char *path, int mode)
2277 RAII_VAR(char *, absolute_base_path, NULL, ast_std_free);
2278 RAII_VAR(char *, p, NULL, ast_free);
2280 if (base_path == NULL || path == NULL) {
2285 p = ast_strdup(path);
2291 absolute_base_path = realpath(base_path, NULL);
2292 if (absolute_base_path == NULL) {
2296 return safe_mkdir(absolute_base_path, p, mode);
2299 static void utils_shutdown(void)
2301 close(dev_urandom_fd);
2302 dev_urandom_fd = -1;
2303 #if defined(DEBUG_THREADS) && !defined(LOW_MEMORY)
2304 ast_cli_unregister_multiple(utils_cli, ARRAY_LEN(utils_cli));
2308 int ast_utils_init(void)
2310 dev_urandom_fd = open("/dev/urandom", O_RDONLY);
2312 #ifdef DEBUG_THREADS
2313 #if !defined(LOW_MEMORY)
2314 ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
2317 ast_register_atexit(utils_shutdown);
2323 *\brief Parse digest authorization header.
2324 *\return Returns -1 if we have no auth or something wrong with digest.
2325 *\note This function may be used for Digest request and responce header.
2326 * request arg is set to nonzero, if we parse Digest Request.
2327 * pedantic arg can be set to nonzero if we need to do addition Digest check.
2329 int ast_parse_digest(const char *digest, struct ast_http_digest *d, int request, int pedantic) {
2331 struct ast_str *str = ast_str_create(16);
2333 /* table of recognised keywords, and places where they should be copied */
2336 const ast_string_field *field;
2338 { "username=", &d->username },
2339 { "realm=", &d->realm },
2340 { "nonce=", &d->nonce },
2341 { "uri=", &d->uri },
2342 { "domain=", &d->domain },
2343 { "response=", &d->response },
2344 { "cnonce=", &d->cnonce },
2345 { "opaque=", &d->opaque },
2346 /* Special cases that cannot be directly copied */
2347 { "algorithm=", NULL },
2353 if (ast_strlen_zero(digest) || !d || !str) {
2358 ast_str_set(&str, 0, "%s", digest);
2360 c = ast_skip_blanks(ast_str_buffer(str));
2362 if (strncasecmp(c, "Digest ", strlen("Digest "))) {
2363 ast_log(LOG_WARNING, "Missing Digest.\n");
2367 c += strlen("Digest ");
2369 /* lookup for keys/value pair */
2370 while (c && *c && *(c = ast_skip_blanks(c))) {
2372 for (i = keys; i->key != NULL; i++) {
2373 char *src, *separator;
2375 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
2379 /* Found. Skip keyword, take text in quotes or up to the separator. */
2380 c += strlen(i->key);
2389 strsep(&c, separator); /* clear separator and move ptr */
2391 ast_unescape_c(src);
2394 ast_string_field_ptr_set(d, i->field, src);
2396 /* Special cases that require additional procesing */
2397 if (!strcasecmp(i->key, "algorithm=")) {
2398 if (strcasecmp(src, "MD5")) {
2399 ast_log(LOG_WARNING, "Digest algorithm: \"%s\" not supported.\n", src);
2403 } else if (!strcasecmp(i->key, "qop=") && !strcasecmp(src, "auth")) {
2405 } else if (!strcasecmp(i->key, "nc=")) {
2407 if (sscanf(src, "%30lx", &u) != 1) {
2408 ast_log(LOG_WARNING, "Incorrect Digest nc value: \"%s\".\n", src);
2412 ast_string_field_set(d, nc, src);
2417 if (i->key == NULL) { /* not found, try ',' */
2423 /* Digest checkout */
2424 if (ast_strlen_zero(d->realm) || ast_strlen_zero(d->nonce)) {
2425 /* "realm" and "nonce" MUST be always exist */
2430 /* Additional check for Digest response */
2431 if (ast_strlen_zero(d->username) || ast_strlen_zero(d->uri) || ast_strlen_zero(d->response)) {
2435 if (pedantic && d->qop && (ast_strlen_zero(d->cnonce) || ast_strlen_zero(d->nc))) {
2443 #ifndef __AST_DEBUG_MALLOC
2444 int _ast_asprintf(char **ret, const char *file, int lineno, const char *func, const char *fmt, ...)
2450 if ((res = vasprintf(ret, fmt, ap)) == -1) {
2459 int ast_get_tid(void)
2462 #if defined (__linux) && defined(SYS_gettid)
2463 ret = syscall(SYS_gettid); /* available since Linux 1.4.11 */
2464 #elif defined(__sun)
2465 ret = pthread_self();
2466 #elif defined(__APPLE__)
2467 ret = mach_thread_self();
2468 mach_port_deallocate(mach_task_self(), ret);
2469 #elif defined(__FreeBSD__) && defined(HAVE_SYS_THR_H)
2471 thr_self(&lwpid); /* available since sys/thr.h creation 2003 */
2477 char *ast_utils_which(const char *binary, char *fullpath, size_t fullpath_size)
2479 const char *envPATH = getenv("PATH");
2485 tpath = ast_strdupa(envPATH);
2486 while ((path = strsep(&tpath, ":"))) {
2487 snprintf(fullpath, fullpath_size, "%s/%s", path, binary);
2488 if (!stat(fullpath, &unused)) {
2495 void ast_do_crash(void)
2497 #if defined(DO_CRASH)
2500 * Just in case abort() doesn't work or something else super
2501 * silly, and for Qwell's amusement.
2504 #endif /* defined(DO_CRASH) */
2507 #if defined(AST_DEVMODE)
2508 void __ast_assert_failed(int condition, const char *condition_str, const char *file, int line, const char *function)
2511 * Attempt to put it into the logger, but hope that at least
2512 * someone saw the message on stderr ...
2514 ast_log(__LOG_ERROR, file, line, function, "FRACK!, Failed assertion %s (%d)\n",
2515 condition_str, condition);
2516 fprintf(stderr, "FRACK!, Failed assertion %s (%d) at line %d in %s of %s\n",
2517 condition_str, condition, line, function, file);
2519 * Give the logger a chance to get the message out, just in case
2520 * we abort(), or Asterisk crashes due to whatever problem just
2521 * happened after we exit ast_assert().
2526 #endif /* defined(AST_DEVMODE) */