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$")
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 #define AST_API_MODULE /* ensure that inlinable API functions will be built in lock.h if required */
43 #include "asterisk/lock.h"
44 #include "asterisk/io.h"
45 #include "asterisk/logger.h"
46 #include "asterisk/md5.h"
47 #include "asterisk/sha1.h"
48 #include "asterisk/options.h"
49 #include "asterisk/cli.h"
50 #include "asterisk/linkedlists.h"
52 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
53 #include "asterisk/strings.h"
55 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
56 #include "asterisk/time.h"
58 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
59 #include "asterisk/stringfields.h"
61 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
62 #include "asterisk/utils.h"
64 #define AST_API_MODULE
65 #include "asterisk/threadstorage.h"
67 static char base64
[64];
70 AST_THREADSTORAGE(inet_ntoa_buf
, inet_ntoa_buf_init
);
72 #if !defined(HAVE_GETHOSTBYNAME_R_5) && !defined(HAVE_GETHOSTBYNAME_R_6)
74 #define ERANGE 34 /*!< duh? ERANGE value copied from web... */
77 AST_MUTEX_DEFINE_STATIC(__mutex
);
79 /*! \brief Reentrant replacement for gethostbyname for BSD-based systems.
81 routine is derived from code originally written and placed in the public
82 domain by Enzo Michelangeli <em@em.no-ip.com> */
84 static int gethostbyname_r (const char *name
, struct hostent
*ret
, char *buf
,
85 size_t buflen
, struct hostent
**result
,
90 ast_mutex_lock(&__mutex
); /* begin critical area */
93 ph
= gethostbyname(name
);
94 *h_errnop
= h_errno
; /* copy h_errno to *h_herrnop */
101 int naddr
=0, naliases
=0;
102 /* determine if we have enough space in buf */
104 /* count how many addresses */
105 for (p
= ph
->h_addr_list
; *p
!= 0; p
++) {
106 nbytes
+= ph
->h_length
; /* addresses */
107 nbytes
+= sizeof(*p
); /* pointers */
110 nbytes
+= sizeof(*p
); /* one more for the terminating NULL */
112 /* count how many aliases, and total length of strings */
113 for (p
= ph
->h_aliases
; *p
!= 0; p
++) {
114 nbytes
+= (strlen(*p
)+1); /* aliases */
115 nbytes
+= sizeof(*p
); /* pointers */
118 nbytes
+= sizeof(*p
); /* one more for the terminating NULL */
120 /* here nbytes is the number of bytes required in buffer */
121 /* as a terminator must be there, the minimum value is ph->h_length */
122 if (nbytes
> buflen
) {
124 ast_mutex_unlock(&__mutex
); /* end critical area */
125 return ERANGE
; /* not enough space in buf!! */
128 /* There is enough space. Now we need to do a deep copy! */
129 /* Allocation in buffer:
130 from [0] to [(naddr-1) * sizeof(*p)]:
131 pointers to addresses
132 at [naddr * sizeof(*p)]:
134 from [(naddr+1) * sizeof(*p)] to [(naddr+naliases) * sizeof(*p)] :
136 at [(naddr+naliases+1) * sizeof(*p)]:
138 then naddr addresses (fixed length), and naliases aliases (asciiz).
141 *ret
= *ph
; /* copy whole structure (not its address!) */
144 q
= (char **)buf
; /* pointer to pointers area (type: char **) */
145 ret
->h_addr_list
= q
; /* update pointer to address list */
146 pbuf
= buf
+ ((naddr
+ naliases
+ 2) * sizeof(*p
)); /* skip that area */
147 for (p
= ph
->h_addr_list
; *p
!= 0; p
++) {
148 memcpy(pbuf
, *p
, ph
->h_length
); /* copy address bytes */
149 *q
++ = pbuf
; /* the pointer is the one inside buf... */
150 pbuf
+= ph
->h_length
; /* advance pbuf */
152 *q
++ = NULL
; /* address list terminator */
155 ret
->h_aliases
= q
; /* update pointer to aliases list */
156 for (p
= ph
->h_aliases
; *p
!= 0; p
++) {
157 strcpy(pbuf
, *p
); /* copy alias strings */
158 *q
++ = pbuf
; /* the pointer is the one inside buf... */
159 pbuf
+= strlen(*p
); /* advance pbuf */
160 *pbuf
++ = 0; /* string terminator */
162 *q
++ = NULL
; /* terminator */
164 strcpy(pbuf
, ph
->h_name
); /* copy alias strings */
166 pbuf
+= strlen(ph
->h_name
); /* advance pbuf */
167 *pbuf
++ = 0; /* string terminator */
169 *result
= ret
; /* and let *result point to structure */
172 h_errno
= hsave
; /* restore h_errno */
173 ast_mutex_unlock(&__mutex
); /* end critical area */
175 return (*result
== NULL
); /* return 0 on success, non-zero on error */
181 /*! \brief Re-entrant (thread safe) version of gethostbyname that replaces the
182 standard gethostbyname (which is not thread safe)
184 struct hostent
*ast_gethostbyname(const char *host
, struct ast_hostent
*hp
)
190 struct hostent
*result
= NULL
;
191 /* Although it is perfectly legitimate to lookup a pure integer, for
192 the sake of the sanity of people who like to name their peers as
193 integers, we break with tradition and refuse to look up a
200 else if (!isdigit(*s
))
205 /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
208 memset(hp
, 0, sizeof(struct ast_hostent
));
209 hp
->hp
.h_addrtype
= AF_INET
;
210 hp
->hp
.h_addr_list
= (void *) hp
->buf
;
211 hp
->hp
.h_addr
= hp
->buf
+ sizeof(void *);
212 if (inet_pton(AF_INET
, host
, hp
->hp
.h_addr
) > 0)
217 #ifdef HAVE_GETHOSTBYNAME_R_5
218 result
= gethostbyname_r(host
, &hp
->hp
, hp
->buf
, sizeof(hp
->buf
), &herrno
);
220 if (!result
|| !hp
->hp
.h_addr_list
|| !hp
->hp
.h_addr_list
[0])
223 res
= gethostbyname_r(host
, &hp
->hp
, hp
->buf
, sizeof(hp
->buf
), &result
, &herrno
);
225 if (res
|| !result
|| !hp
->hp
.h_addr_list
|| !hp
->hp
.h_addr_list
[0])
233 AST_MUTEX_DEFINE_STATIC(test_lock
);
234 AST_MUTEX_DEFINE_STATIC(test_lock2
);
235 static pthread_t test_thread
;
236 static int lock_count
= 0;
237 static int test_errors
= 0;
239 /*! \brief This is a regression test for recursive mutexes.
240 test_for_thread_safety() will return 0 if recursive mutex locks are
241 working properly, and non-zero if they are not working properly. */
242 static void *test_thread_body(void *data
)
244 ast_mutex_lock(&test_lock
);
246 if (lock_count
!= 10)
248 ast_mutex_lock(&test_lock
);
250 if (lock_count
!= 20)
252 ast_mutex_lock(&test_lock2
);
253 ast_mutex_unlock(&test_lock
);
255 if (lock_count
!= 10)
257 ast_mutex_unlock(&test_lock
);
259 ast_mutex_unlock(&test_lock2
);
265 int test_for_thread_safety(void)
267 ast_mutex_lock(&test_lock2
);
268 ast_mutex_lock(&test_lock
);
270 ast_mutex_lock(&test_lock
);
272 ast_pthread_create(&test_thread
, NULL
, test_thread_body
, NULL
);
276 ast_mutex_unlock(&test_lock
);
281 ast_mutex_unlock(&test_lock
);
285 ast_mutex_unlock(&test_lock2
);
289 pthread_join(test_thread
, NULL
);
290 return(test_errors
); /* return 0 on success. */
293 /*! \brief Produce 32 char MD5 hash of value. */
294 void ast_md5_hash(char *output
, char *input
)
296 struct MD5Context md5
;
297 unsigned char digest
[16];
302 MD5Update(&md5
, (unsigned char *)input
, strlen(input
));
303 MD5Final(digest
, &md5
);
305 for (x
= 0; x
< 16; x
++)
306 ptr
+= sprintf(ptr
, "%2.2x", digest
[x
]);
309 /*! \brief Produce 40 char SHA1 hash of value. */
310 void ast_sha1_hash(char *output
, char *input
)
312 struct SHA1Context sha
;
315 uint8_t Message_Digest
[20];
319 SHA1Input(&sha
, (const unsigned char *) input
, strlen(input
));
321 SHA1Result(&sha
, Message_Digest
);
323 for (x
= 0; x
< 20; x
++)
324 ptr
+= sprintf(ptr
, "%2.2x", Message_Digest
[x
]);
327 /*! \brief decode BASE64 encoded text */
328 int ast_base64decode(unsigned char *dst
, const char *src
, int max
)
331 unsigned int byte
= 0;
332 unsigned int bits
= 0;
334 while(*src
&& (cnt
< max
)) {
335 /* Shift in 6 bits of input */
337 byte
|= (b2a
[(int)(*src
)]) & 0x3f;
341 /* If we have at least 8 bits left over, take that character
345 *dst
= (byte
>> bits
) & 0xff;
350 /* Dont worry about left over bits, they're extra anyway */
354 /*! \brief encode text to BASE64 coding */
355 int ast_base64encode_full(char *dst
, const unsigned char *src
, int srclen
, int max
, int linebreaks
)
359 unsigned int byte
= 0;
362 /* Reserve space for null byte at end of string */
364 while ((cntin
< srclen
) && (cnt
< max
)) {
369 if ((bits
== 24) && (cnt
+ 4 <= max
)) {
370 *dst
++ = base64
[(byte
>> 18) & 0x3f];
371 *dst
++ = base64
[(byte
>> 12) & 0x3f];
372 *dst
++ = base64
[(byte
>> 6) & 0x3f];
373 *dst
++ = base64
[byte
& 0x3f];
379 if (linebreaks
&& (cnt
< max
) && (col
== 64)) {
385 if (bits
&& (cnt
+ 4 <= max
)) {
386 /* Add one last character for the remaining bits,
387 padding the rest with 0 */
389 *dst
++ = base64
[(byte
>> 18) & 0x3f];
390 *dst
++ = base64
[(byte
>> 12) & 0x3f];
392 *dst
++ = base64
[(byte
>> 6) & 0x3f];
398 if (linebreaks
&& (cnt
< max
)) {
406 int ast_base64encode(char *dst
, const unsigned char *src
, int srclen
, int max
)
408 return ast_base64encode_full(dst
, src
, srclen
, max
, 0);
411 static void base64_init(void)
414 memset(b2a
, -1, sizeof(b2a
));
415 /* Initialize base-64 Conversion table */
416 for (x
= 0; x
< 26; x
++) {
421 base64
[x
+ 26] = 'a' + x
;
422 b2a
['a' + x
] = x
+ 26;
425 base64
[x
+ 52] = '0' + x
;
426 b2a
['0' + x
] = x
+ 52;
435 /*! \brief ast_uri_encode: Turn text string to URI-encoded %XX version
436 \note At this point, we're converting from ISO-8859-x (8-bit), not UTF8
437 as in the SIP protocol spec
438 If doreserved == 1 we will convert reserved characters also.
439 RFC 2396, section 2.4
440 outbuf needs to have more memory allocated than the instring
441 to have room for the expansion. Every char that is converted
442 is replaced by three ASCII characters.
444 Note: The doreserved option is needed for replaces header in
447 char *ast_uri_encode(const char *string
, char *outbuf
, int buflen
, int doreserved
)
449 char *reserved
= ";/?:@&=+$, "; /* Reserved chars */
451 const char *ptr
= string
; /* Start with the string */
455 ast_copy_string(outbuf
, string
, buflen
);
457 /* If there's no characters to convert, just go through and don't do anything */
459 if (((unsigned char) *ptr
) > 127 || (doreserved
&& strchr(reserved
, *ptr
)) ) {
460 /* Oops, we need to start working here */
463 out
= buf
+ (ptr
- string
) ; /* Set output ptr */
465 out
+= sprintf(out
, "%%%02x", (unsigned char) *ptr
);
467 *out
= *ptr
; /* Continue copying the string */
477 /*! \brief ast_uri_decode: Decode SIP URI, URN, URL (overwrite the string) */
478 void ast_uri_decode(char *s
)
483 for (o
= s
; *s
; s
++, o
++) {
484 if (*s
== '%' && strlen(s
) > 2 && sscanf(s
+ 1, "%2x", &tmp
) == 1) {
485 /* have '%', two chars and correct parsing */
487 s
+= 2; /* Will be incremented once more when we break out */
488 } else /* all other cases, just copy */
494 /*! \brief ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa */
495 const char *ast_inet_ntoa(struct in_addr ia
)
499 if (!(buf
= ast_threadstorage_get(&inet_ntoa_buf
, INET_ADDRSTRLEN
)))
502 return inet_ntop(AF_INET
, &ia
, buf
, INET_ADDRSTRLEN
);
506 #undef pthread_create /* For ast_pthread_create function only */
507 #endif /* !__linux__ */
509 #if !defined(LOW_MEMORY)
513 /*! \brief A reasonable maximum number of locks a thread would be holding ... */
514 #define AST_MAX_LOCKS 64
516 /* Allow direct use of pthread_mutex_t and friends */
517 #undef pthread_mutex_t
518 #undef pthread_mutex_lock
519 #undef pthread_mutex_unlock
520 #undef pthread_mutex_init
521 #undef pthread_mutex_destroy
524 * \brief Keep track of which locks a thread holds
526 * There is an instance of this struct for every active thread
528 struct thr_lock_info
{
529 /*! The thread's ID */
531 /*! The thread name which includes where the thread was started */
532 const char *thread_name
;
533 /*! This is the actual container of info for what locks this thread holds */
538 const char *lock_name
;
541 enum ast_lock_type type
;
542 /*! This thread is waiting on this lock */
544 } locks
[AST_MAX_LOCKS
];
545 /*! This is the number of locks currently held by this thread.
546 * The index (num_locks - 1) has the info on the last one in the
548 unsigned int num_locks
;
549 /*! Protects the contents of the locks member
550 * Intentionally not ast_mutex_t */
551 pthread_mutex_t lock
;
552 AST_LIST_ENTRY(thr_lock_info
) entry
;
556 * \brief Locked when accessing the lock_infos list
558 AST_MUTEX_DEFINE_STATIC(lock_infos_lock
);
560 * \brief A list of each thread's lock info
562 static AST_LIST_HEAD_NOLOCK_STATIC(lock_infos
, thr_lock_info
);
565 * \brief Destroy a thread's lock info
567 * This gets called automatically when the thread stops
569 static void lock_info_destroy(void *data
)
571 struct thr_lock_info
*lock_info
= data
;
573 pthread_mutex_lock(&lock_infos_lock
.mutex
);
574 AST_LIST_REMOVE(&lock_infos
, lock_info
, entry
);
575 pthread_mutex_unlock(&lock_infos_lock
.mutex
);
577 pthread_mutex_destroy(&lock_info
->lock
);
578 free((void *) lock_info
->thread_name
);
583 * \brief The thread storage key for per-thread lock info
585 AST_THREADSTORAGE_CUSTOM(thread_lock_info
, thread_lock_info_init
, lock_info_destroy
);
587 void ast_store_lock_info(enum ast_lock_type type
, const char *filename
,
588 int line_num
, const char *func
, const char *lock_name
, void *lock_addr
)
590 struct thr_lock_info
*lock_info
;
593 if (!(lock_info
= ast_threadstorage_get(&thread_lock_info
, sizeof(*lock_info
))))
596 pthread_mutex_lock(&lock_info
->lock
);
598 for (i
= 0; i
< lock_info
->num_locks
; i
++) {
599 if (lock_info
->locks
[i
].lock_addr
== lock_addr
) {
600 lock_info
->locks
[i
].times_locked
++;
601 pthread_mutex_unlock(&lock_info
->lock
);
606 if (lock_info
->num_locks
== AST_MAX_LOCKS
) {
607 /* Can't use ast_log here, because it will cause infinite recursion */
608 fprintf(stderr
, "XXX ERROR XXX A thread holds more locks than '%d'."
609 " Increase AST_MAX_LOCKS!\n", AST_MAX_LOCKS
);
610 pthread_mutex_unlock(&lock_info
->lock
);
614 if (i
&& lock_info
->locks
[i
].pending
== -1) {
615 /* The last lock on the list was one that this thread tried to lock but
616 * failed at doing so. It has now moved on to something else, so remove
617 * the old lock from the list. */
619 lock_info
->num_locks
--;
620 memset(&lock_info
->locks
[i
], 0, sizeof(lock_info
->locks
[0]));
623 lock_info
->locks
[i
].file
= filename
;
624 lock_info
->locks
[i
].line_num
= line_num
;
625 lock_info
->locks
[i
].func
= func
;
626 lock_info
->locks
[i
].lock_name
= lock_name
;
627 lock_info
->locks
[i
].lock_addr
= lock_addr
;
628 lock_info
->locks
[i
].times_locked
= 1;
629 lock_info
->locks
[i
].type
= type
;
630 lock_info
->locks
[i
].pending
= 1;
631 lock_info
->num_locks
++;
633 pthread_mutex_unlock(&lock_info
->lock
);
636 void ast_mark_lock_acquired(void *lock_addr
)
638 struct thr_lock_info
*lock_info
;
640 if (!(lock_info
= ast_threadstorage_get(&thread_lock_info
, sizeof(*lock_info
))))
643 pthread_mutex_lock(&lock_info
->lock
);
644 if (lock_info
->locks
[lock_info
->num_locks
- 1].lock_addr
== lock_addr
) {
645 lock_info
->locks
[lock_info
->num_locks
- 1].pending
= 0;
647 pthread_mutex_unlock(&lock_info
->lock
);
650 void ast_mark_lock_failed(void *lock_addr
)
652 struct thr_lock_info
*lock_info
;
654 if (!(lock_info
= ast_threadstorage_get(&thread_lock_info
, sizeof(*lock_info
))))
657 pthread_mutex_lock(&lock_info
->lock
);
658 if (lock_info
->locks
[lock_info
->num_locks
- 1].lock_addr
== lock_addr
) {
659 lock_info
->locks
[lock_info
->num_locks
- 1].pending
= -1;
660 lock_info
->locks
[lock_info
->num_locks
- 1].times_locked
--;
662 pthread_mutex_unlock(&lock_info
->lock
);
665 void ast_remove_lock_info(void *lock_addr
)
667 struct thr_lock_info
*lock_info
;
670 if (!(lock_info
= ast_threadstorage_get(&thread_lock_info
, sizeof(*lock_info
))))
673 pthread_mutex_lock(&lock_info
->lock
);
675 for (i
= lock_info
->num_locks
- 1; i
>= 0; i
--) {
676 if (lock_info
->locks
[i
].lock_addr
== lock_addr
)
681 /* Lock not found :( */
682 pthread_mutex_unlock(&lock_info
->lock
);
686 if (lock_info
->locks
[i
].times_locked
> 1) {
687 lock_info
->locks
[i
].times_locked
--;
688 pthread_mutex_unlock(&lock_info
->lock
);
692 if (i
< lock_info
->num_locks
- 1) {
693 /* Not the last one ... *should* be rare! */
694 memmove(&lock_info
->locks
[i
], &lock_info
->locks
[i
+ 1],
695 (lock_info
->num_locks
- (i
+ 1)) * sizeof(lock_info
->locks
[0]));
698 lock_info
->num_locks
--;
700 pthread_mutex_unlock(&lock_info
->lock
);
703 static const char *locktype2str(enum ast_lock_type type
)
717 static int handle_show_locks(int fd
, int argc
, char *argv
[])
719 struct thr_lock_info
*lock_info
;
720 struct ast_dynamic_str
*str
;
722 if (!(str
= ast_dynamic_str_create(4096)))
723 return RESULT_FAILURE
;
725 ast_dynamic_str_append(&str
, 0, "\n"
726 "=======================================================================\n"
727 "=== Currently Held Locks ==============================================\n"
728 "=======================================================================\n"
730 "=== <file> <line num> <function> <lock name> <lock addr> (times locked)\n"
734 return RESULT_FAILURE
;
736 pthread_mutex_lock(&lock_infos_lock
.mutex
);
737 AST_LIST_TRAVERSE(&lock_infos
, lock_info
, entry
) {
739 ast_dynamic_str_append(&str
, 0, "=== Thread ID: %u (%s)\n", (int) lock_info
->thread_id
,
740 lock_info
->thread_name
);
741 pthread_mutex_lock(&lock_info
->lock
);
742 for (i
= 0; str
&& i
< lock_info
->num_locks
; i
++) {
746 ast_dynamic_str_append(&str
, 0, "=== ---> %sLock #%d (%s): %s %d %s %s %p (%d)\n",
747 lock_info
->locks
[i
].pending
> 0 ? "Waiting for " :
748 lock_info
->locks
[i
].pending
< 0 ? "Tried and failed to get " : "", i
,
749 lock_info
->locks
[i
].file
,
750 locktype2str(lock_info
->locks
[i
].type
),
751 lock_info
->locks
[i
].line_num
,
752 lock_info
->locks
[i
].func
, lock_info
->locks
[i
].lock_name
,
753 lock_info
->locks
[i
].lock_addr
,
754 lock_info
->locks
[i
].times_locked
);
756 if (!lock_info
->locks
[i
].pending
|| lock_info
->locks
[i
].pending
== -1)
759 /* We only have further details for mutexes right now */
760 if (lock_info
->locks
[i
].type
!= AST_MUTEX
)
763 lock
= lock_info
->locks
[i
].lock_addr
;
765 ast_reentrancy_lock(lock
);
766 for (j
= 0; str
&& j
< lock
->reentrancy
; j
++) {
767 ast_dynamic_str_append(&str
, 0, "=== --- ---> Locked Here: %s line %d (%s)\n",
768 lock
->file
[j
], lock
->lineno
[j
], lock
->func
[j
]);
770 ast_reentrancy_unlock(lock
);
772 pthread_mutex_unlock(&lock_info
->lock
);
775 ast_dynamic_str_append(&str
, 0, "=== -------------------------------------------------------------------\n"
780 pthread_mutex_unlock(&lock_infos_lock
.mutex
);
783 return RESULT_FAILURE
;
785 ast_dynamic_str_append(&str
, 0, "=======================================================================\n"
789 return RESULT_FAILURE
;
791 ast_cli(fd
, "%s", str
->str
);
795 return RESULT_SUCCESS
;
798 static char show_locks_help
[] =
799 "Usage: core show locks\n"
800 " This command is for lock debugging. It prints out which locks\n"
801 "are owned by each active thread.\n";
803 static struct ast_cli_entry utils_cli
[] = {
804 { { "core", "show", "locks", NULL
}, handle_show_locks
,
805 "Show which locks are locked by which thread", show_locks_help
},
808 #endif /* DEBUG_THREADS */
813 * support for 'show threads'. The start routine is wrapped by
814 * dummy_start(), so that ast_register_thread() and
815 * ast_unregister_thread() know the thread identifier.
818 void *(*start_routine
)(void *);
824 * on OS/X, pthread_cleanup_push() and pthread_cleanup_pop()
825 * are odd macros which start and end a block, so they _must_ be
826 * used in pairs (the latter with a '1' argument to call the
828 * On BSD we don't need this, but we keep it for compatibility.
830 static void *dummy_start(void *data
)
833 struct thr_arg a
= *((struct thr_arg
*) data
); /* make a local copy */
835 struct thr_lock_info
*lock_info
;
836 pthread_mutexattr_t mutex_attr
;
839 /* note that even though data->name is a pointer to allocated memory,
840 we are not freeing it here because ast_register_thread is going to
841 keep a copy of the pointer and then ast_unregister_thread will
845 ast_register_thread(a
.name
);
846 pthread_cleanup_push(ast_unregister_thread
, (void *) pthread_self());
849 if (!(lock_info
= ast_threadstorage_get(&thread_lock_info
, sizeof(*lock_info
))))
852 lock_info
->thread_id
= pthread_self();
853 lock_info
->thread_name
= strdup(a
.name
);
855 pthread_mutexattr_init(&mutex_attr
);
856 pthread_mutexattr_settype(&mutex_attr
, AST_MUTEX_KIND
);
857 pthread_mutex_init(&lock_info
->lock
, &mutex_attr
);
858 pthread_mutexattr_destroy(&mutex_attr
);
860 pthread_mutex_lock(&lock_infos_lock
.mutex
); /* Intentionally not the wrapper */
861 AST_LIST_INSERT_TAIL(&lock_infos
, lock_info
, entry
);
862 pthread_mutex_unlock(&lock_infos_lock
.mutex
); /* Intentionally not the wrapper */
863 #endif /* DEBUG_THREADS */
865 ret
= a
.start_routine(a
.data
);
867 pthread_cleanup_pop(1);
872 #endif /* !LOW_MEMORY */
874 int ast_pthread_create_stack(pthread_t
*thread
, pthread_attr_t
*attr
, void *(*start_routine
)(void *),
875 void *data
, size_t stacksize
, const char *file
, const char *caller
,
876 int line
, const char *start_fn
)
878 #if !defined(LOW_MEMORY)
883 attr
= alloca(sizeof(*attr
));
884 pthread_attr_init(attr
);
888 /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
889 which is kind of useless. Change this here to
890 PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
891 priority will propagate down to new threads by default.
892 This does mean that callers cannot set a different priority using
893 PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
894 the priority afterwards with pthread_setschedparam(). */
895 if ((errno
= pthread_attr_setinheritsched(attr
, PTHREAD_INHERIT_SCHED
)))
896 ast_log(LOG_WARNING
, "pthread_attr_setinheritsched: %s\n", strerror(errno
));
900 stacksize
= AST_STACKSIZE
;
902 if ((errno
= pthread_attr_setstacksize(attr
, stacksize
? stacksize
: AST_STACKSIZE
)))
903 ast_log(LOG_WARNING
, "pthread_attr_setstacksize: %s\n", strerror(errno
));
905 #if !defined(LOW_MEMORY)
906 if ((a
= ast_malloc(sizeof(*a
)))) {
907 a
->start_routine
= start_routine
;
909 start_routine
= dummy_start
;
910 asprintf(&a
->name
, "%-20s started at [%5d] %s %s()",
911 start_fn
, line
, file
, caller
);
914 #endif /* !LOW_MEMORY */
916 return pthread_create(thread
, attr
, start_routine
, data
); /* We're in ast_pthread_create, so it's okay */
919 int ast_wait_for_input(int fd
, int ms
)
921 struct pollfd pfd
[1];
922 memset(pfd
, 0, sizeof(pfd
));
924 pfd
[0].events
= POLLIN
|POLLPRI
;
925 return poll(pfd
, 1, ms
);
928 int ast_carefulwrite(int fd
, char *s
, int len
, int timeoutms
)
930 /* Try to write string, but wait no more than ms milliseconds
933 struct pollfd fds
[1];
935 res
= write(fd
, s
, len
);
936 if ((res
< 0) && (errno
!= EAGAIN
)) {
946 fds
[0].events
= POLLOUT
;
947 /* Wait until writable again */
948 res
= poll(fds
, 1, timeoutms
);
956 char *ast_strip_quoted(char *s
, const char *beg_quotes
, const char *end_quotes
)
962 if ((q
= strchr(beg_quotes
, *s
)) && *q
!= '\0') {
963 e
= s
+ strlen(s
) - 1;
964 if (*e
== *(end_quotes
+ (q
- beg_quotes
))) {
973 char *ast_unescape_semicolon(char *s
)
978 while ((e
= strchr(work
, ';'))) {
979 if ((e
> work
) && (*(e
-1) == '\\')) {
980 memmove(e
- 1, e
, strlen(e
) + 1);
990 int ast_build_string_va(char **buffer
, size_t *space
, const char *fmt
, va_list ap
)
994 if (!buffer
|| !*buffer
|| !space
|| !*space
)
997 result
= vsnprintf(*buffer
, *space
, fmt
, ap
);
1001 else if (result
> *space
)
1009 int ast_build_string(char **buffer
, size_t *space
, const char *fmt
, ...)
1015 result
= ast_build_string_va(buffer
, space
, fmt
, ap
);
1021 int ast_true(const char *s
)
1023 if (ast_strlen_zero(s
))
1026 /* Determine if this is a true value */
1027 if (!strcasecmp(s
, "yes") ||
1028 !strcasecmp(s
, "true") ||
1029 !strcasecmp(s
, "y") ||
1030 !strcasecmp(s
, "t") ||
1031 !strcasecmp(s
, "1") ||
1032 !strcasecmp(s
, "on"))
1038 int ast_false(const char *s
)
1040 if (ast_strlen_zero(s
))
1043 /* Determine if this is a false value */
1044 if (!strcasecmp(s
, "no") ||
1045 !strcasecmp(s
, "false") ||
1046 !strcasecmp(s
, "n") ||
1047 !strcasecmp(s
, "f") ||
1048 !strcasecmp(s
, "0") ||
1049 !strcasecmp(s
, "off"))
1055 #define ONE_MILLION 1000000
1057 * put timeval in a valid range. usec is 0..999999
1058 * negative values are not allowed and truncated.
1060 static struct timeval
tvfix(struct timeval a
)
1062 if (a
.tv_usec
>= ONE_MILLION
) {
1063 ast_log(LOG_WARNING
, "warning too large timestamp %ld.%ld\n",
1064 a
.tv_sec
, (long int) a
.tv_usec
);
1065 a
.tv_sec
+= a
.tv_usec
/ ONE_MILLION
;
1066 a
.tv_usec
%= ONE_MILLION
;
1067 } else if (a
.tv_usec
< 0) {
1068 ast_log(LOG_WARNING
, "warning negative timestamp %ld.%ld\n",
1069 a
.tv_sec
, (long int) a
.tv_usec
);
1075 struct timeval
ast_tvadd(struct timeval a
, struct timeval b
)
1077 /* consistency checks to guarantee usec in 0..999999 */
1080 a
.tv_sec
+= b
.tv_sec
;
1081 a
.tv_usec
+= b
.tv_usec
;
1082 if (a
.tv_usec
>= ONE_MILLION
) {
1084 a
.tv_usec
-= ONE_MILLION
;
1089 struct timeval
ast_tvsub(struct timeval a
, struct timeval b
)
1091 /* consistency checks to guarantee usec in 0..999999 */
1094 a
.tv_sec
-= b
.tv_sec
;
1095 a
.tv_usec
-= b
.tv_usec
;
1096 if (a
.tv_usec
< 0) {
1098 a
.tv_usec
+= ONE_MILLION
;
1104 /*! \brief glibc puts a lock inside random(3), so that the results are thread-safe.
1105 * BSD libc (and others) do not. */
1108 AST_MUTEX_DEFINE_STATIC(randomlock
);
1110 long int ast_random(void)
1113 ast_mutex_lock(&randomlock
);
1115 ast_mutex_unlock(&randomlock
);
1120 char *ast_process_quotes_and_slashes(char *start
, char find
, char replace_with
)
1122 char *dataPut
= start
;
1126 for (; *start
; start
++) {
1128 *dataPut
++ = *start
; /* Always goes verbatim */
1131 if (*start
== '\\') {
1132 inEscape
= 1; /* Do not copy \ into the data */
1133 } else if (*start
== '\'') {
1134 inQuotes
= 1 - inQuotes
; /* Do not copy ' into the data */
1136 /* Replace , with |, unless in quotes */
1137 *dataPut
++ = inQuotes
? *start
: ((*start
== find
) ? replace_with
: *start
);
1141 if (start
!= dataPut
)
1146 void ast_join(char *s
, size_t len
, char * const w
[])
1151 /* Join words into a string */
1154 for (x
= 0; ofs
< len
&& w
[x
]; x
++) {
1157 for (src
= w
[x
]; *src
&& ofs
< len
; src
++)
1165 const char __ast_string_field_empty
[] = "";
1167 static int add_string_pool(struct ast_string_field_mgr
*mgr
, size_t size
)
1169 struct ast_string_field_pool
*pool
;
1171 if (!(pool
= ast_calloc(1, sizeof(*pool
) + size
)))
1174 pool
->prev
= mgr
->pool
;
1183 int __ast_string_field_init(struct ast_string_field_mgr
*mgr
, size_t size
,
1184 ast_string_field
*fields
, int num_fields
)
1188 if (add_string_pool(mgr
, size
))
1191 for (index
= 0; index
< num_fields
; index
++)
1192 fields
[index
] = __ast_string_field_empty
;
1197 ast_string_field
__ast_string_field_alloc_space(struct ast_string_field_mgr
*mgr
, size_t needed
,
1198 ast_string_field
*fields
, int num_fields
)
1200 char *result
= NULL
;
1202 if (__builtin_expect(needed
> mgr
->space
, 0)) {
1203 size_t new_size
= mgr
->size
* 2;
1205 while (new_size
< needed
)
1208 if (add_string_pool(mgr
, new_size
))
1212 result
= mgr
->pool
->base
+ mgr
->used
;
1213 mgr
->used
+= needed
;
1214 mgr
->space
-= needed
;
1218 void __ast_string_field_index_build_va(struct ast_string_field_mgr
*mgr
,
1219 ast_string_field
*fields
, int num_fields
,
1220 int index
, const char *format
, va_list ap1
, va_list ap2
)
1224 needed
= vsnprintf(mgr
->pool
->base
+ mgr
->used
, mgr
->space
, format
, ap1
) + 1;
1228 if (needed
> mgr
->space
) {
1229 size_t new_size
= mgr
->size
* 2;
1231 while (new_size
< needed
)
1234 if (add_string_pool(mgr
, new_size
))
1237 vsprintf(mgr
->pool
->base
+ mgr
->used
, format
, ap2
);
1240 fields
[index
] = mgr
->pool
->base
+ mgr
->used
;
1241 mgr
->used
+= needed
;
1242 mgr
->space
-= needed
;
1245 void __ast_string_field_index_build(struct ast_string_field_mgr
*mgr
,
1246 ast_string_field
*fields
, int num_fields
,
1247 int index
, const char *format
, ...)
1251 va_start(ap1
, format
);
1252 va_start(ap2
, format
); /* va_copy does not exist on FreeBSD */
1254 __ast_string_field_index_build_va(mgr
, fields
, num_fields
, index
, format
, ap1
, ap2
);
1260 AST_MUTEX_DEFINE_STATIC(fetchadd_m
); /* used for all fetc&add ops */
1262 int ast_atomic_fetchadd_int_slow(volatile int *p
, int v
)
1265 ast_mutex_lock(&fetchadd_m
);
1268 ast_mutex_unlock(&fetchadd_m
);
1273 * get values from config variables.
1275 int ast_get_time_t(const char *src
, time_t *dst
, time_t _default
, int *consumed
)
1285 if (ast_strlen_zero(src
))
1288 /* only integer at the moment, but one day we could accept more formats */
1289 if (sscanf(src
, "%ld%n", &t
, &scanned
) == 1) {
1292 *consumed
= scanned
;
1298 int ast_dynamic_str_thread_build_va(struct ast_dynamic_str
**buf
, size_t max_len
,
1299 struct ast_threadstorage
*ts
, int append
, const char *fmt
, va_list ap
)
1302 int offset
= (append
&& (*buf
)->len
) ? strlen((*buf
)->str
) : 0;
1303 #if defined(DEBUG_THREADLOCALS)
1304 struct ast_dynamic_str
*old_buf
= *buf
;
1305 #endif /* defined(DEBUG_THREADLOCALS) */
1307 res
= vsnprintf((*buf
)->str
+ offset
, (*buf
)->len
- offset
, fmt
, ap
);
1309 /* Check to see if there was not enough space in the string buffer to prepare
1310 * the string. Also, if a maximum length is present, make sure the current
1311 * length is less than the maximum before increasing the size. */
1312 if ((res
+ offset
+ 1) > (*buf
)->len
&& (max_len
? ((*buf
)->len
< max_len
) : 1)) {
1313 /* Set the new size of the string buffer to be the size needed
1314 * to hold the resulting string (res) plus one byte for the
1315 * terminating '\0'. If this size is greater than the max, set
1316 * the new length to be the maximum allowed. */
1318 (*buf
)->len
= ((res
+ offset
+ 1) < max_len
) ? (res
+ offset
+ 1) : max_len
;
1320 (*buf
)->len
= res
+ offset
+ 1;
1322 if (!(*buf
= ast_realloc(*buf
, (*buf
)->len
+ sizeof(*(*buf
)))))
1323 return AST_DYNSTR_BUILD_FAILED
;
1326 (*buf
)->str
[offset
] = '\0';
1329 pthread_setspecific(ts
->key
, *buf
);
1330 #if defined(DEBUG_THREADLOCALS)
1331 __ast_threadstorage_object_replace(old_buf
, *buf
, (*buf
)->len
+ sizeof(*(*buf
)));
1332 #endif /* defined(DEBUG_THREADLOCALS) */
1335 /* va_end() and va_start() must be done before calling
1336 * vsnprintf() again. */
1337 return AST_DYNSTR_BUILD_RETRY
;
1343 void ast_enable_packet_fragmentation(int sock
)
1345 #if defined(HAVE_IP_MTU_DISCOVER)
1346 int val
= IP_PMTUDISC_DONT
;
1348 if (setsockopt(sock
, IPPROTO_IP
, IP_MTU_DISCOVER
, &val
, sizeof(val
)))
1349 ast_log(LOG_WARNING
, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
1350 #endif /* HAVE_IP_MTU_DISCOVER */
1353 int ast_utils_init(void)
1356 #ifdef DEBUG_THREADS
1357 ast_cli_register_multiple(utils_cli
, sizeof(utils_cli
) / sizeof(utils_cli
[0]));