2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * See http://www.asterisk.org for more information about
7 * the Asterisk project. Please do not directly contact
8 * any of the maintainers of this project for assistance;
9 * the project provides a web site, mailing lists and IRC
10 * channels for your use.
12 * This program is free software, distributed under the terms of
13 * the GNU General Public License Version 2. See the LICENSE file
14 * at the top of the source tree.
19 * \brief Utility functions
21 * \note These are important for portability and security,
22 * so please use them in favour of other routines.
23 * Please consult the CODING GUIDELINES for more information.
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33 #ifdef HAVE_DEV_URANDOM
37 #include "asterisk/network.h"
39 #define AST_API_MODULE /* ensure that inlinable API functions will be built in lock.h if required */
40 #include "asterisk/lock.h"
41 #include "asterisk/io.h"
42 #include "asterisk/md5.h"
43 #include "asterisk/sha1.h"
44 #include "asterisk/cli.h"
45 #include "asterisk/linkedlists.h"
47 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
48 #include "asterisk/strings.h"
50 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
51 #include "asterisk/time.h"
53 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
54 #include "asterisk/stringfields.h"
56 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
57 #include "asterisk/utils.h"
59 #define AST_API_MODULE
60 #include "asterisk/threadstorage.h"
62 #define AST_API_MODULE
63 #include "asterisk/config.h"
65 static char base64[64];
68 AST_THREADSTORAGE(inet_ntoa_buf);
70 #if !defined(HAVE_GETHOSTBYNAME_R_5) && !defined(HAVE_GETHOSTBYNAME_R_6)
72 #define ERANGE 34 /*!< duh? ERANGE value copied from web... */
75 AST_MUTEX_DEFINE_STATIC(__mutex);
77 /*! \brief Reentrant replacement for gethostbyname for BSD-based systems.
79 routine is derived from code originally written and placed in the public
80 domain by Enzo Michelangeli <em@em.no-ip.com> */
82 static int gethostbyname_r (const char *name, struct hostent *ret, char *buf,
83 size_t buflen, struct hostent **result,
88 ast_mutex_lock(&__mutex); /* begin critical area */
91 ph = gethostbyname(name);
92 *h_errnop = h_errno; /* copy h_errno to *h_herrnop */
99 int naddr = 0, naliases = 0;
100 /* determine if we have enough space in buf */
102 /* count how many addresses */
103 for (p = ph->h_addr_list; *p != 0; p++) {
104 nbytes += ph->h_length; /* addresses */
105 nbytes += sizeof(*p); /* pointers */
108 nbytes += sizeof(*p); /* one more for the terminating NULL */
110 /* count how many aliases, and total length of strings */
111 for (p = ph->h_aliases; *p != 0; p++) {
112 nbytes += (strlen(*p)+1); /* aliases */
113 nbytes += sizeof(*p); /* pointers */
116 nbytes += sizeof(*p); /* one more for the terminating NULL */
118 /* here nbytes is the number of bytes required in buffer */
119 /* as a terminator must be there, the minimum value is ph->h_length */
120 if (nbytes > buflen) {
122 ast_mutex_unlock(&__mutex); /* end critical area */
123 return ERANGE; /* not enough space in buf!! */
126 /* There is enough space. Now we need to do a deep copy! */
127 /* Allocation in buffer:
128 from [0] to [(naddr-1) * sizeof(*p)]:
129 pointers to addresses
130 at [naddr * sizeof(*p)]:
132 from [(naddr+1) * sizeof(*p)] to [(naddr+naliases) * sizeof(*p)] :
134 at [(naddr+naliases+1) * sizeof(*p)]:
136 then naddr addresses (fixed length), and naliases aliases (asciiz).
139 *ret = *ph; /* copy whole structure (not its address!) */
142 q = (char **)buf; /* pointer to pointers area (type: char **) */
143 ret->h_addr_list = q; /* update pointer to address list */
144 pbuf = buf + ((naddr + naliases + 2) * sizeof(*p)); /* skip that area */
145 for (p = ph->h_addr_list; *p != 0; p++) {
146 memcpy(pbuf, *p, ph->h_length); /* copy address bytes */
147 *q++ = pbuf; /* the pointer is the one inside buf... */
148 pbuf += ph->h_length; /* advance pbuf */
150 *q++ = NULL; /* address list terminator */
153 ret->h_aliases = q; /* update pointer to aliases list */
154 for (p = ph->h_aliases; *p != 0; p++) {
155 strcpy(pbuf, *p); /* copy alias strings */
156 *q++ = pbuf; /* the pointer is the one inside buf... */
157 pbuf += strlen(*p); /* advance pbuf */
158 *pbuf++ = 0; /* string terminator */
160 *q++ = NULL; /* terminator */
162 strcpy(pbuf, ph->h_name); /* copy alias strings */
164 pbuf += strlen(ph->h_name); /* advance pbuf */
165 *pbuf++ = 0; /* string terminator */
167 *result = ret; /* and let *result point to structure */
170 h_errno = hsave; /* restore h_errno */
171 ast_mutex_unlock(&__mutex); /* end critical area */
173 return (*result == NULL); /* return 0 on success, non-zero on error */
179 /*! \brief Re-entrant (thread safe) version of gethostbyname that replaces the
180 standard gethostbyname (which is not thread safe)
182 struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp)
188 struct hostent *result = NULL;
189 /* Although it is perfectly legitimate to lookup a pure integer, for
190 the sake of the sanity of people who like to name their peers as
191 integers, we break with tradition and refuse to look up a
198 else if (!isdigit(*s))
203 /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
206 memset(hp, 0, sizeof(struct ast_hostent));
207 hp->hp.h_addrtype = AF_INET;
208 hp->hp.h_addr_list = (void *) hp->buf;
209 hp->hp.h_addr = hp->buf + sizeof(void *);
210 if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
215 #ifdef HAVE_GETHOSTBYNAME_R_5
216 result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);
218 if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
221 res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
223 if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
231 AST_MUTEX_DEFINE_STATIC(test_lock);
232 AST_MUTEX_DEFINE_STATIC(test_lock2);
233 static pthread_t test_thread;
234 static int lock_count = 0;
235 static int test_errors = 0;
237 /*! \brief This is a regression test for recursive mutexes.
238 test_for_thread_safety() will return 0 if recursive mutex locks are
239 working properly, and non-zero if they are not working properly. */
240 static void *test_thread_body(void *data)
242 ast_mutex_lock(&test_lock);
244 if (lock_count != 10)
246 ast_mutex_lock(&test_lock);
248 if (lock_count != 20)
250 ast_mutex_lock(&test_lock2);
251 ast_mutex_unlock(&test_lock);
253 if (lock_count != 10)
255 ast_mutex_unlock(&test_lock);
257 ast_mutex_unlock(&test_lock2);
263 int test_for_thread_safety(void)
265 ast_mutex_lock(&test_lock2);
266 ast_mutex_lock(&test_lock);
268 ast_mutex_lock(&test_lock);
270 ast_pthread_create(&test_thread, NULL, test_thread_body, NULL);
274 ast_mutex_unlock(&test_lock);
279 ast_mutex_unlock(&test_lock);
283 ast_mutex_unlock(&test_lock2);
287 pthread_join(test_thread, NULL);
288 return(test_errors); /* return 0 on success. */
291 /*! \brief Produce 32 char MD5 hash of value. */
292 void ast_md5_hash(char *output, char *input)
294 struct MD5Context md5;
295 unsigned char digest[16];
300 MD5Update(&md5, (unsigned char *)input, strlen(input));
301 MD5Final(digest, &md5);
303 for (x = 0; x < 16; x++)
304 ptr += sprintf(ptr, "%2.2x", digest[x]);
307 /*! \brief Produce 40 char SHA1 hash of value. */
308 void ast_sha1_hash(char *output, char *input)
310 struct SHA1Context sha;
313 uint8_t Message_Digest[20];
317 SHA1Input(&sha, (const unsigned char *) input, strlen(input));
319 SHA1Result(&sha, Message_Digest);
321 for (x = 0; x < 20; x++)
322 ptr += sprintf(ptr, "%2.2x", Message_Digest[x]);
325 /*! \brief decode BASE64 encoded text */
326 int ast_base64decode(unsigned char *dst, const char *src, int max)
329 unsigned int byte = 0;
330 unsigned int bits = 0;
332 while (*src && (cnt < max)) {
333 /* Shift in 6 bits of input */
335 byte |= (b2a[(int)(*src)]) & 0x3f;
339 /* If we have at least 8 bits left over, take that character
343 *dst = (byte >> bits) & 0xff;
348 /* Dont worry about left over bits, they're extra anyway */
352 /*! \brief encode text to BASE64 coding */
353 int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
357 unsigned int byte = 0;
360 /* Reserve space for null byte at end of string */
362 while ((cntin < srclen) && (cnt < max)) {
367 if ((bits == 24) && (cnt + 4 <= max)) {
368 *dst++ = base64[(byte >> 18) & 0x3f];
369 *dst++ = base64[(byte >> 12) & 0x3f];
370 *dst++ = base64[(byte >> 6) & 0x3f];
371 *dst++ = base64[byte & 0x3f];
377 if (linebreaks && (cnt < max) && (col == 64)) {
383 if (bits && (cnt + 4 <= max)) {
384 /* Add one last character for the remaining bits,
385 padding the rest with 0 */
387 *dst++ = base64[(byte >> 18) & 0x3f];
388 *dst++ = base64[(byte >> 12) & 0x3f];
390 *dst++ = base64[(byte >> 6) & 0x3f];
396 if (linebreaks && (cnt < max)) {
404 int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
406 return ast_base64encode_full(dst, src, srclen, max, 0);
409 static void base64_init(void)
412 memset(b2a, -1, sizeof(b2a));
413 /* Initialize base-64 Conversion table */
414 for (x = 0; x < 26; x++) {
419 base64[x + 26] = 'a' + x;
420 b2a['a' + x] = x + 26;
423 base64[x + 52] = '0' + x;
424 b2a['0' + x] = x + 52;
433 /*! \brief ast_uri_encode: Turn text string to URI-encoded %XX version
434 \note At this point, we're converting from ISO-8859-x (8-bit), not UTF8
435 as in the SIP protocol spec
436 If doreserved == 1 we will convert reserved characters also.
437 RFC 2396, section 2.4
438 outbuf needs to have more memory allocated than the instring
439 to have room for the expansion. Every char that is converted
440 is replaced by three ASCII characters.
442 Note: The doreserved option is needed for replaces header in
445 char *ast_uri_encode(const char *string, char *outbuf, int buflen, int doreserved)
447 char *reserved = ";/?:@&=+$,# "; /* Reserved chars */
449 const char *ptr = string; /* Start with the string */
453 ast_copy_string(outbuf, string, buflen);
455 /* If there's no characters to convert, just go through and don't do anything */
457 if ((*ptr < 32 || (unsigned char) *ptr) > 127 || (doreserved && strchr(reserved, *ptr)) ) {
458 /* Oops, we need to start working here */
461 out = buf + (ptr - string) ; /* Set output ptr */
463 out += sprintf(out, "%%%02x", (unsigned char) *ptr);
465 *out = *ptr; /* Continue copying the string */
475 /*! \brief ast_uri_decode: Decode SIP URI, URN, URL (overwrite the string) */
476 void ast_uri_decode(char *s)
481 for (o = s; *s; s++, o++) {
482 if (*s == '%' && strlen(s) > 2 && sscanf(s + 1, "%2x", &tmp) == 1) {
483 /* have '%', two chars and correct parsing */
485 s += 2; /* Will be incremented once more when we break out */
486 } else /* all other cases, just copy */
492 /*! \brief ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa */
493 const char *ast_inet_ntoa(struct in_addr ia)
497 if (!(buf = ast_threadstorage_get(&inet_ntoa_buf, INET_ADDRSTRLEN)))
500 return inet_ntop(AF_INET, &ia, buf, INET_ADDRSTRLEN);
503 #ifdef HAVE_DEV_URANDOM
504 static int dev_urandom_fd;
508 #undef pthread_create /* For ast_pthread_create function only */
509 #endif /* !__linux__ */
511 #if !defined(LOW_MEMORY)
515 /*! \brief A reasonable maximum number of locks a thread would be holding ... */
516 #define AST_MAX_LOCKS 64
518 /* Allow direct use of pthread_mutex_t and friends */
519 #undef pthread_mutex_t
520 #undef pthread_mutex_lock
521 #undef pthread_mutex_unlock
522 #undef pthread_mutex_init
523 #undef pthread_mutex_destroy
526 * \brief Keep track of which locks a thread holds
528 * There is an instance of this struct for every active thread
530 struct thr_lock_info {
531 /*! The thread's ID */
533 /*! The thread name which includes where the thread was started */
534 const char *thread_name;
535 /*! This is the actual container of info for what locks this thread holds */
540 const char *lock_name;
543 enum ast_lock_type type;
544 /*! This thread is waiting on this lock */
547 struct ast_bt *backtrace;
549 } locks[AST_MAX_LOCKS];
550 /*! This is the number of locks currently held by this thread.
551 * The index (num_locks - 1) has the info on the last one in the
553 unsigned int num_locks;
554 /*! Protects the contents of the locks member
555 * Intentionally not ast_mutex_t */
556 pthread_mutex_t lock;
557 AST_LIST_ENTRY(thr_lock_info) entry;
561 * \brief Locked when accessing the lock_infos list
563 AST_MUTEX_DEFINE_STATIC(lock_infos_lock);
565 * \brief A list of each thread's lock info
567 static AST_LIST_HEAD_NOLOCK_STATIC(lock_infos, thr_lock_info);
570 * \brief Destroy a thread's lock info
572 * This gets called automatically when the thread stops
574 static void lock_info_destroy(void *data)
576 struct thr_lock_info *lock_info = data;
579 pthread_mutex_lock(&lock_infos_lock.mutex);
580 AST_LIST_REMOVE(&lock_infos, lock_info, entry);
581 pthread_mutex_unlock(&lock_infos_lock.mutex);
584 for (i = 0; i < lock_info->num_locks; i++) {
586 "Thread '%s' still has a lock! - '%s' (%p) from '%s' in %s:%d!\n",
587 lock_info->thread_name,
588 lock_info->locks[i].lock_name,
589 lock_info->locks[i].lock_addr,
590 lock_info->locks[i].func,
591 lock_info->locks[i].file,
592 lock_info->locks[i].line_num
596 pthread_mutex_destroy(&lock_info->lock);
597 if (lock_info->thread_name)
598 free((void *) lock_info->thread_name);
603 * \brief The thread storage key for per-thread lock info
605 AST_THREADSTORAGE_CUSTOM(thread_lock_info, NULL, lock_info_destroy);
607 void ast_store_lock_info(enum ast_lock_type type, const char *filename,
608 int line_num, const char *func, const char *lock_name, void *lock_addr, struct ast_bt *bt)
610 void ast_store_lock_info(enum ast_lock_type type, const char *filename,
611 int line_num, const char *func, const char *lock_name, void *lock_addr)
614 struct thr_lock_info *lock_info;
617 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
620 pthread_mutex_lock(&lock_info->lock);
622 for (i = 0; i < lock_info->num_locks; i++) {
623 if (lock_info->locks[i].lock_addr == lock_addr) {
624 lock_info->locks[i].times_locked++;
626 lock_info->locks[i].backtrace = bt;
628 pthread_mutex_unlock(&lock_info->lock);
633 if (lock_info->num_locks == AST_MAX_LOCKS) {
634 /* Can't use ast_log here, because it will cause infinite recursion */
635 fprintf(stderr, "XXX ERROR XXX A thread holds more locks than '%d'."
636 " Increase AST_MAX_LOCKS!\n", AST_MAX_LOCKS);
637 pthread_mutex_unlock(&lock_info->lock);
641 if (i && lock_info->locks[i - 1].pending == -1) {
642 /* The last lock on the list was one that this thread tried to lock but
643 * failed at doing so. It has now moved on to something else, so remove
644 * the old lock from the list. */
646 lock_info->num_locks--;
647 memset(&lock_info->locks[i], 0, sizeof(lock_info->locks[0]));
650 lock_info->locks[i].file = filename;
651 lock_info->locks[i].line_num = line_num;
652 lock_info->locks[i].func = func;
653 lock_info->locks[i].lock_name = lock_name;
654 lock_info->locks[i].lock_addr = lock_addr;
655 lock_info->locks[i].times_locked = 1;
656 lock_info->locks[i].type = type;
657 lock_info->locks[i].pending = 1;
659 lock_info->locks[i].backtrace = bt;
661 lock_info->num_locks++;
663 pthread_mutex_unlock(&lock_info->lock);
666 void ast_mark_lock_acquired(void *lock_addr)
668 struct thr_lock_info *lock_info;
670 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
673 pthread_mutex_lock(&lock_info->lock);
674 if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
675 lock_info->locks[lock_info->num_locks - 1].pending = 0;
677 pthread_mutex_unlock(&lock_info->lock);
680 void ast_mark_lock_failed(void *lock_addr)
682 struct thr_lock_info *lock_info;
684 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
687 pthread_mutex_lock(&lock_info->lock);
688 if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
689 lock_info->locks[lock_info->num_locks - 1].pending = -1;
690 lock_info->locks[lock_info->num_locks - 1].times_locked--;
692 pthread_mutex_unlock(&lock_info->lock);
695 int ast_find_lock_info(void *lock_addr, const char **filename, int *lineno, const char **func, const char **mutex_name)
697 struct thr_lock_info *lock_info;
700 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
703 pthread_mutex_lock(&lock_info->lock);
705 for (i = lock_info->num_locks - 1; i >= 0; i--) {
706 if (lock_info->locks[i].lock_addr == lock_addr)
711 /* Lock not found :( */
712 pthread_mutex_unlock(&lock_info->lock);
716 *filename = lock_info->locks[i].file;
717 *lineno = lock_info->locks[i].line_num;
718 *func = lock_info->locks[i].func;
719 *mutex_name = lock_info->locks[i].lock_name;
721 pthread_mutex_unlock(&lock_info->lock);
727 void ast_remove_lock_info(void *lock_addr, struct ast_bt *bt)
729 void ast_remove_lock_info(void *lock_addr)
732 struct thr_lock_info *lock_info;
735 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
738 pthread_mutex_lock(&lock_info->lock);
740 for (i = lock_info->num_locks - 1; i >= 0; i--) {
741 if (lock_info->locks[i].lock_addr == lock_addr)
746 /* Lock not found :( */
747 pthread_mutex_unlock(&lock_info->lock);
751 if (lock_info->locks[i].times_locked > 1) {
752 lock_info->locks[i].times_locked--;
754 lock_info->locks[i].backtrace = bt;
756 pthread_mutex_unlock(&lock_info->lock);
760 if (i < lock_info->num_locks - 1) {
761 /* Not the last one ... *should* be rare! */
762 memmove(&lock_info->locks[i], &lock_info->locks[i + 1],
763 (lock_info->num_locks - (i + 1)) * sizeof(lock_info->locks[0]));
766 lock_info->num_locks--;
768 pthread_mutex_unlock(&lock_info->lock);
771 static const char *locktype2str(enum ast_lock_type type)
786 static void append_backtrace_information(struct ast_str **str, struct ast_bt *bt)
791 ast_str_append(str, 0, "\tNo backtrace to print\n");
795 if ((symbols = backtrace_symbols(bt->addresses, bt->num_frames))) {
798 for (frame_iterator = 0; frame_iterator < bt->num_frames; ++frame_iterator) {
799 ast_str_append(str, 0, "\t%s\n", symbols[frame_iterator]);
804 ast_str_append(str, 0, "\tCouldn't retrieve backtrace symbols\n");
809 static void append_lock_information(struct ast_str **str, struct thr_lock_info *lock_info, int i)
813 struct ast_lock_track *lt;
815 ast_str_append(str, 0, "=== ---> %sLock #%d (%s): %s %d %s %s %p (%d)\n",
816 lock_info->locks[i].pending > 0 ? "Waiting for " :
817 lock_info->locks[i].pending < 0 ? "Tried and failed to get " : "", i,
818 lock_info->locks[i].file,
819 locktype2str(lock_info->locks[i].type),
820 lock_info->locks[i].line_num,
821 lock_info->locks[i].func, lock_info->locks[i].lock_name,
822 lock_info->locks[i].lock_addr,
823 lock_info->locks[i].times_locked);
825 append_backtrace_information(str, lock_info->locks[i].backtrace);
828 if (!lock_info->locks[i].pending || lock_info->locks[i].pending == -1)
831 /* We only have further details for mutexes right now */
832 if (lock_info->locks[i].type != AST_MUTEX)
835 lock = lock_info->locks[i].lock_addr;
837 ast_reentrancy_lock(lt);
838 for (j = 0; *str && j < lt->reentrancy; j++) {
839 ast_str_append(str, 0, "=== --- ---> Locked Here: %s line %d (%s)\n",
840 lt->file[j], lt->lineno[j], lt->func[j]);
842 ast_reentrancy_unlock(lt);
846 /*! This function can help you find highly temporal locks; locks that happen for a
847 short time, but at unexpected times, usually at times that create a deadlock,
848 Why is this thing locked right then? Who is locking it? Who am I fighting
851 To answer such questions, just call this routine before you would normally try
852 to aquire a lock. It doesn't do anything if the lock is not acquired. If the
853 lock is taken, it will publish a line or two to the console via ast_log().
855 Sometimes, the lock message is pretty uninformative. For instance, you might
856 find that the lock is being aquired deep within the astobj2 code; this tells
857 you little about higher level routines that call the astobj2 routines.
858 But, using gdb, you can set a break at the ast_log below, and for that
859 breakpoint, you can set the commands:
862 which will give a stack trace and continue. -- that aught to do the job!
865 void log_show_lock(void *this_lock_addr)
867 struct thr_lock_info *lock_info;
870 if (!(str = ast_str_create(4096))) {
871 ast_log(LOG_NOTICE,"Could not create str\n");
876 pthread_mutex_lock(&lock_infos_lock.mutex);
877 AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
879 pthread_mutex_lock(&lock_info->lock);
880 for (i = 0; str && i < lock_info->num_locks; i++) {
881 /* ONLY show info about this particular lock, if
883 if (lock_info->locks[i].lock_addr == this_lock_addr) {
884 append_lock_information(&str, lock_info, i);
885 ast_log(LOG_NOTICE, "%s", str->str);
889 pthread_mutex_unlock(&lock_info->lock);
891 pthread_mutex_unlock(&lock_infos_lock.mutex);
896 static char *handle_show_locks(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
898 struct thr_lock_info *lock_info;
901 if (!(str = ast_str_create(4096)))
906 e->command = "core show locks";
908 "Usage: core show locks\n"
909 " This command is for lock debugging. It prints out which locks\n"
910 "are owned by each active thread.\n";
917 ast_str_append(&str, 0, "\n"
918 "=======================================================================\n"
919 "=== Currently Held Locks ==============================================\n"
920 "=======================================================================\n"
922 "=== <pending> <lock#> (<file>): <lock type> <line num> <function> <lock name> <lock addr> (times locked)\n"
928 pthread_mutex_lock(&lock_infos_lock.mutex);
929 AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
931 if (lock_info->num_locks) {
932 ast_str_append(&str, 0, "=== Thread ID: %d (%s)\n", (int) lock_info->thread_id,
933 lock_info->thread_name);
934 pthread_mutex_lock(&lock_info->lock);
935 for (i = 0; str && i < lock_info->num_locks; i++) {
936 append_lock_information(&str, lock_info, i);
938 pthread_mutex_unlock(&lock_info->lock);
941 ast_str_append(&str, 0, "=== -------------------------------------------------------------------\n"
947 pthread_mutex_unlock(&lock_infos_lock.mutex);
952 ast_str_append(&str, 0, "=======================================================================\n"
958 ast_cli(a->fd, "%s", str->str);
965 static struct ast_cli_entry utils_cli[] = {
966 AST_CLI_DEFINE(handle_show_locks, "Show which locks are held by which thread"),
969 #endif /* DEBUG_THREADS */
972 * support for 'show threads'. The start routine is wrapped by
973 * dummy_start(), so that ast_register_thread() and
974 * ast_unregister_thread() know the thread identifier.
977 void *(*start_routine)(void *);
983 * on OS/X, pthread_cleanup_push() and pthread_cleanup_pop()
984 * are odd macros which start and end a block, so they _must_ be
985 * used in pairs (the latter with a '1' argument to call the
987 * On BSD we don't need this, but we keep it for compatibility.
989 static void *dummy_start(void *data)
992 struct thr_arg a = *((struct thr_arg *) data); /* make a local copy */
994 struct thr_lock_info *lock_info;
995 pthread_mutexattr_t mutex_attr;
998 /* note that even though data->name is a pointer to allocated memory,
999 we are not freeing it here because ast_register_thread is going to
1000 keep a copy of the pointer and then ast_unregister_thread will
1004 ast_register_thread(a.name);
1005 pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
1007 #ifdef DEBUG_THREADS
1008 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
1011 lock_info->thread_id = pthread_self();
1012 lock_info->thread_name = strdup(a.name);
1014 pthread_mutexattr_init(&mutex_attr);
1015 pthread_mutexattr_settype(&mutex_attr, AST_MUTEX_KIND);
1016 pthread_mutex_init(&lock_info->lock, &mutex_attr);
1017 pthread_mutexattr_destroy(&mutex_attr);
1019 pthread_mutex_lock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
1020 AST_LIST_INSERT_TAIL(&lock_infos, lock_info, entry);
1021 pthread_mutex_unlock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
1022 #endif /* DEBUG_THREADS */
1024 ret = a.start_routine(a.data);
1026 pthread_cleanup_pop(1);
1031 #endif /* !LOW_MEMORY */
1033 int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
1034 void *data, size_t stacksize, const char *file, const char *caller,
1035 int line, const char *start_fn)
1037 #if !defined(LOW_MEMORY)
1042 attr = alloca(sizeof(*attr));
1043 pthread_attr_init(attr);
1047 /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
1048 which is kind of useless. Change this here to
1049 PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
1050 priority will propagate down to new threads by default.
1051 This does mean that callers cannot set a different priority using
1052 PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
1053 the priority afterwards with pthread_setschedparam(). */
1054 if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
1055 ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
1059 stacksize = AST_STACKSIZE;
1061 if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
1062 ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
1064 #if !defined(LOW_MEMORY)
1065 if ((a = ast_malloc(sizeof(*a)))) {
1066 a->start_routine = start_routine;
1068 start_routine = dummy_start;
1069 asprintf(&a->name, "%-20s started at [%5d] %s %s()",
1070 start_fn, line, file, caller);
1073 #endif /* !LOW_MEMORY */
1075 return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
1079 int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
1080 void *data, size_t stacksize, const char *file, const char *caller,
1081 int line, const char *start_fn)
1083 unsigned char attr_destroy = 0;
1087 attr = alloca(sizeof(*attr));
1088 pthread_attr_init(attr);
1092 if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
1093 ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
1095 res = ast_pthread_create_stack(thread, attr, start_routine, data,
1096 stacksize, file, caller, line, start_fn);
1099 pthread_attr_destroy(attr);
1104 int ast_wait_for_input(int fd, int ms)
1106 struct pollfd pfd[1];
1107 memset(pfd, 0, sizeof(pfd));
1109 pfd[0].events = POLLIN|POLLPRI;
1110 return poll(pfd, 1, ms);
1114 * Try to write string, but wait no more than ms milliseconds before timing out.
1116 * \note The code assumes that the file descriptor has NONBLOCK set,
1117 * so there is only one system call made to do a write, unless we actually
1118 * have a need to wait. This way, we get better performance.
1119 * If the descriptor is blocking, all assumptions on the guaranteed
1120 * detail do not apply anymore.
1121 * Also note that in the current implementation, the delay is per-write,
1122 * so you still have no guarantees, anyways.
1123 * Fortunately the routine is only used in a few places (cli.c, manager.c,
1124 * res_agi.c) so it is reasonably easy to check how it behaves there.
1126 * XXX We either need to fix the code, or fix the documentation.
1128 int ast_carefulwrite(int fd, char *s, int len, int timeoutms)
1130 /* Try to write string, but wait no more than ms milliseconds
1131 before timing out */
1133 struct pollfd fds[1];
1135 res = write(fd, s, len);
1136 if ((res < 0) && (errno != EAGAIN)) {
1146 fds[0].events = POLLOUT;
1147 /* Wait until writable again */
1148 res = poll(fds, 1, timeoutms);
1156 char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
1162 if ((q = strchr(beg_quotes, *s)) && *q != '\0') {
1163 e = s + strlen(s) - 1;
1164 if (*e == *(end_quotes + (q - beg_quotes))) {
1173 char *ast_unescape_semicolon(char *s)
1178 while ((e = strchr(work, ';'))) {
1179 if ((e > work) && (*(e-1) == '\\')) {
1180 memmove(e - 1, e, strlen(e) + 1);
1190 /* !\brief unescape some C sequences in place, return pointer to the original string.
1192 char *ast_unescape_c(char *src)
1198 for (ret = dst = src; (c = *src++); *dst++ = c ) {
1200 continue; /* copy char at the end of the loop */
1201 switch ((c = *src++)) {
1202 case '\0': /* special, trailing '\' */
1205 case 'b': /* backspace */
1208 case 'f': /* form feed */
1221 /* default, use the char literally */
1227 int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap)
1231 if (!buffer || !*buffer || !space || !*space)
1234 result = vsnprintf(*buffer, *space, fmt, ap);
1238 else if (result > *space)
1246 int ast_build_string(char **buffer, size_t *space, const char *fmt, ...)
1252 result = ast_build_string_va(buffer, space, fmt, ap);
1258 int ast_true(const char *s)
1260 if (ast_strlen_zero(s))
1263 /* Determine if this is a true value */
1264 if (!strcasecmp(s, "yes") ||
1265 !strcasecmp(s, "true") ||
1266 !strcasecmp(s, "y") ||
1267 !strcasecmp(s, "t") ||
1268 !strcasecmp(s, "1") ||
1269 !strcasecmp(s, "on"))
1275 int ast_false(const char *s)
1277 if (ast_strlen_zero(s))
1280 /* Determine if this is a false value */
1281 if (!strcasecmp(s, "no") ||
1282 !strcasecmp(s, "false") ||
1283 !strcasecmp(s, "n") ||
1284 !strcasecmp(s, "f") ||
1285 !strcasecmp(s, "0") ||
1286 !strcasecmp(s, "off"))
1292 #define ONE_MILLION 1000000
1294 * put timeval in a valid range. usec is 0..999999
1295 * negative values are not allowed and truncated.
1297 static struct timeval tvfix(struct timeval a)
1299 if (a.tv_usec >= ONE_MILLION) {
1300 ast_log(LOG_WARNING, "warning too large timestamp %ld.%ld\n",
1301 (long)a.tv_sec, (long int) a.tv_usec);
1302 a.tv_sec += a.tv_usec / ONE_MILLION;
1303 a.tv_usec %= ONE_MILLION;
1304 } else if (a.tv_usec < 0) {
1305 ast_log(LOG_WARNING, "warning negative timestamp %ld.%ld\n",
1306 (long)a.tv_sec, (long int) a.tv_usec);
1312 struct timeval ast_tvadd(struct timeval a, struct timeval b)
1314 /* consistency checks to guarantee usec in 0..999999 */
1317 a.tv_sec += b.tv_sec;
1318 a.tv_usec += b.tv_usec;
1319 if (a.tv_usec >= ONE_MILLION) {
1321 a.tv_usec -= ONE_MILLION;
1326 struct timeval ast_tvsub(struct timeval a, struct timeval b)
1328 /* consistency checks to guarantee usec in 0..999999 */
1331 a.tv_sec -= b.tv_sec;
1332 a.tv_usec -= b.tv_usec;
1333 if (a.tv_usec < 0) {
1335 a.tv_usec += ONE_MILLION;
1341 /*! \brief glibc puts a lock inside random(3), so that the results are thread-safe.
1342 * BSD libc (and others) do not. */
1345 AST_MUTEX_DEFINE_STATIC(randomlock);
1348 long int ast_random(void)
1351 #ifdef HAVE_DEV_URANDOM
1352 if (dev_urandom_fd >= 0) {
1353 int read_res = read(dev_urandom_fd, &res, sizeof(res));
1355 long int rm = RAND_MAX;
1356 res = res < 0 ? ~res : res;
1365 ast_mutex_lock(&randomlock);
1367 ast_mutex_unlock(&randomlock);
1372 char *ast_process_quotes_and_slashes(char *start, char find, char replace_with)
1374 char *dataPut = start;
1378 for (; *start; start++) {
1380 *dataPut++ = *start; /* Always goes verbatim */
1383 if (*start == '\\') {
1384 inEscape = 1; /* Do not copy \ into the data */
1385 } else if (*start == '\'') {
1386 inQuotes = 1 - inQuotes; /* Do not copy ' into the data */
1388 /* Replace , with |, unless in quotes */
1389 *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
1393 if (start != dataPut)
1398 void ast_join(char *s, size_t len, char * const w[])
1403 /* Join words into a string */
1406 for (x = 0; ofs < len && w[x]; x++) {
1409 for (src = w[x]; *src && ofs < len; src++)
1418 * stringfields support routines.
1421 const char __ast_string_field_empty[] = ""; /*!< the empty string */
1423 /*! \brief add a new block to the pool.
1424 * We can only allocate from the topmost pool, so the
1425 * fields in *mgr reflect the size of that only.
1427 static int add_string_pool(struct ast_string_field_mgr *mgr,
1428 struct ast_string_field_pool **pool_head, size_t size)
1430 struct ast_string_field_pool *pool;
1432 if (!(pool = ast_calloc(1, sizeof(*pool) + size)))
1435 pool->prev = *pool_head;
1444 * This is an internal API, code should not use it directly.
1445 * It initializes all fields as empty, then uses 'size' for 3 functions:
1446 * size > 0 means initialize the pool list with a pool of given size.
1447 * This must be called right after allocating the object.
1448 * size = 0 means release all pools except the most recent one.
1449 * This is useful to e.g. reset an object to the initial value.
1450 * size < 0 means release all pools.
1451 * This must be done before destroying the object.
1453 int __ast_string_field_init(struct ast_string_field_mgr *mgr,
1454 struct ast_string_field_pool **pool_head, int size)
1456 const char **p = (const char **)pool_head + 1;
1457 struct ast_string_field_pool *cur = *pool_head;
1459 /* clear fields - this is always necessary */
1460 while ((struct ast_string_field_mgr *)p != mgr)
1461 *p++ = __ast_string_field_empty;
1462 if (size > 0) { /* allocate the initial pool */
1464 return add_string_pool(mgr, pool_head, size);
1466 if (size < 0) { /* reset all pools */
1468 } else { /* preserve the first pool */
1470 ast_log(LOG_WARNING, "trying to reset empty pool\n");
1474 (*pool_head)->prev = NULL;
1478 struct ast_string_field_pool *prev = cur->prev;
1485 ast_string_field __ast_string_field_alloc_space(struct ast_string_field_mgr *mgr,
1486 struct ast_string_field_pool **pool_head, size_t needed)
1488 char *result = NULL;
1489 size_t space = mgr->size - mgr->used;
1491 if (__builtin_expect(needed > space, 0)) {
1492 size_t new_size = mgr->size * 2;
1494 while (new_size < needed)
1497 if (add_string_pool(mgr, pool_head, new_size))
1501 result = (*pool_head)->base + mgr->used;
1502 mgr->used += needed;
1506 __attribute((format (printf, 4, 0)))
1507 void __ast_string_field_ptr_build_va(struct ast_string_field_mgr *mgr,
1508 struct ast_string_field_pool **pool_head,
1509 const ast_string_field *ptr, const char *format, va_list ap1, va_list ap2)
1512 char *dst = (*pool_head)->base + mgr->used;
1513 const char **p = (const char **)ptr;
1514 size_t space = mgr->size - mgr->used;
1516 /* try to write using available space */
1517 needed = vsnprintf(dst, space, format, ap1) + 1;
1521 if (needed > space) { /* if it fails, reallocate */
1522 size_t new_size = mgr->size * 2;
1524 while (new_size < needed)
1527 if (add_string_pool(mgr, pool_head, new_size))
1530 dst = (*pool_head)->base + mgr->used;
1531 vsprintf(dst, format, ap2);
1535 mgr->used += needed;
1538 __attribute((format (printf, 4, 5)))
1539 void __ast_string_field_ptr_build(struct ast_string_field_mgr *mgr,
1540 struct ast_string_field_pool **pool_head,
1541 const ast_string_field *ptr, const char *format, ...)
1545 va_start(ap1, format);
1546 va_start(ap2, format); /* va_copy does not exist on FreeBSD */
1548 __ast_string_field_ptr_build_va(mgr, pool_head, ptr, format, ap1, ap2);
1553 /* end of stringfields support */
1555 AST_MUTEX_DEFINE_STATIC(fetchadd_m); /* used for all fetc&add ops */
1557 int ast_atomic_fetchadd_int_slow(volatile int *p, int v)
1560 ast_mutex_lock(&fetchadd_m);
1563 ast_mutex_unlock(&fetchadd_m);
1568 * get values from config variables.
1570 int ast_get_timeval(const char *src, struct timeval *dst, struct timeval _default, int *consumed)
1572 long double dtv = 0.0;
1580 if (ast_strlen_zero(src))
1583 /* only integer at the moment, but one day we could accept more formats */
1584 if (sscanf(src, "%Lf%n", &dtv, &scanned) > 0) {
1586 dst->tv_usec = (dtv - dst->tv_sec) * 1000000.0;
1588 *consumed = scanned;
1595 * get values from config variables.
1597 int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed)
1607 if (ast_strlen_zero(src))
1610 /* only integer at the moment, but one day we could accept more formats */
1611 if (sscanf(src, "%ld%n", &t, &scanned) == 1) {
1614 *consumed = scanned;
1621 * core handler for dynamic strings.
1622 * This is not meant to be called directly, but rather through the
1623 * various wrapper macros
1625 * ast_str_append(...)
1626 * ast_str_set_va(...)
1627 * ast_str_append_va(...)
1630 __attribute__((format (printf, 4, 0)))
1631 int __ast_str_helper(struct ast_str **buf, size_t max_len,
1632 int append, const char *fmt, va_list ap)
1635 int offset = (append && (*buf)->len) ? (*buf)->used : 0;
1638 max_len = (*buf)->len; /* don't exceed the allocated space */
1640 * Ask vsnprintf how much space we need. Remember that vsnprintf
1641 * does not count the final '\0' so we must add 1.
1643 res = vsnprintf((*buf)->str + offset, (*buf)->len - offset, fmt, ap);
1645 need = res + offset + 1;
1647 * If there is not enough space and we are below the max length,
1648 * reallocate the buffer and return a message telling to retry.
1650 if (need > (*buf)->len && (max_len == 0 || (*buf)->len < max_len) ) {
1651 if (max_len && max_len < need) /* truncate as needed */
1653 else if (max_len == 0) /* if unbounded, give more room for next time */
1654 need += 16 + need/4;
1655 if (0) /* debugging */
1656 ast_verbose("extend from %d to %d\n", (int)(*buf)->len, need);
1657 if (ast_str_make_space(buf, need)) {
1658 ast_verbose("failed to extend from %d to %d\n", (int)(*buf)->len, need);
1659 return AST_DYNSTR_BUILD_FAILED;
1661 (*buf)->str[offset] = '\0'; /* Truncate the partial write. */
1663 /* va_end() and va_start() must be done before calling
1664 * vsnprintf() again. */
1665 return AST_DYNSTR_BUILD_RETRY;
1667 /* update space used, keep in mind the truncation */
1668 (*buf)->used = (res + offset > (*buf)->len) ? (*buf)->len : res + offset;
1673 void ast_enable_packet_fragmentation(int sock)
1675 #if defined(HAVE_IP_MTU_DISCOVER)
1676 int val = IP_PMTUDISC_DONT;
1678 if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
1679 ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
1680 #endif /* HAVE_IP_MTU_DISCOVER */
1683 int ast_mkdir(const char *path, int mode)
1686 int len = strlen(path), count = 0, x, piececount = 0;
1687 char *tmp = ast_strdupa(path);
1689 char *fullpath = alloca(len + 1);
1692 for (ptr = tmp; *ptr; ptr++) {
1697 /* Count the components to the directory path */
1698 pieces = alloca(count * sizeof(*pieces));
1699 for (ptr = tmp; *ptr; ptr++) {
1702 pieces[piececount++] = ptr + 1;
1707 for (x = 0; x < piececount; x++) {
1708 /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
1709 strcat(fullpath, "/");
1710 strcat(fullpath, pieces[x]);
1711 res = mkdir(fullpath, mode);
1712 if (res && errno != EEXIST)
1718 int ast_utils_init(void)
1720 #ifdef HAVE_DEV_URANDOM
1721 dev_urandom_fd = open("/dev/urandom", O_RDONLY);
1724 #ifdef DEBUG_THREADS
1725 #if !defined(LOW_MEMORY)
1726 ast_cli_register_multiple(utils_cli, sizeof(utils_cli) / sizeof(utils_cli[0]));
1732 #ifndef __AST_DEBUG_MALLOC
1733 int _ast_asprintf(char **ret, const char *file, int lineno, const char *func, const char *fmt, ...)
1739 if ((res = vasprintf(ret, fmt, ap)) == -1) {