Merged revisions 111125 via svnmerge from
[asterisk-bristuff.git] / main / utils.c
blob5b80b107cb485895f821c6cda1a3520b77fe5514
1 /*
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.
17 /*! \file
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.
26 #include "asterisk.h"
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30 #include <ctype.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <stdlib.h>
34 #include <errno.h>
35 #include <stdarg.h>
36 #include <stdio.h>
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];
68 static char b2a[256];
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... */
75 #undef gethostbyname
77 AST_MUTEX_DEFINE_STATIC(__mutex);
79 /*! \brief Reentrant replacement for gethostbyname for BSD-based systems.
80 \note This
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,
86 int *h_errnop)
88 int hsave;
89 struct hostent *ph;
90 ast_mutex_lock(&__mutex); /* begin critical area */
91 hsave = h_errno;
93 ph = gethostbyname(name);
94 *h_errnop = h_errno; /* copy h_errno to *h_herrnop */
95 if (ph == NULL) {
96 *result = NULL;
97 } else {
98 char **p, **q;
99 char *pbuf;
100 int nbytes=0;
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 */
108 naddr++;
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 */
116 naliases++;
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) {
123 *result = NULL;
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)]:
133 NULL
134 from [(naddr+1) * sizeof(*p)] to [(naddr+naliases) * sizeof(*p)] :
135 pointers to aliases
136 at [(naddr+naliases+1) * sizeof(*p)]:
137 NULL
138 then naddr addresses (fixed length), and naliases aliases (asciiz).
141 *ret = *ph; /* copy whole structure (not its address!) */
143 /* copy addresses */
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 */
154 /* copy aliases */
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 */
165 ret->h_name = pbuf;
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 */
179 #endif
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)
186 int res;
187 int herrno;
188 int dots=0;
189 const char *s;
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
194 pure integer */
195 s = host;
196 res = 0;
197 while(s && *s) {
198 if (*s == '.')
199 dots++;
200 else if (!isdigit(*s))
201 break;
202 s++;
204 if (!s || !*s) {
205 /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
206 if (dots != 3)
207 return NULL;
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)
213 return &hp->hp;
214 return NULL;
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])
221 return NULL;
222 #else
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])
226 return NULL;
227 #endif
228 return &hp->hp;
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);
245 lock_count += 10;
246 if (lock_count != 10)
247 test_errors++;
248 ast_mutex_lock(&test_lock);
249 lock_count += 10;
250 if (lock_count != 20)
251 test_errors++;
252 ast_mutex_lock(&test_lock2);
253 ast_mutex_unlock(&test_lock);
254 lock_count -= 10;
255 if (lock_count != 10)
256 test_errors++;
257 ast_mutex_unlock(&test_lock);
258 lock_count -= 10;
259 ast_mutex_unlock(&test_lock2);
260 if (lock_count != 0)
261 test_errors++;
262 return NULL;
265 int test_for_thread_safety(void)
267 ast_mutex_lock(&test_lock2);
268 ast_mutex_lock(&test_lock);
269 lock_count += 1;
270 ast_mutex_lock(&test_lock);
271 lock_count += 1;
272 ast_pthread_create(&test_thread, NULL, test_thread_body, NULL);
273 usleep(100);
274 if (lock_count != 2)
275 test_errors++;
276 ast_mutex_unlock(&test_lock);
277 lock_count -= 1;
278 usleep(100);
279 if (lock_count != 1)
280 test_errors++;
281 ast_mutex_unlock(&test_lock);
282 lock_count -= 1;
283 if (lock_count != 0)
284 test_errors++;
285 ast_mutex_unlock(&test_lock2);
286 usleep(100);
287 if (lock_count != 0)
288 test_errors++;
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];
298 char *ptr;
299 int x;
301 MD5Init(&md5);
302 MD5Update(&md5, (unsigned char *)input, strlen(input));
303 MD5Final(digest, &md5);
304 ptr = output;
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;
313 char *ptr;
314 int x;
315 uint8_t Message_Digest[20];
317 SHA1Reset(&sha);
319 SHA1Input(&sha, (const unsigned char *) input, strlen(input));
321 SHA1Result(&sha, Message_Digest);
322 ptr = output;
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)
330 int cnt = 0;
331 unsigned int byte = 0;
332 unsigned int bits = 0;
333 int incnt = 0;
334 while(*src && (cnt < max)) {
335 /* Shift in 6 bits of input */
336 byte <<= 6;
337 byte |= (b2a[(int)(*src)]) & 0x3f;
338 bits += 6;
339 src++;
340 incnt++;
341 /* If we have at least 8 bits left over, take that character
342 off the top */
343 if (bits >= 8) {
344 bits -= 8;
345 *dst = (byte >> bits) & 0xff;
346 dst++;
347 cnt++;
350 /* Dont worry about left over bits, they're extra anyway */
351 return cnt;
354 /*! \brief encode text to BASE64 coding */
355 int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
357 int cnt = 0;
358 int col = 0;
359 unsigned int byte = 0;
360 int bits = 0;
361 int cntin = 0;
362 /* Reserve space for null byte at end of string */
363 max--;
364 while ((cntin < srclen) && (cnt < max)) {
365 byte <<= 8;
366 byte |= *(src++);
367 bits += 8;
368 cntin++;
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];
374 cnt += 4;
375 col += 4;
376 bits = 0;
377 byte = 0;
379 if (linebreaks && (cnt < max) && (col == 64)) {
380 *dst++ = '\n';
381 cnt++;
382 col = 0;
385 if (bits && (cnt + 4 <= max)) {
386 /* Add one last character for the remaining bits,
387 padding the rest with 0 */
388 byte <<= 24 - bits;
389 *dst++ = base64[(byte >> 18) & 0x3f];
390 *dst++ = base64[(byte >> 12) & 0x3f];
391 if (bits == 16)
392 *dst++ = base64[(byte >> 6) & 0x3f];
393 else
394 *dst++ = '=';
395 *dst++ = '=';
396 cnt += 4;
398 if (linebreaks && (cnt < max)) {
399 *dst++ = '\n';
400 cnt++;
402 *dst = '\0';
403 return cnt;
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)
413 int x;
414 memset(b2a, -1, sizeof(b2a));
415 /* Initialize base-64 Conversion table */
416 for (x = 0; x < 26; x++) {
417 /* A-Z */
418 base64[x] = 'A' + x;
419 b2a['A' + x] = x;
420 /* a-z */
421 base64[x + 26] = 'a' + x;
422 b2a['a' + x] = x + 26;
423 /* 0-9 */
424 if (x < 10) {
425 base64[x + 52] = '0' + x;
426 b2a['0' + x] = x + 52;
429 base64[62] = '+';
430 base64[63] = '/';
431 b2a[(int)'+'] = 62;
432 b2a[(int)'/'] = 63;
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
445 SIP transfers.
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 */
452 char *out = NULL;
453 char *buf = NULL;
455 ast_copy_string(outbuf, string, buflen);
457 /* If there's no characters to convert, just go through and don't do anything */
458 while (*ptr) {
459 if (((unsigned char) *ptr) > 127 || (doreserved && strchr(reserved, *ptr)) ) {
460 /* Oops, we need to start working here */
461 if (!buf) {
462 buf = outbuf;
463 out = buf + (ptr - string) ; /* Set output ptr */
465 out += sprintf(out, "%%%02x", (unsigned char) *ptr);
466 } else if (buf) {
467 *out = *ptr; /* Continue copying the string */
468 out++;
470 ptr++;
472 if (buf)
473 *out = '\0';
474 return outbuf;
477 /*! \brief ast_uri_decode: Decode SIP URI, URN, URL (overwrite the string) */
478 void ast_uri_decode(char *s)
480 char *o;
481 unsigned int tmp;
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 */
486 *o = tmp;
487 s += 2; /* Will be incremented once more when we break out */
488 } else /* all other cases, just copy */
489 *o = *s;
491 *o = '\0';
494 /*! \brief ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa */
495 const char *ast_inet_ntoa(struct in_addr ia)
497 char *buf;
499 if (!(buf = ast_threadstorage_get(&inet_ntoa_buf, INET_ADDRSTRLEN)))
500 return "";
502 return inet_ntop(AF_INET, &ia, buf, INET_ADDRSTRLEN);
505 #ifndef __linux__
506 #undef pthread_create /* For ast_pthread_create function only */
507 #endif /* !__linux__ */
509 #if !defined(LOW_MEMORY)
511 #ifdef DEBUG_THREADS
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
523 /*!
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 */
530 pthread_t thread_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 */
534 struct {
535 const char *file;
536 int line_num;
537 const char *func;
538 const char *lock_name;
539 void *lock_addr;
540 int times_locked;
541 enum ast_lock_type type;
542 /*! This thread is waiting on this lock */
543 int pending:2;
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
547 * locks member */
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;
555 /*!
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);
579 free(lock_info);
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;
591 int i;
593 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
594 return;
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);
602 return;
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);
611 return;
614 if (i && lock_info->locks[i - 1].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. */
618 i--;
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))))
641 return;
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))))
655 return;
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;
668 int i = 0;
670 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
671 return;
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)
677 break;
680 if (i == -1) {
681 /* Lock not found :( */
682 pthread_mutex_unlock(&lock_info->lock);
683 return;
686 if (lock_info->locks[i].times_locked > 1) {
687 lock_info->locks[i].times_locked--;
688 pthread_mutex_unlock(&lock_info->lock);
689 return;
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)
705 switch (type) {
706 case AST_MUTEX:
707 return "MUTEX";
708 case AST_RDLOCK:
709 return "RDLOCK";
710 case AST_WRLOCK:
711 return "WRLOCK";
714 return "UNKNOWN";
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"
729 "===\n"
730 "=== <file> <line num> <function> <lock name> <lock addr> (times locked)\n"
731 "===\n");
733 if (!str)
734 return RESULT_FAILURE;
736 pthread_mutex_lock(&lock_infos_lock.mutex);
737 AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
738 int i;
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++) {
743 int j;
744 ast_mutex_t *lock;
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)
757 continue;
759 /* We only have further details for mutexes right now */
760 if (lock_info->locks[i].type != AST_MUTEX)
761 continue;
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);
773 if (!str)
774 break;
775 ast_dynamic_str_append(&str, 0, "=== -------------------------------------------------------------------\n"
776 "===\n");
777 if (!str)
778 break;
780 pthread_mutex_unlock(&lock_infos_lock.mutex);
782 if (!str)
783 return RESULT_FAILURE;
785 ast_dynamic_str_append(&str, 0, "=======================================================================\n"
786 "\n");
788 if (!str)
789 return RESULT_FAILURE;
791 ast_cli(fd, "%s", str->str);
793 free(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.
817 struct thr_arg {
818 void *(*start_routine)(void *);
819 void *data;
820 char *name;
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
827 * handler on exit.
828 * On BSD we don't need this, but we keep it for compatibility.
830 static void *dummy_start(void *data)
832 void *ret;
833 struct thr_arg a = *((struct thr_arg *) data); /* make a local copy */
834 #ifdef DEBUG_THREADS
835 struct thr_lock_info *lock_info;
836 pthread_mutexattr_t mutex_attr;
837 #endif
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
842 free the memory
844 free(data);
845 ast_register_thread(a.name);
846 pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
848 #ifdef DEBUG_THREADS
849 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
850 return NULL;
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);
869 return ret;
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)
879 struct thr_arg *a;
880 #endif
882 if (!attr) {
883 attr = alloca(sizeof(*attr));
884 pthread_attr_init(attr);
887 #ifdef __linux__
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));
897 #endif
899 if (!stacksize)
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;
908 a->data = data;
909 start_routine = dummy_start;
910 asprintf(&a->name, "%-20s started at [%5d] %s %s()",
911 start_fn, line, file, caller);
912 data = a;
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));
923 pfd[0].fd = fd;
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
931 before timing out */
932 int res = 0;
933 struct pollfd fds[1];
934 while (len) {
935 res = write(fd, s, len);
936 if ((res < 0) && (errno != EAGAIN)) {
937 return -1;
939 if (res < 0)
940 res = 0;
941 len -= res;
942 s += res;
943 res = 0;
944 if (len) {
945 fds[0].fd = fd;
946 fds[0].events = POLLOUT;
947 /* Wait until writable again */
948 res = poll(fds, 1, timeoutms);
949 if (res < 1)
950 return -1;
953 return res;
956 char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
958 char *e;
959 char *q;
961 s = ast_strip(s);
962 if ((q = strchr(beg_quotes, *s)) && *q != '\0') {
963 e = s + strlen(s) - 1;
964 if (*e == *(end_quotes + (q - beg_quotes))) {
965 s++;
966 *e = '\0';
970 return s;
973 char *ast_unescape_semicolon(char *s)
975 char *e;
976 char *work = s;
978 while ((e = strchr(work, ';'))) {
979 if ((e > work) && (*(e-1) == '\\')) {
980 memmove(e - 1, e, strlen(e) + 1);
981 work = e;
982 } else {
983 work = e + 1;
987 return s;
990 int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap)
992 int result;
994 if (!buffer || !*buffer || !space || !*space)
995 return -1;
997 result = vsnprintf(*buffer, *space, fmt, ap);
999 if (result < 0)
1000 return -1;
1001 else if (result > *space)
1002 result = *space;
1004 *buffer += result;
1005 *space -= result;
1006 return 0;
1009 int ast_build_string(char **buffer, size_t *space, const char *fmt, ...)
1011 va_list ap;
1012 int result;
1014 va_start(ap, fmt);
1015 result = ast_build_string_va(buffer, space, fmt, ap);
1016 va_end(ap);
1018 return result;
1021 int ast_true(const char *s)
1023 if (ast_strlen_zero(s))
1024 return 0;
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"))
1033 return -1;
1035 return 0;
1038 int ast_false(const char *s)
1040 if (ast_strlen_zero(s))
1041 return 0;
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"))
1050 return -1;
1052 return 0;
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);
1070 a.tv_usec = 0;
1072 return a;
1075 struct timeval ast_tvadd(struct timeval a, struct timeval b)
1077 /* consistency checks to guarantee usec in 0..999999 */
1078 a = tvfix(a);
1079 b = tvfix(b);
1080 a.tv_sec += b.tv_sec;
1081 a.tv_usec += b.tv_usec;
1082 if (a.tv_usec >= ONE_MILLION) {
1083 a.tv_sec++;
1084 a.tv_usec -= ONE_MILLION;
1086 return a;
1089 struct timeval ast_tvsub(struct timeval a, struct timeval b)
1091 /* consistency checks to guarantee usec in 0..999999 */
1092 a = tvfix(a);
1093 b = tvfix(b);
1094 a.tv_sec -= b.tv_sec;
1095 a.tv_usec -= b.tv_usec;
1096 if (a.tv_usec < 0) {
1097 a.tv_sec-- ;
1098 a.tv_usec += ONE_MILLION;
1100 return a;
1102 #undef 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. */
1106 #ifndef linux
1108 AST_MUTEX_DEFINE_STATIC(randomlock);
1110 long int ast_random(void)
1112 long int res;
1113 ast_mutex_lock(&randomlock);
1114 res = random();
1115 ast_mutex_unlock(&randomlock);
1116 return res;
1118 #endif
1120 char *ast_process_quotes_and_slashes(char *start, char find, char replace_with)
1122 char *dataPut = start;
1123 int inEscape = 0;
1124 int inQuotes = 0;
1126 for (; *start; start++) {
1127 if (inEscape) {
1128 *dataPut++ = *start; /* Always goes verbatim */
1129 inEscape = 0;
1130 } else {
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 */
1135 } else {
1136 /* Replace , with |, unless in quotes */
1137 *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
1141 if (start != dataPut)
1142 *dataPut = 0;
1143 return dataPut;
1146 void ast_join(char *s, size_t len, char * const w[])
1148 int x, ofs = 0;
1149 const char *src;
1151 /* Join words into a string */
1152 if (!s)
1153 return;
1154 for (x = 0; ofs < len && w[x]; x++) {
1155 if (x > 0)
1156 s[ofs++] = ' ';
1157 for (src = w[x]; *src && ofs < len; src++)
1158 s[ofs++] = *src;
1160 if (ofs == len)
1161 ofs--;
1162 s[ofs] = '\0';
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)))
1172 return -1;
1174 pool->prev = mgr->pool;
1175 mgr->pool = pool;
1176 mgr->size = size;
1177 mgr->space = size;
1178 mgr->used = 0;
1180 return 0;
1183 int __ast_string_field_init(struct ast_string_field_mgr *mgr, size_t size,
1184 ast_string_field *fields, int num_fields)
1186 int index;
1188 if (add_string_pool(mgr, size))
1189 return -1;
1191 for (index = 0; index < num_fields; index++)
1192 fields[index] = __ast_string_field_empty;
1194 return 0;
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)
1206 new_size *= 2;
1208 if (add_string_pool(mgr, new_size))
1209 return NULL;
1212 result = mgr->pool->base + mgr->used;
1213 mgr->used += needed;
1214 mgr->space -= needed;
1215 return result;
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)
1222 size_t needed;
1224 needed = vsnprintf(mgr->pool->base + mgr->used, mgr->space, format, ap1) + 1;
1226 va_end(ap1);
1228 if (needed > mgr->space) {
1229 size_t new_size = mgr->size * 2;
1231 while (new_size < needed)
1232 new_size *= 2;
1234 if (add_string_pool(mgr, new_size))
1235 return;
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, ...)
1249 va_list ap1, ap2;
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);
1256 va_end(ap1);
1257 va_end(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)
1264 int ret;
1265 ast_mutex_lock(&fetchadd_m);
1266 ret = *p;
1267 *p += v;
1268 ast_mutex_unlock(&fetchadd_m);
1269 return ret;
1272 /*! \brief
1273 * get values from config variables.
1275 int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed)
1277 long t;
1278 int scanned;
1280 if (dst == NULL)
1281 return -1;
1283 *dst = _default;
1285 if (ast_strlen_zero(src))
1286 return -1;
1288 /* only integer at the moment, but one day we could accept more formats */
1289 if (sscanf(src, "%ld%n", &t, &scanned) == 1) {
1290 *dst = t;
1291 if (consumed)
1292 *consumed = scanned;
1293 return 0;
1294 } else
1295 return -1;
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)
1301 int res;
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. */
1317 if (max_len)
1318 (*buf)->len = ((res + offset + 1) < max_len) ? (res + offset + 1) : max_len;
1319 else
1320 (*buf)->len = res + offset + 1;
1322 if (!(*buf = ast_realloc(*buf, (*buf)->len + sizeof(*(*buf)))))
1323 return AST_DYNSTR_BUILD_FAILED;
1325 if (append)
1326 (*buf)->str[offset] = '\0';
1328 if (ts) {
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;
1340 return res;
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)
1355 base64_init();
1356 #ifdef DEBUG_THREADS
1357 ast_cli_register_multiple(utils_cli, sizeof(utils_cli) / sizeof(utils_cli[0]));
1358 #endif
1359 return 0;