2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2005, 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.
33 #include <sys/types.h>
34 #include <sys/socket.h>
35 #include <netinet/in.h>
36 #include <arpa/inet.h>
40 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
42 #include "asterisk/lock.h"
43 #include "asterisk/io.h"
44 #include "asterisk/logger.h"
45 #include "asterisk/md5.h"
46 #include "asterisk/options.h"
48 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
49 #include "asterisk/strings.h"
51 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
52 #include "asterisk/time.h"
54 #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
55 #include "asterisk/utils.h"
57 static char base64[64];
60 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined( __NetBSD__ ) || defined(__APPLE__)
62 /* duh? ERANGE value copied from web... */
66 AST_MUTEX_DEFINE_STATIC(__mutex);
68 /* Recursive replacement for gethostbyname for BSD-based systems. This
69 routine is derived from code originally written and placed in the public
70 domain by Enzo Michelangeli <em@em.no-ip.com> */
72 static int gethostbyname_r (const char *name, struct hostent *ret, char *buf,
73 size_t buflen, struct hostent **result,
78 ast_mutex_lock(&__mutex); /* begin critical area */
81 ph = gethostbyname(name);
82 *h_errnop = h_errno; /* copy h_errno to *h_herrnop */
89 int naddr=0, naliases=0;
90 /* determine if we have enough space in buf */
92 /* count how many addresses */
93 for (p = ph->h_addr_list; *p != 0; p++) {
94 nbytes += ph->h_length; /* addresses */
95 nbytes += sizeof(*p); /* pointers */
98 nbytes += sizeof(*p); /* one more for the terminating NULL */
100 /* count how many aliases, and total length of strings */
101 for (p = ph->h_aliases; *p != 0; p++) {
102 nbytes += (strlen(*p)+1); /* aliases */
103 nbytes += sizeof(*p); /* pointers */
106 nbytes += sizeof(*p); /* one more for the terminating NULL */
108 /* here nbytes is the number of bytes required in buffer */
109 /* as a terminator must be there, the minimum value is ph->h_length */
110 if(nbytes > buflen) {
112 ast_mutex_unlock(&__mutex); /* end critical area */
113 return ERANGE; /* not enough space in buf!! */
116 /* There is enough space. Now we need to do a deep copy! */
117 /* Allocation in buffer:
118 from [0] to [(naddr-1) * sizeof(*p)]:
119 pointers to addresses
120 at [naddr * sizeof(*p)]:
122 from [(naddr+1) * sizeof(*p)] to [(naddr+naliases) * sizeof(*p)] :
124 at [(naddr+naliases+1) * sizeof(*p)]:
126 then naddr addresses (fixed length), and naliases aliases (asciiz).
129 *ret = *ph; /* copy whole structure (not its address!) */
132 q = (char **)buf; /* pointer to pointers area (type: char **) */
133 ret->h_addr_list = q; /* update pointer to address list */
134 pbuf = buf + ((naddr+naliases+2)*sizeof(*p)); /* skip that area */
135 for (p = ph->h_addr_list; *p != 0; p++) {
136 memcpy(pbuf, *p, ph->h_length); /* copy address bytes */
137 *q++ = pbuf; /* the pointer is the one inside buf... */
138 pbuf += ph->h_length; /* advance pbuf */
140 *q++ = NULL; /* address list terminator */
143 ret->h_aliases = q; /* update pointer to aliases list */
144 for (p = ph->h_aliases; *p != 0; p++) {
145 strcpy(pbuf, *p); /* copy alias strings */
146 *q++ = pbuf; /* the pointer is the one inside buf... */
147 pbuf += strlen(*p); /* advance pbuf */
148 *pbuf++ = 0; /* string terminator */
150 *q++ = NULL; /* terminator */
152 strcpy(pbuf, ph->h_name); /* copy alias strings */
154 pbuf += strlen(ph->h_name); /* advance pbuf */
155 *pbuf++ = 0; /* string terminator */
157 *result = ret; /* and let *result point to structure */
160 h_errno = hsave; /* restore h_errno */
161 ast_mutex_unlock(&__mutex); /* end critical area */
163 return (*result == NULL); /* return 0 on success, non-zero on error */
169 /*! \brief Re-entrant (thread safe) version of gethostbyname that replaces the
170 standard gethostbyname (which is not thread safe)
172 struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp)
178 struct hostent *result = NULL;
179 /* Although it is perfectly legitimate to lookup a pure integer, for
180 the sake of the sanity of people who like to name their peers as
181 integers, we break with tradition and refuse to look up a
188 else if (!isdigit(*s))
193 /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
196 memset(hp, 0, sizeof(struct ast_hostent));
197 hp->hp.h_addr_list = (void *) hp->buf;
198 hp->hp.h_addr = hp->buf + sizeof(void *);
199 if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
205 result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);
207 if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
210 res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
212 if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
220 AST_MUTEX_DEFINE_STATIC(test_lock);
221 AST_MUTEX_DEFINE_STATIC(test_lock2);
222 static pthread_t test_thread;
223 static int lock_count = 0;
224 static int test_errors = 0;
226 /*! \brief This is a regression test for recursive mutexes.
227 test_for_thread_safety() will return 0 if recursive mutex locks are
228 working properly, and non-zero if they are not working properly. */
229 static void *test_thread_body(void *data)
231 ast_mutex_lock(&test_lock);
233 if (lock_count != 10)
235 ast_mutex_lock(&test_lock);
237 if (lock_count != 20)
239 ast_mutex_lock(&test_lock2);
240 ast_mutex_unlock(&test_lock);
242 if (lock_count != 10)
244 ast_mutex_unlock(&test_lock);
246 ast_mutex_unlock(&test_lock2);
252 int test_for_thread_safety(void)
254 ast_mutex_lock(&test_lock2);
255 ast_mutex_lock(&test_lock);
257 ast_mutex_lock(&test_lock);
259 ast_pthread_create(&test_thread, NULL, test_thread_body, NULL);
263 ast_mutex_unlock(&test_lock);
268 ast_mutex_unlock(&test_lock);
272 ast_mutex_unlock(&test_lock2);
276 pthread_join(test_thread, NULL);
277 return(test_errors); /* return 0 on success. */
280 /*! \brief ast_md5_hash: Produce 16 char MD5 hash of value. ---*/
281 void ast_md5_hash(char *output, char *input)
283 struct MD5Context md5;
284 unsigned char digest[16];
289 MD5Update(&md5, (unsigned char *)input, strlen(input));
290 MD5Final(digest, &md5);
293 ptr += sprintf(ptr, "%2.2x", digest[x]);
296 int ast_base64decode(unsigned char *dst, const char *src, int max)
299 unsigned int byte = 0;
300 unsigned int bits = 0;
303 unsigned char *odst = dst;
305 while(*src && (cnt < max)) {
306 /* Shift in 6 bits of input */
308 byte |= (b2a[(int)(*src)]) & 0x3f;
311 printf("Add: %c %s\n", *src, binary(b2a[(int)(*src)] & 0x3f, 6));
315 /* If we have at least 8 bits left over, take that character
319 *dst = (byte >> bits) & 0xff;
321 printf("Remove: %02x %s\n", *dst, binary(*dst, 8));
330 /* Dont worry about left over bits, they're extra anyway */
334 int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
337 unsigned int byte = 0;
345 /* Reserve one bit for end */
347 while((cntin < srclen) && (cnt < max)) {
350 printf("Add: %02x %s\n", *src, binary(*src, 8));
355 while((bits >= 6) && (cnt < max)) {
357 /* We want only the top */
358 index = (byte >> bits) & 0x3f;
359 *dst = base64[index];
361 printf("Remove: %c %s\n", *dst, binary(index, 6));
367 if (bits && (cnt < max)) {
368 /* Add one last character for the remaining bits,
369 padding the rest with 0 */
371 index = (byte) & 0x3f;
372 *(dst++) = base64[index];
379 static void base64_init(void)
382 memset(b2a, -1, sizeof(b2a));
383 /* Initialize base-64 Conversion table */
389 base64[x + 26] = 'a' + x;
390 b2a['a' + x] = x + 26;
393 base64[x + 52] = '0' + x;
394 b2a['0' + x] = x + 52;
403 if (b2a[(int)base64[x]] != x) {
404 fprintf(stderr, "!!! %d failed\n", x);
406 fprintf(stderr, "--- %d passed\n", x);
411 /*! \brief ast_uri_encode: Turn text string to URI-encoded %XX version ---*/
412 /* At this point, we're converting from ISO-8859-x (8-bit), not UTF8
413 as in the SIP protocol spec
414 If doreserved == 1 we will convert reserved characters also.
415 RFC 2396, section 2.4
416 outbuf needs to have more memory allocated than the instring
417 to have room for the expansion. Every char that is converted
418 is replaced by three ASCII characters.
420 Note: The doreserved option is needed for replaces header in
423 char *ast_uri_encode(char *string, char *outbuf, int buflen, int doreserved)
425 char *reserved = ";/?:@&=+$, "; /* Reserved chars */
427 char *ptr = string; /* Start with the string */
431 strncpy(outbuf, string, buflen);
433 /* If there's no characters to convert, just go through and don't do anything */
435 if (((unsigned char) *ptr) > 127 || (doreserved && strchr(reserved, *ptr)) ) {
436 /* Oops, we need to start working here */
439 out = buf + (ptr - string) ; /* Set output ptr */
441 out += sprintf(out, "%%%02x", (unsigned char) *ptr);
443 *out = *ptr; /* Continue copying the string */
453 /*! \brief ast_uri_decode: Decode SIP URI, URN, URL (overwrite the string) ---*/
454 void ast_uri_decode(char *s)
459 for (o = s; *s; s++, o++) {
460 if (*s == '%' && strlen(s) > 2 && sscanf(s + 1, "%2x", &tmp) == 1) {
461 /* have '%', two chars and correct parsing */
463 s += 2; /* Will be incremented once more when we break out */
464 } else /* all other cases, just copy */
470 /*! \brief ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa */
471 const char *ast_inet_ntoa(char *buf, int bufsiz, struct in_addr ia)
473 return inet_ntop(AF_INET, &ia, buf, bufsiz);
476 int ast_utils_init(void)
483 #undef pthread_create /* For ast_pthread_create function only */
484 #endif /* !__linux__ */
486 int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize)
488 pthread_attr_t lattr;
490 pthread_attr_init(&lattr);
494 /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
495 which is kind of useless. Change this here to
496 PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
497 priority will propagate down to new threads by default.
498 This does mean that callers cannot set a different priority using
499 PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
500 the priority afterwards with pthread_setschedparam(). */
501 errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED);
503 ast_log(LOG_WARNING, "pthread_attr_setinheritsched returned non-zero: %s\n", strerror(errno));
507 stacksize = AST_STACKSIZE;
508 errno = pthread_attr_setstacksize(attr, stacksize);
510 ast_log(LOG_WARNING, "pthread_attr_setstacksize returned non-zero: %s\n", strerror(errno));
511 return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
514 int ast_wait_for_input(int fd, int ms)
516 struct pollfd pfd[1];
517 memset(pfd, 0, sizeof(pfd));
519 pfd[0].events = POLLIN|POLLPRI;
520 return poll(pfd, 1, ms);
523 char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
529 if ((q = strchr(beg_quotes, *s))) {
530 e = s + strlen(s) - 1;
531 if (*e == *(end_quotes + (q - beg_quotes))) {
540 int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap)
544 if (!buffer || !*buffer || !space || !*space)
547 result = vsnprintf(*buffer, *space, fmt, ap);
551 else if (result > *space)
559 int ast_build_string(char **buffer, size_t *space, const char *fmt, ...)
565 result = ast_build_string_va(buffer, space, fmt, ap);
571 int ast_true(const char *s)
573 if (ast_strlen_zero(s))
576 /* Determine if this is a true value */
577 if (!strcasecmp(s, "yes") ||
578 !strcasecmp(s, "true") ||
579 !strcasecmp(s, "y") ||
580 !strcasecmp(s, "t") ||
581 !strcasecmp(s, "1") ||
582 !strcasecmp(s, "on"))
588 int ast_false(const char *s)
590 if (ast_strlen_zero(s))
593 /* Determine if this is a false value */
594 if (!strcasecmp(s, "no") ||
595 !strcasecmp(s, "false") ||
596 !strcasecmp(s, "n") ||
597 !strcasecmp(s, "f") ||
598 !strcasecmp(s, "0") ||
599 !strcasecmp(s, "off"))
605 #define ONE_MILLION 1000000
607 * put timeval in a valid range. usec is 0..999999
608 * negative values are not allowed and truncated.
610 static struct timeval tvfix(struct timeval a)
612 if (a.tv_usec >= ONE_MILLION) {
613 ast_log(LOG_WARNING, "warning too large timestamp %ld.%ld\n",
614 a.tv_sec, (long int) a.tv_usec);
615 a.tv_sec += a.tv_usec % ONE_MILLION;
616 a.tv_usec %= ONE_MILLION;
617 } else if (a.tv_usec < 0) {
618 ast_log(LOG_WARNING, "warning negative timestamp %ld.%ld\n",
619 a.tv_sec, (long int) a.tv_usec);
625 struct timeval ast_tvadd(struct timeval a, struct timeval b)
627 /* consistency checks to guarantee usec in 0..999999 */
630 a.tv_sec += b.tv_sec;
631 a.tv_usec += b.tv_usec;
632 if (a.tv_usec >= ONE_MILLION) {
634 a.tv_usec -= ONE_MILLION;
639 struct timeval ast_tvsub(struct timeval a, struct timeval b)
641 /* consistency checks to guarantee usec in 0..999999 */
644 a.tv_sec -= b.tv_sec;
645 a.tv_usec -= b.tv_usec;
648 a.tv_usec += ONE_MILLION;
654 #ifndef HAVE_STRCASESTR
655 static char *upper(const char *orig, char *buf, int bufsize)
659 while (i < (bufsize - 1) && orig[i]) {
660 buf[i] = toupper(orig[i]);
669 char *strcasestr(const char *haystack, const char *needle)
672 int u1len = strlen(haystack) + 1, u2len = strlen(needle) + 1;
679 /* Needle bigger than haystack */
682 offset = strstr(upper(haystack, u1, u1len), upper(needle, u2, u2len));
684 /* Return the offset into the original string */
685 return ((char *)((unsigned long)haystack + (unsigned long)(offset - u1)));
690 ast_log(LOG_ERROR, "Out of memory\n");
694 #endif /* !HAVE_STRCASESTR */
697 size_t strnlen(const char *s, size_t n)
701 for (len=0; len < n; len++)
707 #endif /* !HAVE_STRNLEN */
709 #if !defined(HAVE_STRNDUP) && !defined(__AST_DEBUG_MALLOC)
710 char *strndup(const char *s, size_t n)
712 size_t len = strnlen(s, n);
713 char *new = malloc(len + 1);
719 return memcpy(new, s, len);
721 #endif /* !defined(HAVE_STRNDUP) && !defined(__AST_DEBUG_MALLOC) */
723 #if !defined(HAVE_VASPRINTF) && !defined(__AST_DEBUG_MALLOC)
724 int vasprintf(char **strp, const char *fmt, va_list ap)
732 size = vsnprintf(&s, 1, fmt, ap2);
734 *strp = malloc(size + 1);
737 vsnprintf(*strp, size + 1, fmt, ap);
741 #endif /* !defined(HAVE_VASPRINTF) && !defined(__AST_DEBUG_MALLOC) */
744 #define LONG_MIN (-9223372036854775807L-1L)
745 /* min value of a "long int" */
746 #define LONG_MAX 9223372036854775807L
747 /* max value of a "long int" */
750 * Convert a string to a quad integer.
752 * Ignores `locale' stuff. Assumes that the upper and lower case
753 * alphabets and digits are each contiguous.
755 uint64_t strtoq(const char *nptr, char **endptr, int base)
760 uint64_t qbase, cutoff;
761 int neg, any, cutlim;
764 * Skip white space and pick up leading +/- sign if any.
765 * If base is 0, allow 0x for hex and 0 for octal, else
766 * assume decimal; if base is already 16, allow 0x.
771 } while (isspace(c));
780 if ((base == 0 || base == 16) &&
781 c == '\0' && (*s == 'x' || *s == 'X')) {
787 base = c == '\0' ? 8 : 10;
790 * Compute the cutoff value between legal numbers and illegal
791 * numbers. That is the largest legal value, divided by the
792 * base. An input number that is greater than this value, if
793 * followed by a legal input character, is too big. One that
794 * is equal to this value may be valid or not; the limit
795 * between valid and invalid numbers is then based on the last
796 * digit. For instance, if the range for quads is
797 * [-9223372036854775808..9223372036854775807] and the input base
798 * is 10, cutoff will be set to 922337203685477580 and cutlim to
799 * either 7 (neg==0) or 8 (neg==1), meaning that if we have
800 * accumulated a value > 922337203685477580, or equal but the
801 * next digit is > 7 (or 8), the number is too big, and we will
802 * return a range error.
804 * Set any if any `digits' consumed; make it negative to indicate
807 qbase = (unsigned)base;
808 cutoff = neg ? (uint64_t)-(LONG_MIN + LONG_MAX) + LONG_MAX : LONG_MAX;
809 cutlim = cutoff % qbase;
811 for (acc = 0, any = 0;; c = *s++) {
817 c -= isupper(c) ? 'A' - 10 : 'a' - 10;
822 if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
831 acc = neg ? LONG_MIN : LONG_MAX;
835 *((const char **)endptr) = any ? s - 1 : nptr;
838 #endif /* !HAVE_STRTOQ */
840 #if (!defined(getloadavg))
842 /* Alternative method of getting load avg on Linux only */
843 int getloadavg(double *list, int nelem)
846 double avg[3] = { 0.0, 0.0, 0.0 };
849 if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
850 fscanf(LOADAVG, "%lf %lf %lf", &avg[0], &avg[1], &avg[2]);
855 for (i = 0; (i < nelem) && (i < 3); i++) {
862 /* Return something that won't cancel the call, but still return -1, in case
863 * we correct the implementation to check return value */
864 int getloadavg(double *list, int nelem)
868 for (i = 0; i < nelem; i++) {
874 #endif /* !defined(getloadavg) */
876 char *ast_process_quotes_and_slashes(char *start, char find, char replace_with)
878 char *dataPut = start;
882 for (; *start; start++) {
884 *dataPut++ = *start; /* Always goes verbatim */
887 if (*start == '\\') {
888 inEscape = 1; /* Do not copy \ into the data */
889 } else if (*start == '\'') {
890 inQuotes = 1-inQuotes; /* Do not copy ' into the data */
892 /* Replace , with |, unless in quotes */
893 *dataPut++ = inQuotes ? *start : ((*start==find) ? replace_with : *start);
897 if (start != dataPut)