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$")
40 #include <sys/syscall.h>
41 #if defined(__APPLE__)
42 #include <mach/mach.h>
43 #elif defined(HAVE_SYS_THR_H)
47 #include "asterisk/network.h"
49 #define AST_API_MODULE /* ensure that inlinable API functions will be built in lock.h if required */
50 #include "asterisk/lock.h"
51 #include "asterisk/io.h"
52 #include "asterisk/md5.h"
53 #include "asterisk/sha1.h"
54 #include "asterisk/cli.h"
55 #include "asterisk/linkedlists.h"
57 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
58 #include "asterisk/strings.h"
60 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
61 #include "asterisk/time.h"
63 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
64 #include "asterisk/stringfields.h"
66 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
67 #include "asterisk/utils.h"
69 #define AST_API_MODULE
70 #include "asterisk/threadstorage.h"
72 #define AST_API_MODULE
73 #include "asterisk/config.h"
75 static char base64[64];
78 AST_THREADSTORAGE(inet_ntoa_buf);
80 #if !defined(HAVE_GETHOSTBYNAME_R_5) && !defined(HAVE_GETHOSTBYNAME_R_6)
82 #define ERANGE 34 /*!< duh? ERANGE value copied from web... */
85 AST_MUTEX_DEFINE_STATIC(__mutex);
87 /*! \brief Reentrant replacement for gethostbyname for BSD-based systems.
89 routine is derived from code originally written and placed in the public
90 domain by Enzo Michelangeli <em@em.no-ip.com> */
92 static int gethostbyname_r (const char *name, struct hostent *ret, char *buf,
93 size_t buflen, struct hostent **result,
98 ast_mutex_lock(&__mutex); /* begin critical area */
101 ph = gethostbyname(name);
102 *h_errnop = h_errno; /* copy h_errno to *h_herrnop */
109 int naddr = 0, naliases = 0;
110 /* determine if we have enough space in buf */
112 /* count how many addresses */
113 for (p = ph->h_addr_list; *p != 0; p++) {
114 nbytes += ph->h_length; /* addresses */
115 nbytes += sizeof(*p); /* pointers */
118 nbytes += sizeof(*p); /* one more for the terminating NULL */
120 /* count how many aliases, and total length of strings */
121 for (p = ph->h_aliases; *p != 0; p++) {
122 nbytes += (strlen(*p)+1); /* aliases */
123 nbytes += sizeof(*p); /* pointers */
126 nbytes += sizeof(*p); /* one more for the terminating NULL */
128 /* here nbytes is the number of bytes required in buffer */
129 /* as a terminator must be there, the minimum value is ph->h_length */
130 if (nbytes > buflen) {
132 ast_mutex_unlock(&__mutex); /* end critical area */
133 return ERANGE; /* not enough space in buf!! */
136 /* There is enough space. Now we need to do a deep copy! */
137 /* Allocation in buffer:
138 from [0] to [(naddr-1) * sizeof(*p)]:
139 pointers to addresses
140 at [naddr * sizeof(*p)]:
142 from [(naddr+1) * sizeof(*p)] to [(naddr+naliases) * sizeof(*p)] :
144 at [(naddr+naliases+1) * sizeof(*p)]:
146 then naddr addresses (fixed length), and naliases aliases (asciiz).
149 *ret = *ph; /* copy whole structure (not its address!) */
152 q = (char **)buf; /* pointer to pointers area (type: char **) */
153 ret->h_addr_list = q; /* update pointer to address list */
154 pbuf = buf + ((naddr + naliases + 2) * sizeof(*p)); /* skip that area */
155 for (p = ph->h_addr_list; *p != 0; p++) {
156 memcpy(pbuf, *p, ph->h_length); /* copy address bytes */
157 *q++ = pbuf; /* the pointer is the one inside buf... */
158 pbuf += ph->h_length; /* advance pbuf */
160 *q++ = NULL; /* address list terminator */
163 ret->h_aliases = q; /* update pointer to aliases list */
164 for (p = ph->h_aliases; *p != 0; p++) {
165 strcpy(pbuf, *p); /* copy alias strings */
166 *q++ = pbuf; /* the pointer is the one inside buf... */
167 pbuf += strlen(*p); /* advance pbuf */
168 *pbuf++ = 0; /* string terminator */
170 *q++ = NULL; /* terminator */
172 strcpy(pbuf, ph->h_name); /* copy alias strings */
174 pbuf += strlen(ph->h_name); /* advance pbuf */
175 *pbuf++ = 0; /* string terminator */
177 *result = ret; /* and let *result point to structure */
180 h_errno = hsave; /* restore h_errno */
181 ast_mutex_unlock(&__mutex); /* end critical area */
183 return (*result == NULL); /* return 0 on success, non-zero on error */
189 /*! \brief Re-entrant (thread safe) version of gethostbyname that replaces the
190 standard gethostbyname (which is not thread safe)
192 struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp)
198 struct hostent *result = NULL;
199 /* Although it is perfectly legitimate to lookup a pure integer, for
200 the sake of the sanity of people who like to name their peers as
201 integers, we break with tradition and refuse to look up a
208 else if (!isdigit(*s))
213 /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
216 memset(hp, 0, sizeof(struct ast_hostent));
217 hp->hp.h_addrtype = AF_INET;
218 hp->hp.h_addr_list = (void *) hp->buf;
219 hp->hp.h_addr = hp->buf + sizeof(void *);
220 /* For AF_INET, this will always be 4 */
222 if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
227 #ifdef HAVE_GETHOSTBYNAME_R_5
228 result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);
230 if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
233 res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
235 if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
241 /*! \brief Produce 32 char MD5 hash of value. */
242 void ast_md5_hash(char *output, const char *input)
244 struct MD5Context md5;
245 unsigned char digest[16];
250 MD5Update(&md5, (const unsigned char *) input, strlen(input));
251 MD5Final(digest, &md5);
253 for (x = 0; x < 16; x++)
254 ptr += sprintf(ptr, "%2.2x", digest[x]);
257 /*! \brief Produce 40 char SHA1 hash of value. */
258 void ast_sha1_hash(char *output, const char *input)
260 struct SHA1Context sha;
263 uint8_t Message_Digest[20];
267 SHA1Input(&sha, (const unsigned char *) input, strlen(input));
269 SHA1Result(&sha, Message_Digest);
271 for (x = 0; x < 20; x++)
272 ptr += sprintf(ptr, "%2.2x", Message_Digest[x]);
275 /*! \brief Produce a 20 byte SHA1 hash of value. */
276 void ast_sha1_hash_uint(uint8_t *digest, const char *input)
278 struct SHA1Context sha;
282 SHA1Input(&sha, (const unsigned char *) input, strlen(input));
284 SHA1Result(&sha, digest);
287 /*! \brief decode BASE64 encoded text */
288 int ast_base64decode(unsigned char *dst, const char *src, int max)
291 unsigned int byte = 0;
292 unsigned int bits = 0;
294 while(*src && *src != '=' && (cnt < max)) {
295 /* Shift in 6 bits of input */
297 byte |= (b2a[(int)(*src)]) & 0x3f;
301 /* If we have at least 8 bits left over, take that character
305 *dst = (byte >> bits) & 0xff;
310 /* Don't worry about left over bits, they're extra anyway */
314 /*! \brief encode text to BASE64 coding */
315 int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
319 unsigned int byte = 0;
322 /* Reserve space for null byte at end of string */
324 while ((cntin < srclen) && (cnt < max)) {
329 if ((bits == 24) && (cnt + 4 <= max)) {
330 *dst++ = base64[(byte >> 18) & 0x3f];
331 *dst++ = base64[(byte >> 12) & 0x3f];
332 *dst++ = base64[(byte >> 6) & 0x3f];
333 *dst++ = base64[byte & 0x3f];
339 if (linebreaks && (cnt < max) && (col == 64)) {
345 if (bits && (cnt + 4 <= max)) {
346 /* Add one last character for the remaining bits,
347 padding the rest with 0 */
349 *dst++ = base64[(byte >> 18) & 0x3f];
350 *dst++ = base64[(byte >> 12) & 0x3f];
352 *dst++ = base64[(byte >> 6) & 0x3f];
358 if (linebreaks && (cnt < max)) {
366 int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
368 return ast_base64encode_full(dst, src, srclen, max, 0);
371 static void base64_init(void)
374 memset(b2a, -1, sizeof(b2a));
375 /* Initialize base-64 Conversion table */
376 for (x = 0; x < 26; x++) {
381 base64[x + 26] = 'a' + x;
382 b2a['a' + x] = x + 26;
385 base64[x + 52] = '0' + x;
386 b2a['0' + x] = x + 52;
395 const struct ast_flags ast_uri_http = {AST_URI_UNRESERVED};
396 const struct ast_flags ast_uri_http_legacy = {AST_URI_LEGACY_SPACE | AST_URI_UNRESERVED};
397 const struct ast_flags ast_uri_sip_user = {AST_URI_UNRESERVED | AST_URI_SIP_USER_UNRESERVED};
399 char *ast_uri_encode(const char *string, char *outbuf, int buflen, struct ast_flags spec)
401 const char *ptr = string; /* Start with the string */
403 const char *mark = "-_.!~*'()"; /* no encode set, RFC 2396 section 2.3, RFC 3261 sec 25 */
404 const char *user_unreserved = "&=+$,;?/"; /* user-unreserved set, RFC 3261 sec 25 */
406 while (*ptr && out - outbuf < buflen - 1) {
407 if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *ptr == ' ') {
408 /* for legacy encoding, encode spaces as '+' */
411 } else if (!(ast_test_flag(&spec, AST_URI_MARK)
412 && strchr(mark, *ptr))
413 && !(ast_test_flag(&spec, AST_URI_ALPHANUM)
414 && ((*ptr >= '0' && *ptr <= '9')
415 || (*ptr >= 'A' && *ptr <= 'Z')
416 || (*ptr >= 'a' && *ptr <= 'z')))
417 && !(ast_test_flag(&spec, AST_URI_SIP_USER_UNRESERVED)
418 && strchr(user_unreserved, *ptr))) {
420 if (out - outbuf >= buflen - 3) {
423 out += sprintf(out, "%%%02X", (unsigned char) *ptr);
425 *out = *ptr; /* Continue copying the string */
438 void ast_uri_decode(char *s, struct ast_flags spec)
443 for (o = s; *s; s++, o++) {
444 if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *s == '+') {
445 /* legacy mode, decode '+' as space */
447 } else if (*s == '%' && s[1] != '\0' && s[2] != '\0' && sscanf(s + 1, "%2x", &tmp) == 1) {
448 /* have '%', two chars and correct parsing */
450 s += 2; /* Will be incremented once more when we break out */
451 } else /* all other cases, just copy */
457 char *ast_escape_quoted(const char *string, char *outbuf, int buflen)
459 const char *ptr = string;
461 char *allow = "\t\v !"; /* allow LWS (minus \r and \n) and "!" */
463 while (*ptr && out - outbuf < buflen - 1) {
464 if (!(strchr(allow, *ptr))
465 && !(*ptr >= '#' && *ptr <= '[') /* %x23 - %x5b */
466 && !(*ptr >= ']' && *ptr <= '~') /* %x5d - %x7e */
467 && !((unsigned char) *ptr > 0x7f)) { /* UTF8-nonascii */
469 if (out - outbuf >= buflen - 2) {
472 out += sprintf(out, "\\%c", (unsigned char) *ptr);
486 int ast_xml_escape(const char *string, char * const outbuf, const size_t buflen)
489 char *end = outbuf + buflen - 1; /* save one for the null terminator */
491 /* Handle the case for the empty output buffer */
496 /* Escaping rules from http://www.w3.org/TR/REC-xml/#syntax */
497 /* This also prevents partial entities at the end of a string */
498 while (*string && dst < end) {
499 const char *entity = NULL;
512 /* necessary if ]]> is in the string; easier to escape them all */
517 /* necessary in single-quoted strings; easier to escape them all */
522 /* necessary in double-quoted strings; easier to escape them all */
532 ast_assert(len == strlen(entity));
533 if (end - dst < len) {
534 /* no room for the entity; stop */
537 /* just checked for length; strcpy is fine */
543 /* Write null terminator */
545 /* If any chars are left in string, return failure */
546 return *string == '\0' ? 0 : -1;
549 /*! \brief ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa */
550 const char *ast_inet_ntoa(struct in_addr ia)
554 if (!(buf = ast_threadstorage_get(&inet_ntoa_buf, INET_ADDRSTRLEN)))
557 return inet_ntop(AF_INET, &ia, buf, INET_ADDRSTRLEN);
560 static int dev_urandom_fd;
563 #undef pthread_create /* For ast_pthread_create function only */
564 #endif /* !__linux__ */
566 #if !defined(LOW_MEMORY)
570 /*! \brief A reasonable maximum number of locks a thread would be holding ... */
571 #define AST_MAX_LOCKS 64
573 /* Allow direct use of pthread_mutex_t and friends */
574 #undef pthread_mutex_t
575 #undef pthread_mutex_lock
576 #undef pthread_mutex_unlock
577 #undef pthread_mutex_init
578 #undef pthread_mutex_destroy
581 * \brief Keep track of which locks a thread holds
583 * There is an instance of this struct for every active thread
585 struct thr_lock_info {
586 /*! The thread's ID */
588 /*! The thread name which includes where the thread was started */
589 const char *thread_name;
590 /*! This is the actual container of info for what locks this thread holds */
595 const char *lock_name;
598 enum ast_lock_type type;
599 /*! This thread is waiting on this lock */
602 struct ast_bt *backtrace;
604 } locks[AST_MAX_LOCKS];
605 /*! This is the number of locks currently held by this thread.
606 * The index (num_locks - 1) has the info on the last one in the
608 unsigned int num_locks;
609 /*! Protects the contents of the locks member
610 * Intentionally not ast_mutex_t */
611 pthread_mutex_t lock;
612 AST_LIST_ENTRY(thr_lock_info) entry;
616 * \brief Locked when accessing the lock_infos list
618 AST_MUTEX_DEFINE_STATIC(lock_infos_lock);
620 * \brief A list of each thread's lock info
622 static AST_LIST_HEAD_NOLOCK_STATIC(lock_infos, thr_lock_info);
625 * \brief Destroy a thread's lock info
627 * This gets called automatically when the thread stops
629 static void lock_info_destroy(void *data)
631 struct thr_lock_info *lock_info = data;
634 pthread_mutex_lock(&lock_infos_lock.mutex);
635 AST_LIST_REMOVE(&lock_infos, lock_info, entry);
636 pthread_mutex_unlock(&lock_infos_lock.mutex);
639 for (i = 0; i < lock_info->num_locks; i++) {
640 if (lock_info->locks[i].pending == -1) {
641 /* This just means that the last lock this thread went for was by
642 * using trylock, and it failed. This is fine. */
647 "Thread '%s' still has a lock! - '%s' (%p) from '%s' in %s:%d!\n",
648 lock_info->thread_name,
649 lock_info->locks[i].lock_name,
650 lock_info->locks[i].lock_addr,
651 lock_info->locks[i].func,
652 lock_info->locks[i].file,
653 lock_info->locks[i].line_num
657 pthread_mutex_destroy(&lock_info->lock);
658 if (lock_info->thread_name)
659 free((void *) lock_info->thread_name);
664 * \brief The thread storage key for per-thread lock info
666 AST_THREADSTORAGE_CUSTOM(thread_lock_info, NULL, lock_info_destroy);
668 void ast_store_lock_info(enum ast_lock_type type, const char *filename,
669 int line_num, const char *func, const char *lock_name, void *lock_addr, struct ast_bt *bt)
671 void ast_store_lock_info(enum ast_lock_type type, const char *filename,
672 int line_num, const char *func, const char *lock_name, void *lock_addr)
675 struct thr_lock_info *lock_info;
678 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
681 pthread_mutex_lock(&lock_info->lock);
683 for (i = 0; i < lock_info->num_locks; i++) {
684 if (lock_info->locks[i].lock_addr == lock_addr) {
685 lock_info->locks[i].times_locked++;
687 lock_info->locks[i].backtrace = bt;
689 pthread_mutex_unlock(&lock_info->lock);
694 if (lock_info->num_locks == AST_MAX_LOCKS) {
695 /* Can't use ast_log here, because it will cause infinite recursion */
696 fprintf(stderr, "XXX ERROR XXX A thread holds more locks than '%d'."
697 " Increase AST_MAX_LOCKS!\n", AST_MAX_LOCKS);
698 pthread_mutex_unlock(&lock_info->lock);
702 if (i && lock_info->locks[i - 1].pending == -1) {
703 /* The last lock on the list was one that this thread tried to lock but
704 * failed at doing so. It has now moved on to something else, so remove
705 * the old lock from the list. */
707 lock_info->num_locks--;
708 memset(&lock_info->locks[i], 0, sizeof(lock_info->locks[0]));
711 lock_info->locks[i].file = filename;
712 lock_info->locks[i].line_num = line_num;
713 lock_info->locks[i].func = func;
714 lock_info->locks[i].lock_name = lock_name;
715 lock_info->locks[i].lock_addr = lock_addr;
716 lock_info->locks[i].times_locked = 1;
717 lock_info->locks[i].type = type;
718 lock_info->locks[i].pending = 1;
720 lock_info->locks[i].backtrace = bt;
722 lock_info->num_locks++;
724 pthread_mutex_unlock(&lock_info->lock);
727 void ast_mark_lock_acquired(void *lock_addr)
729 struct thr_lock_info *lock_info;
731 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
734 pthread_mutex_lock(&lock_info->lock);
735 if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
736 lock_info->locks[lock_info->num_locks - 1].pending = 0;
738 pthread_mutex_unlock(&lock_info->lock);
741 void ast_mark_lock_failed(void *lock_addr)
743 struct thr_lock_info *lock_info;
745 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
748 pthread_mutex_lock(&lock_info->lock);
749 if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
750 lock_info->locks[lock_info->num_locks - 1].pending = -1;
751 lock_info->locks[lock_info->num_locks - 1].times_locked--;
753 pthread_mutex_unlock(&lock_info->lock);
756 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)
758 struct thr_lock_info *lock_info;
761 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
764 pthread_mutex_lock(&lock_info->lock);
766 for (i = lock_info->num_locks - 1; i >= 0; i--) {
767 if (lock_info->locks[i].lock_addr == lock_addr)
772 /* Lock not found :( */
773 pthread_mutex_unlock(&lock_info->lock);
777 ast_copy_string(filename, lock_info->locks[i].file, filename_size);
778 *lineno = lock_info->locks[i].line_num;
779 ast_copy_string(func, lock_info->locks[i].func, func_size);
780 ast_copy_string(mutex_name, lock_info->locks[i].lock_name, mutex_name_size);
782 pthread_mutex_unlock(&lock_info->lock);
788 void ast_remove_lock_info(void *lock_addr, struct ast_bt *bt)
790 void ast_remove_lock_info(void *lock_addr)
793 struct thr_lock_info *lock_info;
796 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
799 pthread_mutex_lock(&lock_info->lock);
801 for (i = lock_info->num_locks - 1; i >= 0; i--) {
802 if (lock_info->locks[i].lock_addr == lock_addr)
807 /* Lock not found :( */
808 pthread_mutex_unlock(&lock_info->lock);
812 if (lock_info->locks[i].times_locked > 1) {
813 lock_info->locks[i].times_locked--;
815 lock_info->locks[i].backtrace = bt;
817 pthread_mutex_unlock(&lock_info->lock);
821 if (i < lock_info->num_locks - 1) {
822 /* Not the last one ... *should* be rare! */
823 memmove(&lock_info->locks[i], &lock_info->locks[i + 1],
824 (lock_info->num_locks - (i + 1)) * sizeof(lock_info->locks[0]));
827 lock_info->num_locks--;
829 pthread_mutex_unlock(&lock_info->lock);
832 static const char *locktype2str(enum ast_lock_type type)
847 static void append_backtrace_information(struct ast_str **str, struct ast_bt *bt)
853 ast_str_append(str, 0, "\tNo backtrace to print\n");
857 /* store frame count locally to avoid the memory corruption that
858 * sometimes happens on virtualized CentOS 6.x systems */
859 num_frames = bt->num_frames;
860 if ((symbols = ast_bt_get_symbols(bt->addresses, num_frames))) {
863 for (frame_iterator = 0; frame_iterator < num_frames; ++frame_iterator) {
864 ast_str_append(str, 0, "\t%s\n", symbols[frame_iterator]);
869 ast_str_append(str, 0, "\tCouldn't retrieve backtrace symbols\n");
874 static void append_lock_information(struct ast_str **str, struct thr_lock_info *lock_info, int i)
878 struct ast_lock_track *lt;
880 ast_str_append(str, 0, "=== ---> %sLock #%d (%s): %s %d %s %s %p (%d)\n",
881 lock_info->locks[i].pending > 0 ? "Waiting for " :
882 lock_info->locks[i].pending < 0 ? "Tried and failed to get " : "", i,
883 lock_info->locks[i].file,
884 locktype2str(lock_info->locks[i].type),
885 lock_info->locks[i].line_num,
886 lock_info->locks[i].func, lock_info->locks[i].lock_name,
887 lock_info->locks[i].lock_addr,
888 lock_info->locks[i].times_locked);
890 append_backtrace_information(str, lock_info->locks[i].backtrace);
893 if (!lock_info->locks[i].pending || lock_info->locks[i].pending == -1)
896 /* We only have further details for mutexes right now */
897 if (lock_info->locks[i].type != AST_MUTEX)
900 lock = lock_info->locks[i].lock_addr;
902 ast_reentrancy_lock(lt);
903 for (j = 0; *str && j < lt->reentrancy; j++) {
904 ast_str_append(str, 0, "=== --- ---> Locked Here: %s line %d (%s)\n",
905 lt->file[j], lt->lineno[j], lt->func[j]);
907 ast_reentrancy_unlock(lt);
911 /*! This function can help you find highly temporal locks; locks that happen for a
912 short time, but at unexpected times, usually at times that create a deadlock,
913 Why is this thing locked right then? Who is locking it? Who am I fighting
916 To answer such questions, just call this routine before you would normally try
917 to aquire a lock. It doesn't do anything if the lock is not acquired. If the
918 lock is taken, it will publish a line or two to the console via ast_log().
920 Sometimes, the lock message is pretty uninformative. For instance, you might
921 find that the lock is being aquired deep within the astobj2 code; this tells
922 you little about higher level routines that call the astobj2 routines.
923 But, using gdb, you can set a break at the ast_log below, and for that
924 breakpoint, you can set the commands:
927 which will give a stack trace and continue. -- that aught to do the job!
930 void log_show_lock(void *this_lock_addr)
932 struct thr_lock_info *lock_info;
935 if (!(str = ast_str_create(4096))) {
936 ast_log(LOG_NOTICE,"Could not create str\n");
941 pthread_mutex_lock(&lock_infos_lock.mutex);
942 AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
944 pthread_mutex_lock(&lock_info->lock);
945 for (i = 0; str && i < lock_info->num_locks; i++) {
946 /* ONLY show info about this particular lock, if
948 if (lock_info->locks[i].lock_addr == this_lock_addr) {
949 append_lock_information(&str, lock_info, i);
950 ast_log(LOG_NOTICE, "%s", ast_str_buffer(str));
954 pthread_mutex_unlock(&lock_info->lock);
956 pthread_mutex_unlock(&lock_infos_lock.mutex);
961 static char *handle_show_locks(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
963 struct thr_lock_info *lock_info;
966 if (!(str = ast_str_create(4096)))
971 e->command = "core show locks";
973 "Usage: core show locks\n"
974 " This command is for lock debugging. It prints out which locks\n"
975 "are owned by each active thread.\n";
982 ast_str_append(&str, 0, "\n"
983 "=======================================================================\n"
984 "=== Currently Held Locks ==============================================\n"
985 "=======================================================================\n"
987 "=== <pending> <lock#> (<file>): <lock type> <line num> <function> <lock name> <lock addr> (times locked)\n"
993 pthread_mutex_lock(&lock_infos_lock.mutex);
994 AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
996 if (lock_info->num_locks) {
997 ast_str_append(&str, 0, "=== Thread ID: 0x%lx (%s)\n", (long) lock_info->thread_id,
998 lock_info->thread_name);
999 pthread_mutex_lock(&lock_info->lock);
1000 for (i = 0; str && i < lock_info->num_locks; i++) {
1001 append_lock_information(&str, lock_info, i);
1003 pthread_mutex_unlock(&lock_info->lock);
1006 ast_str_append(&str, 0, "=== -------------------------------------------------------------------\n"
1012 pthread_mutex_unlock(&lock_infos_lock.mutex);
1017 ast_str_append(&str, 0, "=======================================================================\n"
1023 ast_cli(a->fd, "%s", ast_str_buffer(str));
1030 static struct ast_cli_entry utils_cli[] = {
1031 AST_CLI_DEFINE(handle_show_locks, "Show which locks are held by which thread"),
1034 #endif /* DEBUG_THREADS */
1037 * support for 'show threads'. The start routine is wrapped by
1038 * dummy_start(), so that ast_register_thread() and
1039 * ast_unregister_thread() know the thread identifier.
1042 void *(*start_routine)(void *);
1048 * on OS/X, pthread_cleanup_push() and pthread_cleanup_pop()
1049 * are odd macros which start and end a block, so they _must_ be
1050 * used in pairs (the latter with a '1' argument to call the
1052 * On BSD we don't need this, but we keep it for compatibility.
1054 static void *dummy_start(void *data)
1057 struct thr_arg a = *((struct thr_arg *) data); /* make a local copy */
1058 #ifdef DEBUG_THREADS
1059 struct thr_lock_info *lock_info;
1060 pthread_mutexattr_t mutex_attr;
1062 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
1065 lock_info->thread_id = pthread_self();
1066 lock_info->thread_name = strdup(a.name);
1068 pthread_mutexattr_init(&mutex_attr);
1069 pthread_mutexattr_settype(&mutex_attr, AST_MUTEX_KIND);
1070 pthread_mutex_init(&lock_info->lock, &mutex_attr);
1071 pthread_mutexattr_destroy(&mutex_attr);
1073 pthread_mutex_lock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
1074 AST_LIST_INSERT_TAIL(&lock_infos, lock_info, entry);
1075 pthread_mutex_unlock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
1076 #endif /* DEBUG_THREADS */
1078 /* note that even though data->name is a pointer to allocated memory,
1079 we are not freeing it here because ast_register_thread is going to
1080 keep a copy of the pointer and then ast_unregister_thread will
1084 ast_register_thread(a.name);
1085 pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
1087 ret = a.start_routine(a.data);
1089 pthread_cleanup_pop(1);
1094 #endif /* !LOW_MEMORY */
1096 int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
1097 void *data, size_t stacksize, const char *file, const char *caller,
1098 int line, const char *start_fn)
1100 #if !defined(LOW_MEMORY)
1105 attr = ast_alloca(sizeof(*attr));
1106 pthread_attr_init(attr);
1110 /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
1111 which is kind of useless. Change this here to
1112 PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
1113 priority will propagate down to new threads by default.
1114 This does mean that callers cannot set a different priority using
1115 PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
1116 the priority afterwards with pthread_setschedparam(). */
1117 if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
1118 ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
1122 stacksize = AST_STACKSIZE;
1124 if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
1125 ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
1127 #if !defined(LOW_MEMORY)
1128 if ((a = ast_malloc(sizeof(*a)))) {
1129 a->start_routine = start_routine;
1131 start_routine = dummy_start;
1132 if (ast_asprintf(&a->name, "%-20s started at [%5d] %s %s()",
1133 start_fn, line, file, caller) < 0) {
1138 #endif /* !LOW_MEMORY */
1140 return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
1144 int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
1145 void *data, size_t stacksize, const char *file, const char *caller,
1146 int line, const char *start_fn)
1148 unsigned char attr_destroy = 0;
1152 attr = ast_alloca(sizeof(*attr));
1153 pthread_attr_init(attr);
1157 if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
1158 ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
1160 res = ast_pthread_create_stack(thread, attr, start_routine, data,
1161 stacksize, file, caller, line, start_fn);
1164 pthread_attr_destroy(attr);
1169 int ast_wait_for_input(int fd, int ms)
1171 struct pollfd pfd[1];
1172 memset(pfd, 0, sizeof(pfd));
1174 pfd[0].events = POLLIN|POLLPRI;
1175 return ast_poll(pfd, 1, ms);
1178 static int ast_wait_for_output(int fd, int timeoutms)
1180 struct pollfd pfd = {
1185 struct timeval start = ast_tvnow();
1188 /* poll() until the fd is writable without blocking */
1189 while ((res = ast_poll(&pfd, 1, timeoutms - elapsed)) <= 0) {
1193 ast_debug(1, "Timed out trying to write\n");
1196 } else if (res == -1) {
1197 /* poll() returned an error, check to see if it was fatal */
1199 if (errno == EINTR || errno == EAGAIN) {
1200 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1201 if (elapsed >= timeoutms) {
1204 /* This was an acceptable error, go back into poll() */
1208 /* Fatal error, bail. */
1209 ast_log(LOG_ERROR, "poll returned error: %s\n", strerror(errno));
1213 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1214 if (elapsed >= timeoutms) {
1223 * Try to write string, but wait no more than ms milliseconds before timing out.
1225 * \note The code assumes that the file descriptor has NONBLOCK set,
1226 * so there is only one system call made to do a write, unless we actually
1227 * have a need to wait. This way, we get better performance.
1228 * If the descriptor is blocking, all assumptions on the guaranteed
1229 * detail do not apply anymore.
1231 int ast_carefulwrite(int fd, char *s, int len, int timeoutms)
1233 struct timeval start = ast_tvnow();
1238 if (ast_wait_for_output(fd, timeoutms - elapsed)) {
1242 res = write(fd, s, len);
1244 if (res < 0 && errno != EAGAIN && errno != EINTR) {
1245 /* fatal error from write() */
1246 ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
1251 /* It was an acceptable error */
1255 /* Update how much data we have left to write */
1260 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1261 if (elapsed >= timeoutms) {
1262 /* We've taken too long to write
1263 * This is only an error condition if we haven't finished writing. */
1272 int ast_careful_fwrite(FILE *f, int fd, const char *src, size_t len, int timeoutms)
1274 struct timeval start = ast_tvnow();
1279 if (ast_wait_for_output(fd, timeoutms - elapsed)) {
1280 /* poll returned a fatal error, so bail out immediately. */
1284 /* Clear any errors from a previous write */
1287 n = fwrite(src, 1, len, f);
1289 if (ferror(f) && errno != EINTR && errno != EAGAIN) {
1290 /* fatal error from fwrite() */
1292 /* Don't spam the logs if it was just that the connection is closed. */
1293 ast_log(LOG_ERROR, "fwrite() returned error: %s\n", strerror(errno));
1299 /* Update for data already written to the socket */
1303 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1304 if (elapsed >= timeoutms) {
1305 /* We've taken too long to write
1306 * This is only an error condition if we haven't finished writing. */
1313 if (errno == EAGAIN || errno == EINTR) {
1317 /* Don't spam the logs if it was just that the connection is closed. */
1318 ast_log(LOG_ERROR, "fflush() returned error: %s\n", strerror(errno));
1324 return n < 0 ? -1 : 0;
1327 char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
1333 if ((q = strchr(beg_quotes, *s)) && *q != '\0') {
1334 e = s + strlen(s) - 1;
1335 if (*e == *(end_quotes + (q - beg_quotes))) {
1344 char *ast_unescape_semicolon(char *s)
1349 while ((e = strchr(work, ';'))) {
1350 if ((e > work) && (*(e-1) == '\\')) {
1351 memmove(e - 1, e, strlen(e) + 1);
1361 /* !\brief unescape some C sequences in place, return pointer to the original string.
1363 char *ast_unescape_c(char *src)
1369 for (ret = dst = src; (c = *src++); *dst++ = c ) {
1371 continue; /* copy char at the end of the loop */
1372 switch ((c = *src++)) {
1373 case '\0': /* special, trailing '\' */
1376 case 'b': /* backspace */
1379 case 'f': /* form feed */
1392 /* default, use the char literally */
1398 int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap)
1402 if (!buffer || !*buffer || !space || !*space)
1405 result = vsnprintf(*buffer, *space, fmt, ap);
1409 else if (result > *space)
1417 int ast_build_string(char **buffer, size_t *space, const char *fmt, ...)
1423 result = ast_build_string_va(buffer, space, fmt, ap);
1429 int ast_regex_string_to_regex_pattern(const char *regex_string, struct ast_str **regex_pattern)
1431 int regex_len = strlen(regex_string);
1434 /* Chop off the leading / if there is one */
1435 if ((regex_len >= 1) && (regex_string[0] == '/')) {
1436 ast_str_set(regex_pattern, 0, "%s", regex_string + 1);
1440 /* Chop off the ending / if there is one */
1441 if ((regex_len > 1) && (regex_string[regex_len - 1] == '/')) {
1442 ast_str_truncate(*regex_pattern, -1);
1449 int ast_true(const char *s)
1451 if (ast_strlen_zero(s))
1454 /* Determine if this is a true value */
1455 if (!strcasecmp(s, "yes") ||
1456 !strcasecmp(s, "true") ||
1457 !strcasecmp(s, "y") ||
1458 !strcasecmp(s, "t") ||
1459 !strcasecmp(s, "1") ||
1460 !strcasecmp(s, "on"))
1466 int ast_false(const char *s)
1468 if (ast_strlen_zero(s))
1471 /* Determine if this is a false value */
1472 if (!strcasecmp(s, "no") ||
1473 !strcasecmp(s, "false") ||
1474 !strcasecmp(s, "n") ||
1475 !strcasecmp(s, "f") ||
1476 !strcasecmp(s, "0") ||
1477 !strcasecmp(s, "off"))
1483 #define ONE_MILLION 1000000
1485 * put timeval in a valid range. usec is 0..999999
1486 * negative values are not allowed and truncated.
1488 static struct timeval tvfix(struct timeval a)
1490 if (a.tv_usec >= ONE_MILLION) {
1491 ast_log(LOG_WARNING, "warning too large timestamp %ld.%ld\n",
1492 (long)a.tv_sec, (long int) a.tv_usec);
1493 a.tv_sec += a.tv_usec / ONE_MILLION;
1494 a.tv_usec %= ONE_MILLION;
1495 } else if (a.tv_usec < 0) {
1496 ast_log(LOG_WARNING, "warning negative timestamp %ld.%ld\n",
1497 (long)a.tv_sec, (long int) a.tv_usec);
1503 struct timeval ast_tvadd(struct timeval a, struct timeval b)
1505 /* consistency checks to guarantee usec in 0..999999 */
1508 a.tv_sec += b.tv_sec;
1509 a.tv_usec += b.tv_usec;
1510 if (a.tv_usec >= ONE_MILLION) {
1512 a.tv_usec -= ONE_MILLION;
1517 struct timeval ast_tvsub(struct timeval a, struct timeval b)
1519 /* consistency checks to guarantee usec in 0..999999 */
1522 a.tv_sec -= b.tv_sec;
1523 a.tv_usec -= b.tv_usec;
1524 if (a.tv_usec < 0) {
1526 a.tv_usec += ONE_MILLION;
1531 int ast_remaining_ms(struct timeval start, int max_ms)
1538 ms = max_ms - ast_tvdiff_ms(ast_tvnow(), start);
1550 AST_MUTEX_DEFINE_STATIC(randomlock);
1553 long int ast_random(void)
1557 if (dev_urandom_fd >= 0) {
1558 int read_res = read(dev_urandom_fd, &res, sizeof(res));
1560 long int rm = RAND_MAX;
1561 res = res < 0 ? ~res : res;
1567 /* XXX - Thread safety really depends on the libc, not the OS.
1569 * But... popular Linux libc's (uClibc, glibc, eglibc), all have a
1570 * somewhat thread safe random(3) (results are random, but not
1571 * reproducible). The libc's for other systems (BSD, et al.), not so
1577 ast_mutex_lock(&randomlock);
1579 ast_mutex_unlock(&randomlock);
1584 void ast_replace_subargument_delimiter(char *s)
1593 char *ast_process_quotes_and_slashes(char *start, char find, char replace_with)
1595 char *dataPut = start;
1599 for (; *start; start++) {
1601 *dataPut++ = *start; /* Always goes verbatim */
1604 if (*start == '\\') {
1605 inEscape = 1; /* Do not copy \ into the data */
1606 } else if (*start == '\'') {
1607 inQuotes = 1 - inQuotes; /* Do not copy ' into the data */
1609 /* Replace , with |, unless in quotes */
1610 *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
1614 if (start != dataPut)
1619 void ast_join(char *s, size_t len, const char * const w[])
1624 /* Join words into a string */
1627 for (x = 0; ofs < len && w[x]; x++) {
1630 for (src = w[x]; *src && ofs < len; src++)
1639 * stringfields support routines.
1642 /* this is a little complex... string fields are stored with their
1643 allocated size in the bytes preceding the string; even the
1644 constant 'empty' string has to be this way, so the code that
1645 checks to see if there is enough room for a new string doesn't
1646 have to have any special case checks
1649 static const struct {
1650 ast_string_field_allocation allocation;
1652 } __ast_string_field_empty_buffer;
1654 ast_string_field __ast_string_field_empty = __ast_string_field_empty_buffer.string;
1656 #define ALLOCATOR_OVERHEAD 48
1658 static size_t optimal_alloc_size(size_t size)
1662 size += ALLOCATOR_OVERHEAD;
1664 for (count = 1; size; size >>= 1, count++);
1666 return (1 << count) - ALLOCATOR_OVERHEAD;
1669 /*! \brief add a new block to the pool.
1670 * We can only allocate from the topmost pool, so the
1671 * fields in *mgr reflect the size of that only.
1673 static int add_string_pool(struct ast_string_field_mgr *mgr, struct ast_string_field_pool **pool_head,
1674 size_t size, const char *file, int lineno, const char *func)
1676 struct ast_string_field_pool *pool;
1677 size_t alloc_size = optimal_alloc_size(sizeof(*pool) + size);
1679 #if defined(__AST_DEBUG_MALLOC)
1680 if (!(pool = __ast_calloc(1, alloc_size, file, lineno, func))) {
1684 if (!(pool = ast_calloc(1, alloc_size))) {
1689 pool->prev = *pool_head;
1690 pool->size = alloc_size - sizeof(*pool);
1692 mgr->last_alloc = NULL;
1698 * This is an internal API, code should not use it directly.
1699 * It initializes all fields as empty, then uses 'size' for 3 functions:
1700 * size > 0 means initialize the pool list with a pool of given size.
1701 * This must be called right after allocating the object.
1702 * size = 0 means release all pools except the most recent one.
1703 * If the first pool was allocated via embedding in another
1704 * object, that pool will be preserved instead.
1705 * This is useful to e.g. reset an object to the initial value.
1706 * size < 0 means release all pools.
1707 * This must be done before destroying the object.
1709 int __ast_string_field_init(struct ast_string_field_mgr *mgr, struct ast_string_field_pool **pool_head,
1710 int needed, const char *file, int lineno, const char *func)
1712 const char **p = (const char **) pool_head + 1;
1713 struct ast_string_field_pool *cur = NULL;
1714 struct ast_string_field_pool *preserve = NULL;
1716 /* clear fields - this is always necessary */
1717 while ((struct ast_string_field_mgr *) p != mgr) {
1718 *p++ = __ast_string_field_empty;
1721 mgr->last_alloc = NULL;
1722 #if defined(__AST_DEBUG_MALLOC)
1723 mgr->owner_file = file;
1724 mgr->owner_func = func;
1725 mgr->owner_line = lineno;
1727 if (needed > 0) { /* allocate the initial pool */
1729 mgr->embedded_pool = NULL;
1730 return add_string_pool(mgr, pool_head, needed, file, lineno, func);
1733 /* if there is an embedded pool, we can't actually release *all*
1734 * pools, we must keep the embedded one. if the caller is about
1735 * to free the structure that contains the stringfield manager
1736 * and embedded pool anyway, it will be freed as part of that
1739 if ((needed < 0) && mgr->embedded_pool) {
1743 if (needed < 0) { /* reset all pools */
1745 } else if (mgr->embedded_pool) { /* preserve the embedded pool */
1746 preserve = mgr->embedded_pool;
1748 } else { /* preserve the last pool */
1749 if (*pool_head == NULL) {
1750 ast_log(LOG_WARNING, "trying to reset empty pool\n");
1753 preserve = *pool_head;
1754 cur = preserve->prev;
1758 preserve->prev = NULL;
1759 preserve->used = preserve->active = 0;
1763 struct ast_string_field_pool *prev = cur->prev;
1765 if (cur != preserve) {
1771 *pool_head = preserve;
1776 ast_string_field __ast_string_field_alloc_space(struct ast_string_field_mgr *mgr,
1777 struct ast_string_field_pool **pool_head, size_t needed)
1779 char *result = NULL;
1780 size_t space = (*pool_head)->size - (*pool_head)->used;
1783 /* Make room for ast_string_field_allocation and make it a multiple of that. */
1784 to_alloc = ast_make_room_for(needed, ast_string_field_allocation);
1785 ast_assert(to_alloc % ast_alignof(ast_string_field_allocation) == 0);
1787 if (__builtin_expect(to_alloc > space, 0)) {
1788 size_t new_size = (*pool_head)->size;
1790 while (new_size < to_alloc) {
1794 #if defined(__AST_DEBUG_MALLOC)
1795 if (add_string_pool(mgr, pool_head, new_size, mgr->owner_file, mgr->owner_line, mgr->owner_func))
1798 if (add_string_pool(mgr, pool_head, new_size, __FILE__, __LINE__, __FUNCTION__))
1803 /* pool->base is always aligned (gcc aligned attribute). We ensure that
1804 * to_alloc is also a multiple of ast_alignof(ast_string_field_allocation)
1805 * causing result to always be aligned as well; which in turn fixes that
1806 * AST_STRING_FIELD_ALLOCATION(result) is aligned. */
1807 result = (*pool_head)->base + (*pool_head)->used;
1808 (*pool_head)->used += to_alloc;
1809 (*pool_head)->active += needed;
1810 result += ast_alignof(ast_string_field_allocation);
1811 AST_STRING_FIELD_ALLOCATION(result) = needed;
1812 mgr->last_alloc = result;
1817 int __ast_string_field_ptr_grow(struct ast_string_field_mgr *mgr,
1818 struct ast_string_field_pool **pool_head, size_t needed,
1819 const ast_string_field *ptr)
1821 ssize_t grow = needed - AST_STRING_FIELD_ALLOCATION(*ptr);
1822 size_t space = (*pool_head)->size - (*pool_head)->used;
1824 if (*ptr != mgr->last_alloc) {
1832 (*pool_head)->used += grow;
1833 (*pool_head)->active += grow;
1834 AST_STRING_FIELD_ALLOCATION(*ptr) += grow;
1839 void __ast_string_field_release_active(struct ast_string_field_pool *pool_head,
1840 const ast_string_field ptr)
1842 struct ast_string_field_pool *pool, *prev;
1844 if (ptr == __ast_string_field_empty) {
1848 for (pool = pool_head, prev = NULL; pool; prev = pool, pool = pool->prev) {
1849 if ((ptr >= pool->base) && (ptr <= (pool->base + pool->size))) {
1850 pool->active -= AST_STRING_FIELD_ALLOCATION(ptr);
1851 if ((pool->active == 0) && prev) {
1852 prev->prev = pool->prev;
1860 void __ast_string_field_ptr_build_va(struct ast_string_field_mgr *mgr,
1861 struct ast_string_field_pool **pool_head,
1862 ast_string_field *ptr, const char *format, va_list ap)
1866 size_t space = (*pool_head)->size - (*pool_head)->used;
1871 /* if the field already has space allocated, try to reuse it;
1872 otherwise, try to use the empty space at the end of the current
1875 if (*ptr != __ast_string_field_empty) {
1876 target = (char *) *ptr;
1877 available = AST_STRING_FIELD_ALLOCATION(*ptr);
1878 if (*ptr == mgr->last_alloc) {
1882 /* pool->used is always a multiple of ast_alignof(ast_string_field_allocation)
1883 * so we don't need to re-align anything here.
1885 target = (*pool_head)->base + (*pool_head)->used + ast_alignof(ast_string_field_allocation);
1886 available = space - ast_alignof(ast_string_field_allocation);
1890 needed = vsnprintf(target, available, format, ap2) + 1;
1893 if (needed > available) {
1894 /* the allocation could not be satisfied using the field's current allocation
1895 (if it has one), or the space available in the pool (if it does not). allocate
1896 space for it, adding a new string pool if necessary.
1898 if (!(target = (char *) __ast_string_field_alloc_space(mgr, pool_head, needed))) {
1901 vsprintf(target, format, ap);
1902 va_end(ap); /* XXX va_end without va_start? */
1903 __ast_string_field_release_active(*pool_head, *ptr);
1905 } else if (*ptr != target) {
1906 /* the allocation was satisfied using available space in the pool, but not
1907 using the space already allocated to the field
1909 __ast_string_field_release_active(*pool_head, *ptr);
1910 mgr->last_alloc = *ptr = target;
1911 AST_STRING_FIELD_ALLOCATION(target) = needed;
1912 (*pool_head)->used += ast_make_room_for(needed, ast_string_field_allocation);
1913 (*pool_head)->active += needed;
1914 } else if ((grow = (needed - AST_STRING_FIELD_ALLOCATION(*ptr))) > 0) {
1915 /* the allocation was satisfied by using available space in the pool *and*
1916 the field was the last allocated field from the pool, so it grew
1918 AST_STRING_FIELD_ALLOCATION(*ptr) += grow;
1919 (*pool_head)->used += ast_align_for(grow, ast_string_field_allocation);
1920 (*pool_head)->active += grow;
1924 void __ast_string_field_ptr_build(struct ast_string_field_mgr *mgr,
1925 struct ast_string_field_pool **pool_head,
1926 ast_string_field *ptr, const char *format, ...)
1930 va_start(ap, format);
1931 __ast_string_field_ptr_build_va(mgr, pool_head, ptr, format, ap);
1935 void *__ast_calloc_with_stringfields(unsigned int num_structs, size_t struct_size, size_t field_mgr_offset,
1936 size_t field_mgr_pool_offset, size_t pool_size, const char *file,
1937 int lineno, const char *func)
1939 struct ast_string_field_mgr *mgr;
1940 struct ast_string_field_pool *pool;
1941 struct ast_string_field_pool **pool_head;
1942 size_t pool_size_needed = sizeof(*pool) + pool_size;
1943 size_t size_to_alloc = optimal_alloc_size(struct_size + pool_size_needed);
1947 #if defined(__AST_DEBUG_MALLOC)
1948 if (!(allocation = __ast_calloc(num_structs, size_to_alloc, file, lineno, func))) {
1952 if (!(allocation = ast_calloc(num_structs, size_to_alloc))) {
1957 for (x = 0; x < num_structs; x++) {
1958 void *base = allocation + (size_to_alloc * x);
1961 mgr = base + field_mgr_offset;
1962 pool_head = base + field_mgr_pool_offset;
1963 pool = base + struct_size;
1965 p = (const char **) pool_head + 1;
1966 while ((struct ast_string_field_mgr *) p != mgr) {
1967 *p++ = __ast_string_field_empty;
1970 mgr->embedded_pool = pool;
1972 pool->size = size_to_alloc - struct_size - sizeof(*pool);
1973 #if defined(__AST_DEBUG_MALLOC)
1974 mgr->owner_file = file;
1975 mgr->owner_func = func;
1976 mgr->owner_line = lineno;
1983 /* end of stringfields support */
1985 AST_MUTEX_DEFINE_STATIC(fetchadd_m); /* used for all fetc&add ops */
1987 int ast_atomic_fetchadd_int_slow(volatile int *p, int v)
1990 ast_mutex_lock(&fetchadd_m);
1993 ast_mutex_unlock(&fetchadd_m);
1998 * get values from config variables.
2000 int ast_get_timeval(const char *src, struct timeval *dst, struct timeval _default, int *consumed)
2002 long double dtv = 0.0;
2010 if (ast_strlen_zero(src))
2013 /* only integer at the moment, but one day we could accept more formats */
2014 if (sscanf(src, "%30Lf%n", &dtv, &scanned) > 0) {
2016 dst->tv_usec = (dtv - dst->tv_sec) * 1000000.0;
2018 *consumed = scanned;
2025 * get values from config variables.
2027 int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed)
2037 if (ast_strlen_zero(src))
2040 /* only integer at the moment, but one day we could accept more formats */
2041 if (sscanf(src, "%30ld%n", &t, &scanned) == 1) {
2044 *consumed = scanned;
2050 void ast_enable_packet_fragmentation(int sock)
2052 #if defined(HAVE_IP_MTU_DISCOVER)
2053 int val = IP_PMTUDISC_DONT;
2055 if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
2056 ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
2057 #endif /* HAVE_IP_MTU_DISCOVER */
2060 int ast_mkdir(const char *path, int mode)
2063 int len = strlen(path), count = 0, x, piececount = 0;
2064 char *tmp = ast_strdupa(path);
2066 char *fullpath = ast_alloca(len + 1);
2069 for (ptr = tmp; *ptr; ptr++) {
2074 /* Count the components to the directory path */
2075 pieces = ast_alloca(count * sizeof(*pieces));
2076 for (ptr = tmp; *ptr; ptr++) {
2079 pieces[piececount++] = ptr + 1;
2084 for (x = 0; x < piececount; x++) {
2085 /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
2086 strcat(fullpath, "/");
2087 strcat(fullpath, pieces[x]);
2088 res = mkdir(fullpath, mode);
2089 if (res && errno != EEXIST)
2095 int ast_utils_init(void)
2097 dev_urandom_fd = open("/dev/urandom", O_RDONLY);
2099 #ifdef DEBUG_THREADS
2100 #if !defined(LOW_MEMORY)
2101 ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
2109 *\brief Parse digest authorization header.
2110 *\return Returns -1 if we have no auth or something wrong with digest.
2111 *\note This function may be used for Digest request and responce header.
2112 * request arg is set to nonzero, if we parse Digest Request.
2113 * pedantic arg can be set to nonzero if we need to do addition Digest check.
2115 int ast_parse_digest(const char *digest, struct ast_http_digest *d, int request, int pedantic) {
2117 struct ast_str *str = ast_str_create(16);
2119 /* table of recognised keywords, and places where they should be copied */
2122 const ast_string_field *field;
2124 { "username=", &d->username },
2125 { "realm=", &d->realm },
2126 { "nonce=", &d->nonce },
2127 { "uri=", &d->uri },
2128 { "domain=", &d->domain },
2129 { "response=", &d->response },
2130 { "cnonce=", &d->cnonce },
2131 { "opaque=", &d->opaque },
2132 /* Special cases that cannot be directly copied */
2133 { "algorithm=", NULL },
2139 if (ast_strlen_zero(digest) || !d || !str) {
2144 ast_str_set(&str, 0, "%s", digest);
2146 c = ast_skip_blanks(ast_str_buffer(str));
2148 if (strncasecmp(c, "Digest ", strlen("Digest "))) {
2149 ast_log(LOG_WARNING, "Missing Digest.\n");
2153 c += strlen("Digest ");
2155 /* lookup for keys/value pair */
2156 while (c && *c && *(c = ast_skip_blanks(c))) {
2158 for (i = keys; i->key != NULL; i++) {
2159 char *src, *separator;
2161 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
2165 /* Found. Skip keyword, take text in quotes or up to the separator. */
2166 c += strlen(i->key);
2175 strsep(&c, separator); /* clear separator and move ptr */
2177 ast_unescape_c(src);
2180 ast_string_field_ptr_set(d, i->field, src);
2182 /* Special cases that require additional procesing */
2183 if (!strcasecmp(i->key, "algorithm=")) {
2184 if (strcasecmp(src, "MD5")) {
2185 ast_log(LOG_WARNING, "Digest algorithm: \"%s\" not supported.\n", src);
2189 } else if (!strcasecmp(i->key, "qop=") && !strcasecmp(src, "auth")) {
2191 } else if (!strcasecmp(i->key, "nc=")) {
2193 if (sscanf(src, "%30lx", &u) != 1) {
2194 ast_log(LOG_WARNING, "Incorrect Digest nc value: \"%s\".\n", src);
2198 ast_string_field_set(d, nc, src);
2203 if (i->key == NULL) { /* not found, try ',' */
2209 /* Digest checkout */
2210 if (ast_strlen_zero(d->realm) || ast_strlen_zero(d->nonce)) {
2211 /* "realm" and "nonce" MUST be always exist */
2216 /* Additional check for Digest response */
2217 if (ast_strlen_zero(d->username) || ast_strlen_zero(d->uri) || ast_strlen_zero(d->response)) {
2221 if (pedantic && d->qop && (ast_strlen_zero(d->cnonce) || ast_strlen_zero(d->nc))) {
2229 #ifndef __AST_DEBUG_MALLOC
2230 int _ast_asprintf(char **ret, const char *file, int lineno, const char *func, const char *fmt, ...)
2236 if ((res = vasprintf(ret, fmt, ap)) == -1) {
2245 int ast_get_tid(void)
2248 #if defined (__linux) && defined(SYS_gettid)
2249 ret = syscall(SYS_gettid); /* available since Linux 1.4.11 */
2250 #elif defined(__sun)
2251 ret = pthread_self();
2252 #elif defined(__APPLE__)
2253 ret = mach_thread_self();
2254 mach_port_deallocate(mach_task_self(), ret);
2255 #elif defined(__FreeBSD__) && defined(HAVE_SYS_THR_H)
2257 thr_self(&lwpid); /* available since sys/thr.h creation 2003 */
2263 char *ast_utils_which(const char *binary, char *fullpath, size_t fullpath_size)
2265 const char *envPATH = getenv("PATH");
2271 tpath = ast_strdupa(envPATH);
2272 while ((path = strsep(&tpath, ":"))) {
2273 snprintf(fullpath, fullpath_size, "%s/%s", path, binary);
2274 if (!stat(fullpath, &unused)) {
2281 void ast_do_crash(void)
2283 #if defined(DO_CRASH)
2286 * Just in case abort() doesn't work or something else super
2287 * silly, and for Qwell's amusement.
2290 #endif /* defined(DO_CRASH) */
2293 #if defined(AST_DEVMODE)
2294 void __ast_assert_failed(int condition, const char *condition_str, const char *file, int line, const char *function)
2297 * Attempt to put it into the logger, but hope that at least
2298 * someone saw the message on stderr ...
2300 ast_log(__LOG_ERROR, file, line, function, "FRACK!, Failed assertion %s (%d)\n",
2301 condition_str, condition);
2302 fprintf(stderr, "FRACK!, Failed assertion %s (%d) at line %d in %s of %s\n",
2303 condition_str, condition, line, function, file);
2305 * Give the logger a chance to get the message out, just in case
2306 * we abort(), or Asterisk crashes due to whatever problem just
2307 * happened after we exit ast_assert().
2312 #endif /* defined(AST_DEVMODE) */