2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * See http://www.asterisk.org for more information about
7 * the Asterisk project. Please do not directly contact
8 * any of the maintainers of this project for assistance;
9 * the project provides a web site, mailing lists and IRC
10 * channels for your use.
12 * This program is free software, distributed under the terms of
13 * the GNU General Public License Version 2. See the LICENSE file
14 * at the top of the source tree.
19 * \brief Utility functions
21 * \note These are important for portability and security,
22 * so please use them in favour of other routines.
23 * Please consult the CODING GUIDELINES for more information.
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
34 #ifdef HAVE_DEV_URANDOM
38 #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"
47 #define AST_API_MODULE /* ensure that inlinable API functions will be built in lock.h if required */
48 #include "asterisk/lock.h"
49 #include "asterisk/io.h"
50 #include "asterisk/md5.h"
51 #include "asterisk/sha1.h"
52 #include "asterisk/cli.h"
53 #include "asterisk/linkedlists.h"
55 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
56 #include "asterisk/strings.h"
58 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
59 #include "asterisk/time.h"
61 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
62 #include "asterisk/stringfields.h"
64 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
65 #include "asterisk/utils.h"
67 #define AST_API_MODULE
68 #include "asterisk/threadstorage.h"
70 #define AST_API_MODULE
71 #include "asterisk/config.h"
73 static char base64[64];
76 AST_THREADSTORAGE(inet_ntoa_buf);
78 #if !defined(HAVE_GETHOSTBYNAME_R_5) && !defined(HAVE_GETHOSTBYNAME_R_6)
80 #define ERANGE 34 /*!< duh? ERANGE value copied from web... */
83 AST_MUTEX_DEFINE_STATIC(__mutex);
85 /*! \brief Reentrant replacement for gethostbyname for BSD-based systems.
87 routine is derived from code originally written and placed in the public
88 domain by Enzo Michelangeli <em@em.no-ip.com> */
90 static int gethostbyname_r (const char *name, struct hostent *ret, char *buf,
91 size_t buflen, struct hostent **result,
96 ast_mutex_lock(&__mutex); /* begin critical area */
99 ph = gethostbyname(name);
100 *h_errnop = h_errno; /* copy h_errno to *h_herrnop */
107 int naddr = 0, naliases = 0;
108 /* determine if we have enough space in buf */
110 /* count how many addresses */
111 for (p = ph->h_addr_list; *p != 0; p++) {
112 nbytes += ph->h_length; /* addresses */
113 nbytes += sizeof(*p); /* pointers */
116 nbytes += sizeof(*p); /* one more for the terminating NULL */
118 /* count how many aliases, and total length of strings */
119 for (p = ph->h_aliases; *p != 0; p++) {
120 nbytes += (strlen(*p)+1); /* aliases */
121 nbytes += sizeof(*p); /* pointers */
124 nbytes += sizeof(*p); /* one more for the terminating NULL */
126 /* here nbytes is the number of bytes required in buffer */
127 /* as a terminator must be there, the minimum value is ph->h_length */
128 if (nbytes > buflen) {
130 ast_mutex_unlock(&__mutex); /* end critical area */
131 return ERANGE; /* not enough space in buf!! */
134 /* There is enough space. Now we need to do a deep copy! */
135 /* Allocation in buffer:
136 from [0] to [(naddr-1) * sizeof(*p)]:
137 pointers to addresses
138 at [naddr * sizeof(*p)]:
140 from [(naddr+1) * sizeof(*p)] to [(naddr+naliases) * sizeof(*p)] :
142 at [(naddr+naliases+1) * sizeof(*p)]:
144 then naddr addresses (fixed length), and naliases aliases (asciiz).
147 *ret = *ph; /* copy whole structure (not its address!) */
150 q = (char **)buf; /* pointer to pointers area (type: char **) */
151 ret->h_addr_list = q; /* update pointer to address list */
152 pbuf = buf + ((naddr + naliases + 2) * sizeof(*p)); /* skip that area */
153 for (p = ph->h_addr_list; *p != 0; p++) {
154 memcpy(pbuf, *p, ph->h_length); /* copy address bytes */
155 *q++ = pbuf; /* the pointer is the one inside buf... */
156 pbuf += ph->h_length; /* advance pbuf */
158 *q++ = NULL; /* address list terminator */
161 ret->h_aliases = q; /* update pointer to aliases list */
162 for (p = ph->h_aliases; *p != 0; p++) {
163 strcpy(pbuf, *p); /* copy alias strings */
164 *q++ = pbuf; /* the pointer is the one inside buf... */
165 pbuf += strlen(*p); /* advance pbuf */
166 *pbuf++ = 0; /* string terminator */
168 *q++ = NULL; /* terminator */
170 strcpy(pbuf, ph->h_name); /* copy alias strings */
172 pbuf += strlen(ph->h_name); /* advance pbuf */
173 *pbuf++ = 0; /* string terminator */
175 *result = ret; /* and let *result point to structure */
178 h_errno = hsave; /* restore h_errno */
179 ast_mutex_unlock(&__mutex); /* end critical area */
181 return (*result == NULL); /* return 0 on success, non-zero on error */
187 /*! \brief Re-entrant (thread safe) version of gethostbyname that replaces the
188 standard gethostbyname (which is not thread safe)
190 struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp)
196 struct hostent *result = NULL;
197 /* Although it is perfectly legitimate to lookup a pure integer, for
198 the sake of the sanity of people who like to name their peers as
199 integers, we break with tradition and refuse to look up a
206 else if (!isdigit(*s))
211 /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
214 memset(hp, 0, sizeof(struct ast_hostent));
215 hp->hp.h_addrtype = AF_INET;
216 hp->hp.h_addr_list = (void *) hp->buf;
217 hp->hp.h_addr = hp->buf + sizeof(void *);
218 /* For AF_INET, this will always be 4 */
220 if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
225 #ifdef HAVE_GETHOSTBYNAME_R_5
226 result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);
228 if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
231 res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
233 if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
239 /*! \brief Produce 32 char MD5 hash of value. */
240 void ast_md5_hash(char *output, const char *input)
242 struct MD5Context md5;
243 unsigned char digest[16];
248 MD5Update(&md5, (const unsigned char *) input, strlen(input));
249 MD5Final(digest, &md5);
251 for (x = 0; x < 16; x++)
252 ptr += sprintf(ptr, "%2.2x", digest[x]);
255 /*! \brief Produce 40 char SHA1 hash of value. */
256 void ast_sha1_hash(char *output, const char *input)
258 struct SHA1Context sha;
261 uint8_t Message_Digest[20];
265 SHA1Input(&sha, (const unsigned char *) input, strlen(input));
267 SHA1Result(&sha, Message_Digest);
269 for (x = 0; x < 20; x++)
270 ptr += sprintf(ptr, "%2.2x", Message_Digest[x]);
273 /*! \brief Produce a 20 byte SHA1 hash of value. */
274 void ast_sha1_hash_uint(uint8_t *digest, const char *input)
276 struct SHA1Context sha;
280 SHA1Input(&sha, (const unsigned char *) input, strlen(input));
282 SHA1Result(&sha, digest);
285 /*! \brief decode BASE64 encoded text */
286 int ast_base64decode(unsigned char *dst, const char *src, int max)
289 unsigned int byte = 0;
290 unsigned int bits = 0;
292 while(*src && *src != '=' && (cnt < max)) {
293 /* Shift in 6 bits of input */
295 byte |= (b2a[(int)(*src)]) & 0x3f;
299 /* If we have at least 8 bits left over, take that character
303 *dst = (byte >> bits) & 0xff;
308 /* Don't worry about left over bits, they're extra anyway */
312 /*! \brief encode text to BASE64 coding */
313 int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
317 unsigned int byte = 0;
320 /* Reserve space for null byte at end of string */
322 while ((cntin < srclen) && (cnt < max)) {
327 if ((bits == 24) && (cnt + 4 <= max)) {
328 *dst++ = base64[(byte >> 18) & 0x3f];
329 *dst++ = base64[(byte >> 12) & 0x3f];
330 *dst++ = base64[(byte >> 6) & 0x3f];
331 *dst++ = base64[byte & 0x3f];
337 if (linebreaks && (cnt < max) && (col == 64)) {
343 if (bits && (cnt + 4 <= max)) {
344 /* Add one last character for the remaining bits,
345 padding the rest with 0 */
347 *dst++ = base64[(byte >> 18) & 0x3f];
348 *dst++ = base64[(byte >> 12) & 0x3f];
350 *dst++ = base64[(byte >> 6) & 0x3f];
356 if (linebreaks && (cnt < max)) {
364 int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
366 return ast_base64encode_full(dst, src, srclen, max, 0);
369 static void base64_init(void)
372 memset(b2a, -1, sizeof(b2a));
373 /* Initialize base-64 Conversion table */
374 for (x = 0; x < 26; x++) {
379 base64[x + 26] = 'a' + x;
380 b2a['a' + x] = x + 26;
383 base64[x + 52] = '0' + x;
384 b2a['0' + x] = x + 52;
393 const struct ast_flags ast_uri_http = {AST_URI_UNRESERVED};
394 const struct ast_flags ast_uri_http_legacy = {AST_URI_LEGACY_SPACE | AST_URI_UNRESERVED};
395 const struct ast_flags ast_uri_sip_user = {AST_URI_UNRESERVED | AST_URI_SIP_USER_UNRESERVED};
397 char *ast_uri_encode(const char *string, char *outbuf, int buflen, struct ast_flags spec)
399 const char *ptr = string; /* Start with the string */
401 const char *mark = "-_.!~*'()"; /* no encode set, RFC 2396 section 2.3, RFC 3261 sec 25 */
402 const char *user_unreserved = "&=+$,;?/"; /* user-unreserved set, RFC 3261 sec 25 */
404 while (*ptr && out - outbuf < buflen - 1) {
405 if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *ptr == ' ') {
406 /* for legacy encoding, encode spaces as '+' */
409 } else if (!(ast_test_flag(&spec, AST_URI_MARK)
410 && strchr(mark, *ptr))
411 && !(ast_test_flag(&spec, AST_URI_ALPHANUM)
412 && ((*ptr >= '0' && *ptr <= '9')
413 || (*ptr >= 'A' && *ptr <= 'Z')
414 || (*ptr >= 'a' && *ptr <= 'z')))
415 && !(ast_test_flag(&spec, AST_URI_SIP_USER_UNRESERVED)
416 && strchr(user_unreserved, *ptr))) {
418 if (out - outbuf >= buflen - 3) {
421 out += sprintf(out, "%%%02X", (unsigned char) *ptr);
423 *out = *ptr; /* Continue copying the string */
436 void ast_uri_decode(char *s, struct ast_flags spec)
441 for (o = s; *s; s++, o++) {
442 if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *s == '+') {
443 /* legacy mode, decode '+' as space */
445 } else if (*s == '%' && s[1] != '\0' && s[2] != '\0' && sscanf(s + 1, "%2x", &tmp) == 1) {
446 /* have '%', two chars and correct parsing */
448 s += 2; /* Will be incremented once more when we break out */
449 } else /* all other cases, just copy */
455 char *ast_escape_quoted(const char *string, char *outbuf, int buflen)
457 const char *ptr = string;
459 char *allow = "\t\v !"; /* allow LWS (minus \r and \n) and "!" */
461 while (*ptr && out - outbuf < buflen - 1) {
462 if (!(strchr(allow, *ptr))
463 && !(*ptr >= '#' && *ptr <= '[') /* %x23 - %x5b */
464 && !(*ptr >= ']' && *ptr <= '~') /* %x5d - %x7e */
465 && !((unsigned char) *ptr > 0x7f)) { /* UTF8-nonascii */
467 if (out - outbuf >= buflen - 2) {
470 out += sprintf(out, "\\%c", (unsigned char) *ptr);
484 /*! \brief ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa */
485 const char *ast_inet_ntoa(struct in_addr ia)
489 if (!(buf = ast_threadstorage_get(&inet_ntoa_buf, INET_ADDRSTRLEN)))
492 return inet_ntop(AF_INET, &ia, buf, INET_ADDRSTRLEN);
495 #ifdef HAVE_DEV_URANDOM
496 static int dev_urandom_fd;
500 #undef pthread_create /* For ast_pthread_create function only */
501 #endif /* !__linux__ */
503 #if !defined(LOW_MEMORY)
507 /*! \brief A reasonable maximum number of locks a thread would be holding ... */
508 #define AST_MAX_LOCKS 64
510 /* Allow direct use of pthread_mutex_t and friends */
511 #undef pthread_mutex_t
512 #undef pthread_mutex_lock
513 #undef pthread_mutex_unlock
514 #undef pthread_mutex_init
515 #undef pthread_mutex_destroy
518 * \brief Keep track of which locks a thread holds
520 * There is an instance of this struct for every active thread
522 struct thr_lock_info {
523 /*! The thread's ID */
525 /*! The thread name which includes where the thread was started */
526 const char *thread_name;
527 /*! This is the actual container of info for what locks this thread holds */
532 const char *lock_name;
535 enum ast_lock_type type;
536 /*! This thread is waiting on this lock */
539 struct ast_bt *backtrace;
541 } locks[AST_MAX_LOCKS];
542 /*! This is the number of locks currently held by this thread.
543 * The index (num_locks - 1) has the info on the last one in the
545 unsigned int num_locks;
546 /*! Protects the contents of the locks member
547 * Intentionally not ast_mutex_t */
548 pthread_mutex_t lock;
549 AST_LIST_ENTRY(thr_lock_info) entry;
553 * \brief Locked when accessing the lock_infos list
555 AST_MUTEX_DEFINE_STATIC(lock_infos_lock);
557 * \brief A list of each thread's lock info
559 static AST_LIST_HEAD_NOLOCK_STATIC(lock_infos, thr_lock_info);
562 * \brief Destroy a thread's lock info
564 * This gets called automatically when the thread stops
566 static void lock_info_destroy(void *data)
568 struct thr_lock_info *lock_info = data;
571 pthread_mutex_lock(&lock_infos_lock.mutex);
572 AST_LIST_REMOVE(&lock_infos, lock_info, entry);
573 pthread_mutex_unlock(&lock_infos_lock.mutex);
576 for (i = 0; i < lock_info->num_locks; i++) {
577 if (lock_info->locks[i].pending == -1) {
578 /* This just means that the last lock this thread went for was by
579 * using trylock, and it failed. This is fine. */
584 "Thread '%s' still has a lock! - '%s' (%p) from '%s' in %s:%d!\n",
585 lock_info->thread_name,
586 lock_info->locks[i].lock_name,
587 lock_info->locks[i].lock_addr,
588 lock_info->locks[i].func,
589 lock_info->locks[i].file,
590 lock_info->locks[i].line_num
594 pthread_mutex_destroy(&lock_info->lock);
595 if (lock_info->thread_name)
596 free((void *) lock_info->thread_name);
601 * \brief The thread storage key for per-thread lock info
603 AST_THREADSTORAGE_CUSTOM(thread_lock_info, NULL, lock_info_destroy);
605 void ast_store_lock_info(enum ast_lock_type type, const char *filename,
606 int line_num, const char *func, const char *lock_name, void *lock_addr, struct ast_bt *bt)
608 void ast_store_lock_info(enum ast_lock_type type, const char *filename,
609 int line_num, const char *func, const char *lock_name, void *lock_addr)
612 struct thr_lock_info *lock_info;
615 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
618 pthread_mutex_lock(&lock_info->lock);
620 for (i = 0; i < lock_info->num_locks; i++) {
621 if (lock_info->locks[i].lock_addr == lock_addr) {
622 lock_info->locks[i].times_locked++;
624 lock_info->locks[i].backtrace = bt;
626 pthread_mutex_unlock(&lock_info->lock);
631 if (lock_info->num_locks == AST_MAX_LOCKS) {
632 /* Can't use ast_log here, because it will cause infinite recursion */
633 fprintf(stderr, "XXX ERROR XXX A thread holds more locks than '%d'."
634 " Increase AST_MAX_LOCKS!\n", AST_MAX_LOCKS);
635 pthread_mutex_unlock(&lock_info->lock);
639 if (i && lock_info->locks[i - 1].pending == -1) {
640 /* The last lock on the list was one that this thread tried to lock but
641 * failed at doing so. It has now moved on to something else, so remove
642 * the old lock from the list. */
644 lock_info->num_locks--;
645 memset(&lock_info->locks[i], 0, sizeof(lock_info->locks[0]));
648 lock_info->locks[i].file = filename;
649 lock_info->locks[i].line_num = line_num;
650 lock_info->locks[i].func = func;
651 lock_info->locks[i].lock_name = lock_name;
652 lock_info->locks[i].lock_addr = lock_addr;
653 lock_info->locks[i].times_locked = 1;
654 lock_info->locks[i].type = type;
655 lock_info->locks[i].pending = 1;
657 lock_info->locks[i].backtrace = bt;
659 lock_info->num_locks++;
661 pthread_mutex_unlock(&lock_info->lock);
664 void ast_mark_lock_acquired(void *lock_addr)
666 struct thr_lock_info *lock_info;
668 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
671 pthread_mutex_lock(&lock_info->lock);
672 if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
673 lock_info->locks[lock_info->num_locks - 1].pending = 0;
675 pthread_mutex_unlock(&lock_info->lock);
678 void ast_mark_lock_failed(void *lock_addr)
680 struct thr_lock_info *lock_info;
682 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
685 pthread_mutex_lock(&lock_info->lock);
686 if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
687 lock_info->locks[lock_info->num_locks - 1].pending = -1;
688 lock_info->locks[lock_info->num_locks - 1].times_locked--;
690 pthread_mutex_unlock(&lock_info->lock);
693 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)
695 struct thr_lock_info *lock_info;
698 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
701 pthread_mutex_lock(&lock_info->lock);
703 for (i = lock_info->num_locks - 1; i >= 0; i--) {
704 if (lock_info->locks[i].lock_addr == lock_addr)
709 /* Lock not found :( */
710 pthread_mutex_unlock(&lock_info->lock);
714 ast_copy_string(filename, lock_info->locks[i].file, filename_size);
715 *lineno = lock_info->locks[i].line_num;
716 ast_copy_string(func, lock_info->locks[i].func, func_size);
717 ast_copy_string(mutex_name, lock_info->locks[i].lock_name, mutex_name_size);
719 pthread_mutex_unlock(&lock_info->lock);
725 void ast_remove_lock_info(void *lock_addr, struct ast_bt *bt)
727 void ast_remove_lock_info(void *lock_addr)
730 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);
738 for (i = lock_info->num_locks - 1; i >= 0; i--) {
739 if (lock_info->locks[i].lock_addr == lock_addr)
744 /* Lock not found :( */
745 pthread_mutex_unlock(&lock_info->lock);
749 if (lock_info->locks[i].times_locked > 1) {
750 lock_info->locks[i].times_locked--;
752 lock_info->locks[i].backtrace = bt;
754 pthread_mutex_unlock(&lock_info->lock);
758 if (i < lock_info->num_locks - 1) {
759 /* Not the last one ... *should* be rare! */
760 memmove(&lock_info->locks[i], &lock_info->locks[i + 1],
761 (lock_info->num_locks - (i + 1)) * sizeof(lock_info->locks[0]));
764 lock_info->num_locks--;
766 pthread_mutex_unlock(&lock_info->lock);
769 static const char *locktype2str(enum ast_lock_type type)
784 static void append_backtrace_information(struct ast_str **str, struct ast_bt *bt)
789 ast_str_append(str, 0, "\tNo backtrace to print\n");
793 if ((symbols = ast_bt_get_symbols(bt->addresses, bt->num_frames))) {
796 for (frame_iterator = 0; frame_iterator < bt->num_frames; ++frame_iterator) {
797 ast_str_append(str, 0, "\t%s\n", symbols[frame_iterator]);
802 ast_str_append(str, 0, "\tCouldn't retrieve backtrace symbols\n");
807 static void append_lock_information(struct ast_str **str, struct thr_lock_info *lock_info, int i)
811 struct ast_lock_track *lt;
813 ast_str_append(str, 0, "=== ---> %sLock #%d (%s): %s %d %s %s %p (%d)\n",
814 lock_info->locks[i].pending > 0 ? "Waiting for " :
815 lock_info->locks[i].pending < 0 ? "Tried and failed to get " : "", i,
816 lock_info->locks[i].file,
817 locktype2str(lock_info->locks[i].type),
818 lock_info->locks[i].line_num,
819 lock_info->locks[i].func, lock_info->locks[i].lock_name,
820 lock_info->locks[i].lock_addr,
821 lock_info->locks[i].times_locked);
823 append_backtrace_information(str, lock_info->locks[i].backtrace);
826 if (!lock_info->locks[i].pending || lock_info->locks[i].pending == -1)
829 /* We only have further details for mutexes right now */
830 if (lock_info->locks[i].type != AST_MUTEX)
833 lock = lock_info->locks[i].lock_addr;
835 ast_reentrancy_lock(lt);
836 for (j = 0; *str && j < lt->reentrancy; j++) {
837 ast_str_append(str, 0, "=== --- ---> Locked Here: %s line %d (%s)\n",
838 lt->file[j], lt->lineno[j], lt->func[j]);
840 ast_reentrancy_unlock(lt);
844 /*! This function can help you find highly temporal locks; locks that happen for a
845 short time, but at unexpected times, usually at times that create a deadlock,
846 Why is this thing locked right then? Who is locking it? Who am I fighting
849 To answer such questions, just call this routine before you would normally try
850 to aquire a lock. It doesn't do anything if the lock is not acquired. If the
851 lock is taken, it will publish a line or two to the console via ast_log().
853 Sometimes, the lock message is pretty uninformative. For instance, you might
854 find that the lock is being aquired deep within the astobj2 code; this tells
855 you little about higher level routines that call the astobj2 routines.
856 But, using gdb, you can set a break at the ast_log below, and for that
857 breakpoint, you can set the commands:
860 which will give a stack trace and continue. -- that aught to do the job!
863 void log_show_lock(void *this_lock_addr)
865 struct thr_lock_info *lock_info;
868 if (!(str = ast_str_create(4096))) {
869 ast_log(LOG_NOTICE,"Could not create str\n");
874 pthread_mutex_lock(&lock_infos_lock.mutex);
875 AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
877 pthread_mutex_lock(&lock_info->lock);
878 for (i = 0; str && i < lock_info->num_locks; i++) {
879 /* ONLY show info about this particular lock, if
881 if (lock_info->locks[i].lock_addr == this_lock_addr) {
882 append_lock_information(&str, lock_info, i);
883 ast_log(LOG_NOTICE, "%s", ast_str_buffer(str));
887 pthread_mutex_unlock(&lock_info->lock);
889 pthread_mutex_unlock(&lock_infos_lock.mutex);
894 static char *handle_show_locks(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
896 struct thr_lock_info *lock_info;
899 if (!(str = ast_str_create(4096)))
904 e->command = "core show locks";
906 "Usage: core show locks\n"
907 " This command is for lock debugging. It prints out which locks\n"
908 "are owned by each active thread.\n";
915 ast_str_append(&str, 0, "\n"
916 "=======================================================================\n"
917 "=== Currently Held Locks ==============================================\n"
918 "=======================================================================\n"
920 "=== <pending> <lock#> (<file>): <lock type> <line num> <function> <lock name> <lock addr> (times locked)\n"
926 pthread_mutex_lock(&lock_infos_lock.mutex);
927 AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
929 if (lock_info->num_locks) {
930 ast_str_append(&str, 0, "=== Thread ID: 0x%lx (%s)\n", (long) lock_info->thread_id,
931 lock_info->thread_name);
932 pthread_mutex_lock(&lock_info->lock);
933 for (i = 0; str && i < lock_info->num_locks; i++) {
934 append_lock_information(&str, lock_info, i);
936 pthread_mutex_unlock(&lock_info->lock);
939 ast_str_append(&str, 0, "=== -------------------------------------------------------------------\n"
945 pthread_mutex_unlock(&lock_infos_lock.mutex);
950 ast_str_append(&str, 0, "=======================================================================\n"
956 ast_cli(a->fd, "%s", ast_str_buffer(str));
963 static struct ast_cli_entry utils_cli[] = {
964 AST_CLI_DEFINE(handle_show_locks, "Show which locks are held by which thread"),
967 #endif /* DEBUG_THREADS */
970 * support for 'show threads'. The start routine is wrapped by
971 * dummy_start(), so that ast_register_thread() and
972 * ast_unregister_thread() know the thread identifier.
975 void *(*start_routine)(void *);
981 * on OS/X, pthread_cleanup_push() and pthread_cleanup_pop()
982 * are odd macros which start and end a block, so they _must_ be
983 * used in pairs (the latter with a '1' argument to call the
985 * On BSD we don't need this, but we keep it for compatibility.
987 static void *dummy_start(void *data)
990 struct thr_arg a = *((struct thr_arg *) data); /* make a local copy */
992 struct thr_lock_info *lock_info;
993 pthread_mutexattr_t mutex_attr;
996 /* note that even though data->name is a pointer to allocated memory,
997 we are not freeing it here because ast_register_thread is going to
998 keep a copy of the pointer and then ast_unregister_thread will
1002 ast_register_thread(a.name);
1003 pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
1005 #ifdef DEBUG_THREADS
1006 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
1009 lock_info->thread_id = pthread_self();
1010 lock_info->thread_name = strdup(a.name);
1012 pthread_mutexattr_init(&mutex_attr);
1013 pthread_mutexattr_settype(&mutex_attr, AST_MUTEX_KIND);
1014 pthread_mutex_init(&lock_info->lock, &mutex_attr);
1015 pthread_mutexattr_destroy(&mutex_attr);
1017 pthread_mutex_lock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
1018 AST_LIST_INSERT_TAIL(&lock_infos, lock_info, entry);
1019 pthread_mutex_unlock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
1020 #endif /* DEBUG_THREADS */
1022 ret = a.start_routine(a.data);
1024 pthread_cleanup_pop(1);
1029 #endif /* !LOW_MEMORY */
1031 int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
1032 void *data, size_t stacksize, const char *file, const char *caller,
1033 int line, const char *start_fn)
1035 #if !defined(LOW_MEMORY)
1040 attr = alloca(sizeof(*attr));
1041 pthread_attr_init(attr);
1045 /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
1046 which is kind of useless. Change this here to
1047 PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
1048 priority will propagate down to new threads by default.
1049 This does mean that callers cannot set a different priority using
1050 PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
1051 the priority afterwards with pthread_setschedparam(). */
1052 if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
1053 ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
1057 stacksize = AST_STACKSIZE;
1059 if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
1060 ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
1062 #if !defined(LOW_MEMORY)
1063 if ((a = ast_malloc(sizeof(*a)))) {
1064 a->start_routine = start_routine;
1066 start_routine = dummy_start;
1067 if (asprintf(&a->name, "%-20s started at [%5d] %s %s()",
1068 start_fn, line, file, caller) < 0) {
1069 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
1074 #endif /* !LOW_MEMORY */
1076 return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
1080 int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
1081 void *data, size_t stacksize, const char *file, const char *caller,
1082 int line, const char *start_fn)
1084 unsigned char attr_destroy = 0;
1088 attr = alloca(sizeof(*attr));
1089 pthread_attr_init(attr);
1093 if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
1094 ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
1096 res = ast_pthread_create_stack(thread, attr, start_routine, data,
1097 stacksize, file, caller, line, start_fn);
1100 pthread_attr_destroy(attr);
1105 int ast_wait_for_input(int fd, int ms)
1107 struct pollfd pfd[1];
1108 memset(pfd, 0, sizeof(pfd));
1110 pfd[0].events = POLLIN|POLLPRI;
1111 return ast_poll(pfd, 1, ms);
1114 static int ast_wait_for_output(int fd, int timeoutms)
1116 struct pollfd pfd = {
1121 struct timeval start = ast_tvnow();
1124 /* poll() until the fd is writable without blocking */
1125 while ((res = ast_poll(&pfd, 1, timeoutms - elapsed)) <= 0) {
1129 ast_debug(1, "Timed out trying to write\n");
1132 } else if (res == -1) {
1133 /* poll() returned an error, check to see if it was fatal */
1135 if (errno == EINTR || errno == EAGAIN) {
1136 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1137 if (elapsed >= timeoutms) {
1140 /* This was an acceptable error, go back into poll() */
1144 /* Fatal error, bail. */
1145 ast_log(LOG_ERROR, "poll returned error: %s\n", strerror(errno));
1149 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1150 if (elapsed >= timeoutms) {
1159 * Try to write string, but wait no more than ms milliseconds before timing out.
1161 * \note The code assumes that the file descriptor has NONBLOCK set,
1162 * so there is only one system call made to do a write, unless we actually
1163 * have a need to wait. This way, we get better performance.
1164 * If the descriptor is blocking, all assumptions on the guaranteed
1165 * detail do not apply anymore.
1167 int ast_carefulwrite(int fd, char *s, int len, int timeoutms)
1169 struct timeval start = ast_tvnow();
1174 if (ast_wait_for_output(fd, timeoutms - elapsed)) {
1178 res = write(fd, s, len);
1180 if (res < 0 && errno != EAGAIN && errno != EINTR) {
1181 /* fatal error from write() */
1182 ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
1187 /* It was an acceptable error */
1191 /* Update how much data we have left to write */
1196 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1197 if (elapsed >= timeoutms) {
1198 /* We've taken too long to write
1199 * This is only an error condition if we haven't finished writing. */
1208 int ast_careful_fwrite(FILE *f, int fd, const char *src, size_t len, int timeoutms)
1210 struct timeval start = ast_tvnow();
1215 if (ast_wait_for_output(fd, timeoutms - elapsed)) {
1216 /* poll returned a fatal error, so bail out immediately. */
1220 /* Clear any errors from a previous write */
1223 n = fwrite(src, 1, len, f);
1225 if (ferror(f) && errno != EINTR && errno != EAGAIN) {
1226 /* fatal error from fwrite() */
1228 /* Don't spam the logs if it was just that the connection is closed. */
1229 ast_log(LOG_ERROR, "fwrite() returned error: %s\n", strerror(errno));
1235 /* Update for data already written to the socket */
1239 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1240 if (elapsed >= timeoutms) {
1241 /* We've taken too long to write
1242 * This is only an error condition if we haven't finished writing. */
1249 if (errno == EAGAIN || errno == EINTR) {
1253 /* Don't spam the logs if it was just that the connection is closed. */
1254 ast_log(LOG_ERROR, "fflush() returned error: %s\n", strerror(errno));
1260 return n < 0 ? -1 : 0;
1263 char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
1269 if ((q = strchr(beg_quotes, *s)) && *q != '\0') {
1270 e = s + strlen(s) - 1;
1271 if (*e == *(end_quotes + (q - beg_quotes))) {
1280 char *ast_unescape_semicolon(char *s)
1285 while ((e = strchr(work, ';'))) {
1286 if ((e > work) && (*(e-1) == '\\')) {
1287 memmove(e - 1, e, strlen(e) + 1);
1297 /* !\brief unescape some C sequences in place, return pointer to the original string.
1299 char *ast_unescape_c(char *src)
1305 for (ret = dst = src; (c = *src++); *dst++ = c ) {
1307 continue; /* copy char at the end of the loop */
1308 switch ((c = *src++)) {
1309 case '\0': /* special, trailing '\' */
1312 case 'b': /* backspace */
1315 case 'f': /* form feed */
1328 /* default, use the char literally */
1334 int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap)
1338 if (!buffer || !*buffer || !space || !*space)
1341 result = vsnprintf(*buffer, *space, fmt, ap);
1345 else if (result > *space)
1353 int ast_build_string(char **buffer, size_t *space, const char *fmt, ...)
1359 result = ast_build_string_va(buffer, space, fmt, ap);
1365 int ast_regex_string_to_regex_pattern(const char *regex_string, struct ast_str *regex_pattern)
1367 int regex_len = strlen(regex_string);
1370 /* Chop off the leading / if there is one */
1371 if ((regex_len >= 1) && (regex_string[0] == '/')) {
1372 ast_str_set(®ex_pattern, 0, "%s", regex_string + 1);
1376 /* Chop off the ending / if there is one */
1377 if ((regex_len > 1) && (regex_string[regex_len - 1] == '/')) {
1378 ast_str_truncate(regex_pattern, -1);
1385 int ast_true(const char *s)
1387 if (ast_strlen_zero(s))
1390 /* Determine if this is a true value */
1391 if (!strcasecmp(s, "yes") ||
1392 !strcasecmp(s, "true") ||
1393 !strcasecmp(s, "y") ||
1394 !strcasecmp(s, "t") ||
1395 !strcasecmp(s, "1") ||
1396 !strcasecmp(s, "on"))
1402 int ast_false(const char *s)
1404 if (ast_strlen_zero(s))
1407 /* Determine if this is a false value */
1408 if (!strcasecmp(s, "no") ||
1409 !strcasecmp(s, "false") ||
1410 !strcasecmp(s, "n") ||
1411 !strcasecmp(s, "f") ||
1412 !strcasecmp(s, "0") ||
1413 !strcasecmp(s, "off"))
1419 #define ONE_MILLION 1000000
1421 * put timeval in a valid range. usec is 0..999999
1422 * negative values are not allowed and truncated.
1424 static struct timeval tvfix(struct timeval a)
1426 if (a.tv_usec >= ONE_MILLION) {
1427 ast_log(LOG_WARNING, "warning too large timestamp %ld.%ld\n",
1428 (long)a.tv_sec, (long int) a.tv_usec);
1429 a.tv_sec += a.tv_usec / ONE_MILLION;
1430 a.tv_usec %= ONE_MILLION;
1431 } else if (a.tv_usec < 0) {
1432 ast_log(LOG_WARNING, "warning negative timestamp %ld.%ld\n",
1433 (long)a.tv_sec, (long int) a.tv_usec);
1439 struct timeval ast_tvadd(struct timeval a, struct timeval b)
1441 /* consistency checks to guarantee usec in 0..999999 */
1444 a.tv_sec += b.tv_sec;
1445 a.tv_usec += b.tv_usec;
1446 if (a.tv_usec >= ONE_MILLION) {
1448 a.tv_usec -= ONE_MILLION;
1453 struct timeval ast_tvsub(struct timeval a, struct timeval b)
1455 /* consistency checks to guarantee usec in 0..999999 */
1458 a.tv_sec -= b.tv_sec;
1459 a.tv_usec -= b.tv_usec;
1460 if (a.tv_usec < 0) {
1462 a.tv_usec += ONE_MILLION;
1468 /*! \brief glibc puts a lock inside random(3), so that the results are thread-safe.
1469 * BSD libc (and others) do not. */
1472 AST_MUTEX_DEFINE_STATIC(randomlock);
1475 long int ast_random(void)
1478 #ifdef HAVE_DEV_URANDOM
1479 if (dev_urandom_fd >= 0) {
1480 int read_res = read(dev_urandom_fd, &res, sizeof(res));
1482 long int rm = RAND_MAX;
1483 res = res < 0 ? ~res : res;
1492 ast_mutex_lock(&randomlock);
1494 ast_mutex_unlock(&randomlock);
1499 void ast_replace_subargument_delimiter(char *s)
1508 char *ast_process_quotes_and_slashes(char *start, char find, char replace_with)
1510 char *dataPut = start;
1514 for (; *start; start++) {
1516 *dataPut++ = *start; /* Always goes verbatim */
1519 if (*start == '\\') {
1520 inEscape = 1; /* Do not copy \ into the data */
1521 } else if (*start == '\'') {
1522 inQuotes = 1 - inQuotes; /* Do not copy ' into the data */
1524 /* Replace , with |, unless in quotes */
1525 *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
1529 if (start != dataPut)
1534 void ast_join(char *s, size_t len, const char * const w[])
1539 /* Join words into a string */
1542 for (x = 0; ofs < len && w[x]; x++) {
1545 for (src = w[x]; *src && ofs < len; src++)
1554 * stringfields support routines.
1557 /* this is a little complex... string fields are stored with their
1558 allocated size in the bytes preceding the string; even the
1559 constant 'empty' string has to be this way, so the code that
1560 checks to see if there is enough room for a new string doesn't
1561 have to have any special case checks
1564 static const struct {
1565 ast_string_field_allocation allocation;
1567 } __ast_string_field_empty_buffer;
1569 ast_string_field __ast_string_field_empty = __ast_string_field_empty_buffer.string;
1571 #define ALLOCATOR_OVERHEAD 48
1573 static size_t optimal_alloc_size(size_t size)
1577 size += ALLOCATOR_OVERHEAD;
1579 for (count = 1; size; size >>= 1, count++);
1581 return (1 << count) - ALLOCATOR_OVERHEAD;
1584 /*! \brief add a new block to the pool.
1585 * We can only allocate from the topmost pool, so the
1586 * fields in *mgr reflect the size of that only.
1588 static int add_string_pool(struct ast_string_field_mgr *mgr, struct ast_string_field_pool **pool_head,
1589 size_t size, const char *file, int lineno, const char *func)
1591 struct ast_string_field_pool *pool;
1592 size_t alloc_size = optimal_alloc_size(sizeof(*pool) + size);
1594 #if defined(__AST_DEBUG_MALLOC)
1595 if (!(pool = __ast_calloc(1, alloc_size, file, lineno, func))) {
1599 if (!(pool = ast_calloc(1, alloc_size))) {
1604 pool->prev = *pool_head;
1605 pool->size = alloc_size - sizeof(*pool);
1607 mgr->last_alloc = NULL;
1613 * This is an internal API, code should not use it directly.
1614 * It initializes all fields as empty, then uses 'size' for 3 functions:
1615 * size > 0 means initialize the pool list with a pool of given size.
1616 * This must be called right after allocating the object.
1617 * size = 0 means release all pools except the most recent one.
1618 * If the first pool was allocated via embedding in another
1619 * object, that pool will be preserved instead.
1620 * This is useful to e.g. reset an object to the initial value.
1621 * size < 0 means release all pools.
1622 * This must be done before destroying the object.
1624 int __ast_string_field_init(struct ast_string_field_mgr *mgr, struct ast_string_field_pool **pool_head,
1625 int needed, const char *file, int lineno, const char *func)
1627 const char **p = (const char **) pool_head + 1;
1628 struct ast_string_field_pool *cur = NULL;
1629 struct ast_string_field_pool *preserve = NULL;
1631 /* clear fields - this is always necessary */
1632 while ((struct ast_string_field_mgr *) p != mgr) {
1633 *p++ = __ast_string_field_empty;
1636 mgr->last_alloc = NULL;
1637 #if defined(__AST_DEBUG_MALLOC)
1638 mgr->owner_file = file;
1639 mgr->owner_func = func;
1640 mgr->owner_line = lineno;
1642 if (needed > 0) { /* allocate the initial pool */
1644 mgr->embedded_pool = NULL;
1645 return add_string_pool(mgr, pool_head, needed, file, lineno, func);
1648 /* if there is an embedded pool, we can't actually release *all*
1649 * pools, we must keep the embedded one. if the caller is about
1650 * to free the structure that contains the stringfield manager
1651 * and embedded pool anyway, it will be freed as part of that
1654 if ((needed < 0) && mgr->embedded_pool) {
1658 if (needed < 0) { /* reset all pools */
1660 } else if (mgr->embedded_pool) { /* preserve the embedded pool */
1661 preserve = mgr->embedded_pool;
1663 } else { /* preserve the last pool */
1664 if (*pool_head == NULL) {
1665 ast_log(LOG_WARNING, "trying to reset empty pool\n");
1668 preserve = *pool_head;
1669 cur = preserve->prev;
1673 preserve->prev = NULL;
1674 preserve->used = preserve->active = 0;
1678 struct ast_string_field_pool *prev = cur->prev;
1680 if (cur != preserve) {
1686 *pool_head = preserve;
1691 ast_string_field __ast_string_field_alloc_space(struct ast_string_field_mgr *mgr,
1692 struct ast_string_field_pool **pool_head, size_t needed)
1694 char *result = NULL;
1695 size_t space = (*pool_head)->size - (*pool_head)->used;
1698 /* Make room for ast_string_field_allocation and make it a multiple of that. */
1699 to_alloc = ast_make_room_for(needed, ast_string_field_allocation);
1700 ast_assert(to_alloc % ast_alignof(ast_string_field_allocation) == 0);
1702 if (__builtin_expect(to_alloc > space, 0)) {
1703 size_t new_size = (*pool_head)->size;
1705 while (new_size < to_alloc) {
1709 #if defined(__AST_DEBUG_MALLOC)
1710 if (add_string_pool(mgr, pool_head, new_size, mgr->owner_file, mgr->owner_line, mgr->owner_func))
1713 if (add_string_pool(mgr, pool_head, new_size, __FILE__, __LINE__, __FUNCTION__))
1718 /* pool->base is always aligned (gcc aligned attribute). We ensure that
1719 * to_alloc is also a multiple of ast_alignof(ast_string_field_allocation)
1720 * causing result to always be aligned as well; which in turn fixes that
1721 * AST_STRING_FIELD_ALLOCATION(result) is aligned. */
1722 result = (*pool_head)->base + (*pool_head)->used;
1723 (*pool_head)->used += to_alloc;
1724 (*pool_head)->active += needed;
1725 result += ast_alignof(ast_string_field_allocation);
1726 AST_STRING_FIELD_ALLOCATION(result) = needed;
1727 mgr->last_alloc = result;
1732 int __ast_string_field_ptr_grow(struct ast_string_field_mgr *mgr,
1733 struct ast_string_field_pool **pool_head, size_t needed,
1734 const ast_string_field *ptr)
1736 ssize_t grow = needed - AST_STRING_FIELD_ALLOCATION(*ptr);
1737 size_t space = (*pool_head)->size - (*pool_head)->used;
1739 if (*ptr != mgr->last_alloc) {
1747 (*pool_head)->used += grow;
1748 (*pool_head)->active += grow;
1749 AST_STRING_FIELD_ALLOCATION(*ptr) += grow;
1754 void __ast_string_field_release_active(struct ast_string_field_pool *pool_head,
1755 const ast_string_field ptr)
1757 struct ast_string_field_pool *pool, *prev;
1759 if (ptr == __ast_string_field_empty) {
1763 for (pool = pool_head, prev = NULL; pool; prev = pool, pool = pool->prev) {
1764 if ((ptr >= pool->base) && (ptr <= (pool->base + pool->size))) {
1765 pool->active -= AST_STRING_FIELD_ALLOCATION(ptr);
1766 if ((pool->active == 0) && prev) {
1767 prev->prev = pool->prev;
1775 void __ast_string_field_ptr_build_va(struct ast_string_field_mgr *mgr,
1776 struct ast_string_field_pool **pool_head,
1777 ast_string_field *ptr, const char *format, va_list ap)
1781 size_t space = (*pool_head)->size - (*pool_head)->used;
1786 /* if the field already has space allocated, try to reuse it;
1787 otherwise, try to use the empty space at the end of the current
1790 if (*ptr != __ast_string_field_empty) {
1791 target = (char *) *ptr;
1792 available = AST_STRING_FIELD_ALLOCATION(*ptr);
1793 if (*ptr == mgr->last_alloc) {
1797 /* pool->used is always a multiple of ast_alignof(ast_string_field_allocation)
1798 * so we don't need to re-align anything here.
1800 target = (*pool_head)->base + (*pool_head)->used + ast_alignof(ast_string_field_allocation);
1801 available = space - ast_alignof(ast_string_field_allocation);
1805 needed = vsnprintf(target, available, format, ap2) + 1;
1808 if (needed > available) {
1809 /* the allocation could not be satisfied using the field's current allocation
1810 (if it has one), or the space available in the pool (if it does not). allocate
1811 space for it, adding a new string pool if necessary.
1813 if (!(target = (char *) __ast_string_field_alloc_space(mgr, pool_head, needed))) {
1816 vsprintf(target, format, ap);
1817 va_end(ap); /* XXX va_end without va_start? */
1818 __ast_string_field_release_active(*pool_head, *ptr);
1820 } else if (*ptr != target) {
1821 /* the allocation was satisfied using available space in the pool, but not
1822 using the space already allocated to the field
1824 __ast_string_field_release_active(*pool_head, *ptr);
1825 mgr->last_alloc = *ptr = target;
1826 AST_STRING_FIELD_ALLOCATION(target) = needed;
1827 (*pool_head)->used += ast_make_room_for(needed, ast_string_field_allocation);
1828 (*pool_head)->active += needed;
1829 } else if ((grow = (needed - AST_STRING_FIELD_ALLOCATION(*ptr))) > 0) {
1830 /* the allocation was satisfied by using available space in the pool *and*
1831 the field was the last allocated field from the pool, so it grew
1833 AST_STRING_FIELD_ALLOCATION(*ptr) += grow;
1834 (*pool_head)->used += ast_align_for(grow, ast_string_field_allocation);
1835 (*pool_head)->active += grow;
1839 void __ast_string_field_ptr_build(struct ast_string_field_mgr *mgr,
1840 struct ast_string_field_pool **pool_head,
1841 ast_string_field *ptr, const char *format, ...)
1845 va_start(ap, format);
1846 __ast_string_field_ptr_build_va(mgr, pool_head, ptr, format, ap);
1850 void *__ast_calloc_with_stringfields(unsigned int num_structs, size_t struct_size, size_t field_mgr_offset,
1851 size_t field_mgr_pool_offset, size_t pool_size, const char *file,
1852 int lineno, const char *func)
1854 struct ast_string_field_mgr *mgr;
1855 struct ast_string_field_pool *pool;
1856 struct ast_string_field_pool **pool_head;
1857 size_t pool_size_needed = sizeof(*pool) + pool_size;
1858 size_t size_to_alloc = optimal_alloc_size(struct_size + pool_size_needed);
1862 #if defined(__AST_DEBUG_MALLOC)
1863 if (!(allocation = __ast_calloc(num_structs, size_to_alloc, file, lineno, func))) {
1867 if (!(allocation = ast_calloc(num_structs, size_to_alloc))) {
1872 for (x = 0; x < num_structs; x++) {
1873 void *base = allocation + (size_to_alloc * x);
1876 mgr = base + field_mgr_offset;
1877 pool_head = base + field_mgr_pool_offset;
1878 pool = base + struct_size;
1880 p = (const char **) pool_head + 1;
1881 while ((struct ast_string_field_mgr *) p != mgr) {
1882 *p++ = __ast_string_field_empty;
1885 mgr->embedded_pool = pool;
1887 pool->size = size_to_alloc - struct_size - sizeof(*pool);
1888 #if defined(__AST_DEBUG_MALLOC)
1889 mgr->owner_file = file;
1890 mgr->owner_func = func;
1891 mgr->owner_line = lineno;
1898 /* end of stringfields support */
1900 AST_MUTEX_DEFINE_STATIC(fetchadd_m); /* used for all fetc&add ops */
1902 int ast_atomic_fetchadd_int_slow(volatile int *p, int v)
1905 ast_mutex_lock(&fetchadd_m);
1908 ast_mutex_unlock(&fetchadd_m);
1913 * get values from config variables.
1915 int ast_get_timeval(const char *src, struct timeval *dst, struct timeval _default, int *consumed)
1917 long double dtv = 0.0;
1925 if (ast_strlen_zero(src))
1928 /* only integer at the moment, but one day we could accept more formats */
1929 if (sscanf(src, "%30Lf%n", &dtv, &scanned) > 0) {
1931 dst->tv_usec = (dtv - dst->tv_sec) * 1000000.0;
1933 *consumed = scanned;
1940 * get values from config variables.
1942 int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed)
1952 if (ast_strlen_zero(src))
1955 /* only integer at the moment, but one day we could accept more formats */
1956 if (sscanf(src, "%30ld%n", &t, &scanned) == 1) {
1959 *consumed = scanned;
1965 void ast_enable_packet_fragmentation(int sock)
1967 #if defined(HAVE_IP_MTU_DISCOVER)
1968 int val = IP_PMTUDISC_DONT;
1970 if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
1971 ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
1972 #endif /* HAVE_IP_MTU_DISCOVER */
1975 int ast_mkdir(const char *path, int mode)
1978 int len = strlen(path), count = 0, x, piececount = 0;
1979 char *tmp = ast_strdupa(path);
1981 char *fullpath = alloca(len + 1);
1984 for (ptr = tmp; *ptr; ptr++) {
1989 /* Count the components to the directory path */
1990 pieces = alloca(count * sizeof(*pieces));
1991 for (ptr = tmp; *ptr; ptr++) {
1994 pieces[piececount++] = ptr + 1;
1999 for (x = 0; x < piececount; x++) {
2000 /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
2001 strcat(fullpath, "/");
2002 strcat(fullpath, pieces[x]);
2003 res = mkdir(fullpath, mode);
2004 if (res && errno != EEXIST)
2010 int ast_utils_init(void)
2012 #ifdef HAVE_DEV_URANDOM
2013 dev_urandom_fd = open("/dev/urandom", O_RDONLY);
2016 #ifdef DEBUG_THREADS
2017 #if !defined(LOW_MEMORY)
2018 ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
2026 *\brief Parse digest authorization header.
2027 *\return Returns -1 if we have no auth or something wrong with digest.
2028 *\note This function may be used for Digest request and responce header.
2029 * request arg is set to nonzero, if we parse Digest Request.
2030 * pedantic arg can be set to nonzero if we need to do addition Digest check.
2032 int ast_parse_digest(const char *digest, struct ast_http_digest *d, int request, int pedantic) {
2034 struct ast_str *str = ast_str_create(16);
2036 /* table of recognised keywords, and places where they should be copied */
2039 const ast_string_field *field;
2041 { "username=", &d->username },
2042 { "realm=", &d->realm },
2043 { "nonce=", &d->nonce },
2044 { "uri=", &d->uri },
2045 { "domain=", &d->domain },
2046 { "response=", &d->response },
2047 { "cnonce=", &d->cnonce },
2048 { "opaque=", &d->opaque },
2049 /* Special cases that cannot be directly copied */
2050 { "algorithm=", NULL },
2056 if (ast_strlen_zero(digest) || !d || !str) {
2061 ast_str_set(&str, 0, "%s", digest);
2063 c = ast_skip_blanks(ast_str_buffer(str));
2065 if (strncasecmp(c, "Digest ", strlen("Digest "))) {
2066 ast_log(LOG_WARNING, "Missing Digest.\n");
2070 c += strlen("Digest ");
2072 /* lookup for keys/value pair */
2073 while (c && *c && *(c = ast_skip_blanks(c))) {
2075 for (i = keys; i->key != NULL; i++) {
2076 char *src, *separator;
2078 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
2082 /* Found. Skip keyword, take text in quotes or up to the separator. */
2083 c += strlen(i->key);
2092 strsep(&c, separator); /* clear separator and move ptr */
2094 ast_unescape_c(src);
2097 ast_string_field_ptr_set(d, i->field, src);
2099 /* Special cases that require additional procesing */
2100 if (!strcasecmp(i->key, "algorithm=")) {
2101 if (strcasecmp(src, "MD5")) {
2102 ast_log(LOG_WARNING, "Digest algorithm: \"%s\" not supported.\n", src);
2106 } else if (!strcasecmp(i->key, "qop=") && !strcasecmp(src, "auth")) {
2108 } else if (!strcasecmp(i->key, "nc=")) {
2110 if (sscanf(src, "%30lx", &u) != 1) {
2111 ast_log(LOG_WARNING, "Incorrect Digest nc value: \"%s\".\n", src);
2115 ast_string_field_set(d, nc, src);
2120 if (i->key == NULL) { /* not found, try ',' */
2126 /* Digest checkout */
2127 if (ast_strlen_zero(d->realm) || ast_strlen_zero(d->nonce)) {
2128 /* "realm" and "nonce" MUST be always exist */
2133 /* Additional check for Digest response */
2134 if (ast_strlen_zero(d->username) || ast_strlen_zero(d->uri) || ast_strlen_zero(d->response)) {
2138 if (pedantic && d->qop && (ast_strlen_zero(d->cnonce) || ast_strlen_zero(d->nc))) {
2146 #ifndef __AST_DEBUG_MALLOC
2147 int _ast_asprintf(char **ret, const char *file, int lineno, const char *func, const char *fmt, ...)
2153 if ((res = vasprintf(ret, fmt, ap)) == -1) {
2162 int ast_get_tid(void)
2165 #if defined (__linux) && defined(SYS_gettid)
2166 ret = syscall(SYS_gettid); /* available since Linux 1.4.11 */
2167 #elif defined(__sun)
2168 ret = pthread_self();
2169 #elif defined(__APPLE__)
2170 ret = mach_thread_self();
2171 mach_port_deallocate(mach_task_self(), ret);
2172 #elif defined(__FreeBSD__) && defined(HAVE_SYS_THR_H)
2174 thr_self(&lwpid); /* available since sys/thr.h creation 2003 */
2180 char *ast_utils_which(const char *binary, char *fullpath, size_t fullpath_size)
2182 const char *envPATH = getenv("PATH");
2188 tpath = ast_strdupa(envPATH);
2189 while ((path = strsep(&tpath, ":"))) {
2190 snprintf(fullpath, fullpath_size, "%s/%s", path, binary);
2191 if (!stat(fullpath, &unused)) {