cc9dee38e50b19f1f83ff84c2924d27754527f76
[asterisk/asterisk.git] / main / utils.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
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.
11  *
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.
15  */
16
17 /*! \file
18  *
19  * \brief Utility functions
20  *
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.
24  */
25
26 /*** MODULEINFO
27         <support_level>core</support_level>
28  ***/
29
30 #include "asterisk.h"
31
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33
34 #include <ctype.h>
35 #include <sys/stat.h>
36 #include <sys/stat.h>
37
38 #include <fcntl.h>
39
40 #include <sys/syscall.h>
41 #if defined(__APPLE__)
42 #include <mach/mach.h>
43 #elif defined(HAVE_SYS_THR_H)
44 #include <sys/thr.h>
45 #endif
46
47 #include "asterisk/network.h"
48
49 #define AST_API_MODULE          /* ensure that inlinable API functions will be built in lock.h if required */
50 #include "asterisk/lock.h"
51 #include "asterisk/io.h"
52 #include "asterisk/md5.h"
53 #include "asterisk/sha1.h"
54 #include "asterisk/cli.h"
55 #include "asterisk/linkedlists.h"
56
57 #define AST_API_MODULE          /* ensure that inlinable API functions will be built in this module if required */
58 #include "asterisk/strings.h"
59
60 #define AST_API_MODULE          /* ensure that inlinable API functions will be built in this module if required */
61 #include "asterisk/time.h"
62
63 #define AST_API_MODULE          /* ensure that inlinable API functions will be built in this module if required */
64 #include "asterisk/stringfields.h"
65
66 #define AST_API_MODULE          /* ensure that inlinable API functions will be built in this module if required */
67 #include "asterisk/utils.h"
68
69 #define AST_API_MODULE
70 #include "asterisk/threadstorage.h"
71
72 #define AST_API_MODULE
73 #include "asterisk/config.h"
74
75 static char base64[64];
76 static char b2a[256];
77
78 AST_THREADSTORAGE(inet_ntoa_buf);
79
80 #if !defined(HAVE_GETHOSTBYNAME_R_5) && !defined(HAVE_GETHOSTBYNAME_R_6)
81
82 #define ERANGE 34       /*!< duh? ERANGE value copied from web... */
83 #undef gethostbyname
84
85 AST_MUTEX_DEFINE_STATIC(__mutex);
86
87 /*! \brief Reentrant replacement for gethostbyname for BSD-based systems.
88 \note This
89 routine is derived from code originally written and placed in the public
90 domain by Enzo Michelangeli <em@em.no-ip.com> */
91
92 static int gethostbyname_r (const char *name, struct hostent *ret, char *buf,
93                                 size_t buflen, struct hostent **result,
94                                 int *h_errnop)
95 {
96         int hsave;
97         struct hostent *ph;
98         ast_mutex_lock(&__mutex); /* begin critical area */
99         hsave = h_errno;
100
101         ph = gethostbyname(name);
102         *h_errnop = h_errno; /* copy h_errno to *h_herrnop */
103         if (ph == NULL) {
104                 *result = NULL;
105         } else {
106                 char **p, **q;
107                 char *pbuf;
108                 int nbytes = 0;
109                 int naddr = 0, naliases = 0;
110                 /* determine if we have enough space in buf */
111
112                 /* count how many addresses */
113                 for (p = ph->h_addr_list; *p != 0; p++) {
114                         nbytes += ph->h_length; /* addresses */
115                         nbytes += sizeof(*p); /* pointers */
116                         naddr++;
117                 }
118                 nbytes += sizeof(*p); /* one more for the terminating NULL */
119
120                 /* count how many aliases, and total length of strings */
121                 for (p = ph->h_aliases; *p != 0; p++) {
122                         nbytes += (strlen(*p)+1); /* aliases */
123                         nbytes += sizeof(*p);  /* pointers */
124                         naliases++;
125                 }
126                 nbytes += sizeof(*p); /* one more for the terminating NULL */
127
128                 /* here nbytes is the number of bytes required in buffer */
129                 /* as a terminator must be there, the minimum value is ph->h_length */
130                 if (nbytes > buflen) {
131                         *result = NULL;
132                         ast_mutex_unlock(&__mutex); /* end critical area */
133                         return ERANGE; /* not enough space in buf!! */
134                 }
135
136                 /* There is enough space. Now we need to do a deep copy! */
137                 /* Allocation in buffer:
138                         from [0] to [(naddr-1) * sizeof(*p)]:
139                         pointers to addresses
140                         at [naddr * sizeof(*p)]:
141                         NULL
142                         from [(naddr+1) * sizeof(*p)] to [(naddr+naliases) * sizeof(*p)] :
143                         pointers to aliases
144                         at [(naddr+naliases+1) * sizeof(*p)]:
145                         NULL
146                         then naddr addresses (fixed length), and naliases aliases (asciiz).
147                 */
148
149                 *ret = *ph;   /* copy whole structure (not its address!) */
150
151                 /* copy addresses */
152                 q = (char **)buf; /* pointer to pointers area (type: char **) */
153                 ret->h_addr_list = q; /* update pointer to address list */
154                 pbuf = buf + ((naddr + naliases + 2) * sizeof(*p)); /* skip that area */
155                 for (p = ph->h_addr_list; *p != 0; p++) {
156                         memcpy(pbuf, *p, ph->h_length); /* copy address bytes */
157                         *q++ = pbuf; /* the pointer is the one inside buf... */
158                         pbuf += ph->h_length; /* advance pbuf */
159                 }
160                 *q++ = NULL; /* address list terminator */
161
162                 /* copy aliases */
163                 ret->h_aliases = q; /* update pointer to aliases list */
164                 for (p = ph->h_aliases; *p != 0; p++) {
165                         strcpy(pbuf, *p); /* copy alias strings */
166                         *q++ = pbuf; /* the pointer is the one inside buf... */
167                         pbuf += strlen(*p); /* advance pbuf */
168                         *pbuf++ = 0; /* string terminator */
169                 }
170                 *q++ = NULL; /* terminator */
171
172                 strcpy(pbuf, ph->h_name); /* copy alias strings */
173                 ret->h_name = pbuf;
174                 pbuf += strlen(ph->h_name); /* advance pbuf */
175                 *pbuf++ = 0; /* string terminator */
176
177                 *result = ret;  /* and let *result point to structure */
178
179         }
180         h_errno = hsave;  /* restore h_errno */
181         ast_mutex_unlock(&__mutex); /* end critical area */
182
183         return (*result == NULL); /* return 0 on success, non-zero on error */
184 }
185
186
187 #endif
188
189 /*! \brief Re-entrant (thread safe) version of gethostbyname that replaces the
190    standard gethostbyname (which is not thread safe)
191 */
192 struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp)
193 {
194         int res;
195         int herrno;
196         int dots = 0;
197         const char *s;
198         struct hostent *result = NULL;
199         /* Although it is perfectly legitimate to lookup a pure integer, for
200            the sake of the sanity of people who like to name their peers as
201            integers, we break with tradition and refuse to look up a
202            pure integer */
203         s = host;
204         res = 0;
205         while (s && *s) {
206                 if (*s == '.')
207                         dots++;
208                 else if (!isdigit(*s))
209                         break;
210                 s++;
211         }
212         if (!s || !*s) {
213                 /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
214                 if (dots != 3)
215                         return NULL;
216                 memset(hp, 0, sizeof(struct ast_hostent));
217                 hp->hp.h_addrtype = AF_INET;
218                 hp->hp.h_addr_list = (void *) hp->buf;
219                 hp->hp.h_addr = hp->buf + sizeof(void *);
220                 /* For AF_INET, this will always be 4 */
221                 hp->hp.h_length = 4;
222                 if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
223                         return &hp->hp;
224                 return NULL;
225
226         }
227 #ifdef HAVE_GETHOSTBYNAME_R_5
228         result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);
229
230         if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
231                 return NULL;
232 #else
233         res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
234
235         if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
236                 return NULL;
237 #endif
238         return &hp->hp;
239 }
240
241 /*! \brief Produce 32 char MD5 hash of value. */
242 void ast_md5_hash(char *output, const char *input)
243 {
244         struct MD5Context md5;
245         unsigned char digest[16];
246         char *ptr;
247         int x;
248
249         MD5Init(&md5);
250         MD5Update(&md5, (const unsigned char *) input, strlen(input));
251         MD5Final(digest, &md5);
252         ptr = output;
253         for (x = 0; x < 16; x++)
254                 ptr += sprintf(ptr, "%2.2x", digest[x]);
255 }
256
257 /*! \brief Produce 40 char SHA1 hash of value. */
258 void ast_sha1_hash(char *output, const char *input)
259 {
260         struct SHA1Context sha;
261         char *ptr;
262         int x;
263         uint8_t Message_Digest[20];
264
265         SHA1Reset(&sha);
266
267         SHA1Input(&sha, (const unsigned char *) input, strlen(input));
268
269         SHA1Result(&sha, Message_Digest);
270         ptr = output;
271         for (x = 0; x < 20; x++)
272                 ptr += sprintf(ptr, "%2.2x", Message_Digest[x]);
273 }
274
275 /*! \brief Produce a 20 byte SHA1 hash of value. */
276 void ast_sha1_hash_uint(uint8_t *digest, const char *input)
277 {
278         struct SHA1Context sha;
279
280         SHA1Reset(&sha);
281
282         SHA1Input(&sha, (const unsigned char *) input, strlen(input));
283
284         SHA1Result(&sha, digest);
285 }
286
287 /*! \brief decode BASE64 encoded text */
288 int ast_base64decode(unsigned char *dst, const char *src, int max)
289 {
290         int cnt = 0;
291         unsigned int byte = 0;
292         unsigned int bits = 0;
293         int incnt = 0;
294         while(*src && *src != '=' && (cnt < max)) {
295                 /* Shift in 6 bits of input */
296                 byte <<= 6;
297                 byte |= (b2a[(int)(*src)]) & 0x3f;
298                 bits += 6;
299                 src++;
300                 incnt++;
301                 /* If we have at least 8 bits left over, take that character
302                    off the top */
303                 if (bits >= 8)  {
304                         bits -= 8;
305                         *dst = (byte >> bits) & 0xff;
306                         dst++;
307                         cnt++;
308                 }
309         }
310         /* Don't worry about left over bits, they're extra anyway */
311         return cnt;
312 }
313
314 /*! \brief encode text to BASE64 coding */
315 int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
316 {
317         int cnt = 0;
318         int col = 0;
319         unsigned int byte = 0;
320         int bits = 0;
321         int cntin = 0;
322         /* Reserve space for null byte at end of string */
323         max--;
324         while ((cntin < srclen) && (cnt < max)) {
325                 byte <<= 8;
326                 byte |= *(src++);
327                 bits += 8;
328                 cntin++;
329                 if ((bits == 24) && (cnt + 4 <= max)) {
330                         *dst++ = base64[(byte >> 18) & 0x3f];
331                         *dst++ = base64[(byte >> 12) & 0x3f];
332                         *dst++ = base64[(byte >> 6) & 0x3f];
333                         *dst++ = base64[byte & 0x3f];
334                         cnt += 4;
335                         col += 4;
336                         bits = 0;
337                         byte = 0;
338                 }
339                 if (linebreaks && (cnt < max) && (col == 64)) {
340                         *dst++ = '\n';
341                         cnt++;
342                         col = 0;
343                 }
344         }
345         if (bits && (cnt + 4 <= max)) {
346                 /* Add one last character for the remaining bits,
347                    padding the rest with 0 */
348                 byte <<= 24 - bits;
349                 *dst++ = base64[(byte >> 18) & 0x3f];
350                 *dst++ = base64[(byte >> 12) & 0x3f];
351                 if (bits == 16)
352                         *dst++ = base64[(byte >> 6) & 0x3f];
353                 else
354                         *dst++ = '=';
355                 *dst++ = '=';
356                 cnt += 4;
357         }
358         if (linebreaks && (cnt < max)) {
359                 *dst++ = '\n';
360                 cnt++;
361         }
362         *dst = '\0';
363         return cnt;
364 }
365
366 int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
367 {
368         return ast_base64encode_full(dst, src, srclen, max, 0);
369 }
370
371 static void base64_init(void)
372 {
373         int x;
374         memset(b2a, -1, sizeof(b2a));
375         /* Initialize base-64 Conversion table */
376         for (x = 0; x < 26; x++) {
377                 /* A-Z */
378                 base64[x] = 'A' + x;
379                 b2a['A' + x] = x;
380                 /* a-z */
381                 base64[x + 26] = 'a' + x;
382                 b2a['a' + x] = x + 26;
383                 /* 0-9 */
384                 if (x < 10) {
385                         base64[x + 52] = '0' + x;
386                         b2a['0' + x] = x + 52;
387                 }
388         }
389         base64[62] = '+';
390         base64[63] = '/';
391         b2a[(int)'+'] = 62;
392         b2a[(int)'/'] = 63;
393 }
394
395 const struct ast_flags ast_uri_http = {AST_URI_UNRESERVED};
396 const struct ast_flags ast_uri_http_legacy = {AST_URI_LEGACY_SPACE | AST_URI_UNRESERVED};
397 const struct ast_flags ast_uri_sip_user = {AST_URI_UNRESERVED | AST_URI_SIP_USER_UNRESERVED};
398
399 char *ast_uri_encode(const char *string, char *outbuf, int buflen, struct ast_flags spec)
400 {
401         const char *ptr  = string;      /* Start with the string */
402         char *out = outbuf;
403         const char *mark = "-_.!~*'()"; /* no encode set, RFC 2396 section 2.3, RFC 3261 sec 25 */
404         const char *user_unreserved = "&=+$,;?/"; /* user-unreserved set, RFC 3261 sec 25 */
405
406         while (*ptr && out - outbuf < buflen - 1) {
407                 if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *ptr == ' ') {
408                         /* for legacy encoding, encode spaces as '+' */
409                         *out = '+';
410                         out++;
411                 } else if (!(ast_test_flag(&spec, AST_URI_MARK)
412                                 && strchr(mark, *ptr))
413                         && !(ast_test_flag(&spec, AST_URI_ALPHANUM)
414                                 && ((*ptr >= '0' && *ptr <= '9')
415                                 || (*ptr >= 'A' && *ptr <= 'Z')
416                                 || (*ptr >= 'a' && *ptr <= 'z')))
417                         && !(ast_test_flag(&spec, AST_URI_SIP_USER_UNRESERVED)
418                                 && strchr(user_unreserved, *ptr))) {
419
420                         if (out - outbuf >= buflen - 3) {
421                                 break;
422                         }
423                         out += sprintf(out, "%%%02X", (unsigned char) *ptr);
424                 } else {
425                         *out = *ptr;    /* Continue copying the string */
426                         out++;
427                 }
428                 ptr++;
429         }
430
431         if (buflen) {
432                 *out = '\0';
433         }
434
435         return outbuf;
436 }
437
438 void ast_uri_decode(char *s, struct ast_flags spec)
439 {
440         char *o;
441         unsigned int tmp;
442
443         for (o = s; *s; s++, o++) {
444                 if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *s == '+') {
445                         /* legacy mode, decode '+' as space */
446                         *o = ' ';
447                 } else if (*s == '%' && s[1] != '\0' && s[2] != '\0' && sscanf(s + 1, "%2x", &tmp) == 1) {
448                         /* have '%', two chars and correct parsing */
449                         *o = tmp;
450                         s += 2; /* Will be incremented once more when we break out */
451                 } else /* all other cases, just copy */
452                         *o = *s;
453         }
454         *o = '\0';
455 }
456
457 char *ast_escape_quoted(const char *string, char *outbuf, int buflen)
458 {
459         const char *ptr  = string;
460         char *out = outbuf;
461         char *allow = "\t\v !"; /* allow LWS (minus \r and \n) and "!" */
462
463         while (*ptr && out - outbuf < buflen - 1) {
464                 if (!(strchr(allow, *ptr))
465                         && !(*ptr >= '#' && *ptr <= '[') /* %x23 - %x5b */
466                         && !(*ptr >= ']' && *ptr <= '~') /* %x5d - %x7e */
467                         && !((unsigned char) *ptr > 0x7f)) {             /* UTF8-nonascii */
468
469                         if (out - outbuf >= buflen - 2) {
470                                 break;
471                         }
472                         out += sprintf(out, "\\%c", (unsigned char) *ptr);
473                 } else {
474                         *out = *ptr;
475                         out++;
476                 }
477                 ptr++;
478         }
479
480         if (buflen) {
481                 *out = '\0';
482         }
483
484         return outbuf;
485 }
486 int ast_xml_escape(const char *string, char * const outbuf, const size_t buflen)
487 {
488         char *dst = outbuf;
489         char *end = outbuf + buflen - 1; /* save one for the null terminator */
490
491         /* Handle the case for the empty output buffer */
492         if (buflen == 0) {
493                 return -1;
494         }
495
496         /* Escaping rules from http://www.w3.org/TR/REC-xml/#syntax */
497         /* This also prevents partial entities at the end of a string */
498         while (*string && dst < end) {
499                 const char *entity = NULL;
500                 int len = 0;
501
502                 switch (*string) {
503                 case '<':
504                         entity = "&lt;";
505                         len = 4;
506                         break;
507                 case '&':
508                         entity = "&amp;";
509                         len = 5;
510                         break;
511                 case '>':
512                         /* necessary if ]]> is in the string; easier to escape them all */
513                         entity = "&gt;";
514                         len = 4;
515                         break;
516                 case '\'':
517                         /* necessary in single-quoted strings; easier to escape them all */
518                         entity = "&apos;";
519                         len = 6;
520                         break;
521                 case '"':
522                         /* necessary in double-quoted strings; easier to escape them all */
523                         entity = "&quot;";
524                         len = 6;
525                         break;
526                 default:
527                         *dst++ = *string++;
528                         break;
529                 }
530
531                 if (entity) {
532                         ast_assert(len == strlen(entity));
533                         if (end - dst < len) {
534                                 /* no room for the entity; stop */
535                                 break;
536                         }
537                         /* just checked for length; strcpy is fine */
538                         strcpy(dst, entity);
539                         dst += len;
540                         ++string;
541                 }
542         }
543         /* Write null terminator */
544         *dst = '\0';
545         /* If any chars are left in string, return failure */
546         return *string == '\0' ? 0 : -1;
547 }
548
549 /*! \brief  ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa */
550 const char *ast_inet_ntoa(struct in_addr ia)
551 {
552         char *buf;
553
554         if (!(buf = ast_threadstorage_get(&inet_ntoa_buf, INET_ADDRSTRLEN)))
555                 return "";
556
557         return inet_ntop(AF_INET, &ia, buf, INET_ADDRSTRLEN);
558 }
559
560 static int dev_urandom_fd;
561
562 #ifndef __linux__
563 #undef pthread_create /* For ast_pthread_create function only */
564 #endif /* !__linux__ */
565
566 #if !defined(LOW_MEMORY)
567
568 #ifdef DEBUG_THREADS
569
570 /*! \brief A reasonable maximum number of locks a thread would be holding ... */
571 #define AST_MAX_LOCKS 64
572
573 /* Allow direct use of pthread_mutex_t and friends */
574 #undef pthread_mutex_t
575 #undef pthread_mutex_lock
576 #undef pthread_mutex_unlock
577 #undef pthread_mutex_init
578 #undef pthread_mutex_destroy
579
580 /*!
581  * \brief Keep track of which locks a thread holds
582  *
583  * There is an instance of this struct for every active thread
584  */
585 struct thr_lock_info {
586         /*! The thread's ID */
587         pthread_t thread_id;
588         /*! The thread name which includes where the thread was started */
589         const char *thread_name;
590         /*! This is the actual container of info for what locks this thread holds */
591         struct {
592                 const char *file;
593                 int line_num;
594                 const char *func;
595                 const char *lock_name;
596                 void *lock_addr;
597                 int times_locked;
598                 enum ast_lock_type type;
599                 /*! This thread is waiting on this lock */
600                 int pending:2;
601 #ifdef HAVE_BKTR
602                 struct ast_bt *backtrace;
603 #endif
604         } locks[AST_MAX_LOCKS];
605         /*! This is the number of locks currently held by this thread.
606          *  The index (num_locks - 1) has the info on the last one in the
607          *  locks member */
608         unsigned int num_locks;
609         /*! Protects the contents of the locks member
610          * Intentionally not ast_mutex_t */
611         pthread_mutex_t lock;
612         AST_LIST_ENTRY(thr_lock_info) entry;
613 };
614
615 /*!
616  * \brief Locked when accessing the lock_infos list
617  */
618 AST_MUTEX_DEFINE_STATIC(lock_infos_lock);
619 /*!
620  * \brief A list of each thread's lock info
621  */
622 static AST_LIST_HEAD_NOLOCK_STATIC(lock_infos, thr_lock_info);
623
624 /*!
625  * \brief Destroy a thread's lock info
626  *
627  * This gets called automatically when the thread stops
628  */
629 static void lock_info_destroy(void *data)
630 {
631         struct thr_lock_info *lock_info = data;
632         int i;
633
634         pthread_mutex_lock(&lock_infos_lock.mutex);
635         AST_LIST_REMOVE(&lock_infos, lock_info, entry);
636         pthread_mutex_unlock(&lock_infos_lock.mutex);
637
638
639         for (i = 0; i < lock_info->num_locks; i++) {
640                 if (lock_info->locks[i].pending == -1) {
641                         /* This just means that the last lock this thread went for was by
642                          * using trylock, and it failed.  This is fine. */
643                         break;
644                 }
645
646                 ast_log(LOG_ERROR,
647                         "Thread '%s' still has a lock! - '%s' (%p) from '%s' in %s:%d!\n",
648                         lock_info->thread_name,
649                         lock_info->locks[i].lock_name,
650                         lock_info->locks[i].lock_addr,
651                         lock_info->locks[i].func,
652                         lock_info->locks[i].file,
653                         lock_info->locks[i].line_num
654                 );
655         }
656
657         pthread_mutex_destroy(&lock_info->lock);
658         if (lock_info->thread_name)
659                 free((void *) lock_info->thread_name);
660         free(lock_info);
661 }
662
663 /*!
664  * \brief The thread storage key for per-thread lock info
665  */
666 AST_THREADSTORAGE_CUSTOM(thread_lock_info, NULL, lock_info_destroy);
667 #ifdef HAVE_BKTR
668 void ast_store_lock_info(enum ast_lock_type type, const char *filename,
669         int line_num, const char *func, const char *lock_name, void *lock_addr, struct ast_bt *bt)
670 #else
671 void ast_store_lock_info(enum ast_lock_type type, const char *filename,
672         int line_num, const char *func, const char *lock_name, void *lock_addr)
673 #endif
674 {
675         struct thr_lock_info *lock_info;
676         int i;
677
678         if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
679                 return;
680
681         pthread_mutex_lock(&lock_info->lock);
682
683         for (i = 0; i < lock_info->num_locks; i++) {
684                 if (lock_info->locks[i].lock_addr == lock_addr) {
685                         lock_info->locks[i].times_locked++;
686 #ifdef HAVE_BKTR
687                         lock_info->locks[i].backtrace = bt;
688 #endif
689                         pthread_mutex_unlock(&lock_info->lock);
690                         return;
691                 }
692         }
693
694         if (lock_info->num_locks == AST_MAX_LOCKS) {
695                 /* Can't use ast_log here, because it will cause infinite recursion */
696                 fprintf(stderr, "XXX ERROR XXX A thread holds more locks than '%d'."
697                         "  Increase AST_MAX_LOCKS!\n", AST_MAX_LOCKS);
698                 pthread_mutex_unlock(&lock_info->lock);
699                 return;
700         }
701
702         if (i && lock_info->locks[i - 1].pending == -1) {
703                 /* The last lock on the list was one that this thread tried to lock but
704                  * failed at doing so.  It has now moved on to something else, so remove
705                  * the old lock from the list. */
706                 i--;
707                 lock_info->num_locks--;
708                 memset(&lock_info->locks[i], 0, sizeof(lock_info->locks[0]));
709         }
710
711         lock_info->locks[i].file = filename;
712         lock_info->locks[i].line_num = line_num;
713         lock_info->locks[i].func = func;
714         lock_info->locks[i].lock_name = lock_name;
715         lock_info->locks[i].lock_addr = lock_addr;
716         lock_info->locks[i].times_locked = 1;
717         lock_info->locks[i].type = type;
718         lock_info->locks[i].pending = 1;
719 #ifdef HAVE_BKTR
720         lock_info->locks[i].backtrace = bt;
721 #endif
722         lock_info->num_locks++;
723
724         pthread_mutex_unlock(&lock_info->lock);
725 }
726
727 void ast_mark_lock_acquired(void *lock_addr)
728 {
729         struct thr_lock_info *lock_info;
730
731         if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
732                 return;
733
734         pthread_mutex_lock(&lock_info->lock);
735         if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
736                 lock_info->locks[lock_info->num_locks - 1].pending = 0;
737         }
738         pthread_mutex_unlock(&lock_info->lock);
739 }
740
741 void ast_mark_lock_failed(void *lock_addr)
742 {
743         struct thr_lock_info *lock_info;
744
745         if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
746                 return;
747
748         pthread_mutex_lock(&lock_info->lock);
749         if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
750                 lock_info->locks[lock_info->num_locks - 1].pending = -1;
751                 lock_info->locks[lock_info->num_locks - 1].times_locked--;
752         }
753         pthread_mutex_unlock(&lock_info->lock);
754 }
755
756 int ast_find_lock_info(void *lock_addr, char *filename, size_t filename_size, int *lineno, char *func, size_t func_size, char *mutex_name, size_t mutex_name_size)
757 {
758         struct thr_lock_info *lock_info;
759         int i = 0;
760
761         if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
762                 return -1;
763
764         pthread_mutex_lock(&lock_info->lock);
765
766         for (i = lock_info->num_locks - 1; i >= 0; i--) {
767                 if (lock_info->locks[i].lock_addr == lock_addr)
768                         break;
769         }
770
771         if (i == -1) {
772                 /* Lock not found :( */
773                 pthread_mutex_unlock(&lock_info->lock);
774                 return -1;
775         }
776
777         ast_copy_string(filename, lock_info->locks[i].file, filename_size);
778         *lineno = lock_info->locks[i].line_num;
779         ast_copy_string(func, lock_info->locks[i].func, func_size);
780         ast_copy_string(mutex_name, lock_info->locks[i].lock_name, mutex_name_size);
781
782         pthread_mutex_unlock(&lock_info->lock);
783
784         return 0;
785 }
786
787 #ifdef HAVE_BKTR
788 void ast_remove_lock_info(void *lock_addr, struct ast_bt *bt)
789 #else
790 void ast_remove_lock_info(void *lock_addr)
791 #endif
792 {
793         struct thr_lock_info *lock_info;
794         int i = 0;
795
796         if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
797                 return;
798
799         pthread_mutex_lock(&lock_info->lock);
800
801         for (i = lock_info->num_locks - 1; i >= 0; i--) {
802                 if (lock_info->locks[i].lock_addr == lock_addr)
803                         break;
804         }
805
806         if (i == -1) {
807                 /* Lock not found :( */
808                 pthread_mutex_unlock(&lock_info->lock);
809                 return;
810         }
811
812         if (lock_info->locks[i].times_locked > 1) {
813                 lock_info->locks[i].times_locked--;
814 #ifdef HAVE_BKTR
815                 lock_info->locks[i].backtrace = bt;
816 #endif
817                 pthread_mutex_unlock(&lock_info->lock);
818                 return;
819         }
820
821         if (i < lock_info->num_locks - 1) {
822                 /* Not the last one ... *should* be rare! */
823                 memmove(&lock_info->locks[i], &lock_info->locks[i + 1],
824                         (lock_info->num_locks - (i + 1)) * sizeof(lock_info->locks[0]));
825         }
826
827         lock_info->num_locks--;
828
829         pthread_mutex_unlock(&lock_info->lock);
830 }
831
832 static const char *locktype2str(enum ast_lock_type type)
833 {
834         switch (type) {
835         case AST_MUTEX:
836                 return "MUTEX";
837         case AST_RDLOCK:
838                 return "RDLOCK";
839         case AST_WRLOCK:
840                 return "WRLOCK";
841         }
842
843         return "UNKNOWN";
844 }
845
846 #ifdef HAVE_BKTR
847 static void append_backtrace_information(struct ast_str **str, struct ast_bt *bt)
848 {
849         char **symbols;
850         int num_frames;
851
852         if (!bt) {
853                 ast_str_append(str, 0, "\tNo backtrace to print\n");
854                 return;
855         }
856
857         /* store frame count locally to avoid the memory corruption that
858          * sometimes happens on virtualized CentOS 6.x systems */
859         num_frames = bt->num_frames;
860         if ((symbols = ast_bt_get_symbols(bt->addresses, num_frames))) {
861                 int frame_iterator;
862
863                 for (frame_iterator = 0; frame_iterator < num_frames; ++frame_iterator) {
864                         ast_str_append(str, 0, "\t%s\n", symbols[frame_iterator]);
865                 }
866
867                 free(symbols);
868         } else {
869                 ast_str_append(str, 0, "\tCouldn't retrieve backtrace symbols\n");
870         }
871 }
872 #endif
873
874 static void append_lock_information(struct ast_str **str, struct thr_lock_info *lock_info, int i)
875 {
876         int j;
877         ast_mutex_t *lock;
878         struct ast_lock_track *lt;
879
880         ast_str_append(str, 0, "=== ---> %sLock #%d (%s): %s %d %s %s %p (%d)\n",
881                                    lock_info->locks[i].pending > 0 ? "Waiting for " :
882                                    lock_info->locks[i].pending < 0 ? "Tried and failed to get " : "", i,
883                                    lock_info->locks[i].file,
884                                    locktype2str(lock_info->locks[i].type),
885                                    lock_info->locks[i].line_num,
886                                    lock_info->locks[i].func, lock_info->locks[i].lock_name,
887                                    lock_info->locks[i].lock_addr,
888                                    lock_info->locks[i].times_locked);
889 #ifdef HAVE_BKTR
890         append_backtrace_information(str, lock_info->locks[i].backtrace);
891 #endif
892
893         if (!lock_info->locks[i].pending || lock_info->locks[i].pending == -1)
894                 return;
895
896         /* We only have further details for mutexes right now */
897         if (lock_info->locks[i].type != AST_MUTEX)
898                 return;
899
900         lock = lock_info->locks[i].lock_addr;
901         lt = lock->track;
902         ast_reentrancy_lock(lt);
903         for (j = 0; *str && j < lt->reentrancy; j++) {
904                 ast_str_append(str, 0, "=== --- ---> Locked Here: %s line %d (%s)\n",
905                                            lt->file[j], lt->lineno[j], lt->func[j]);
906         }
907         ast_reentrancy_unlock(lt);
908 }
909
910
911 /*! This function can help you find highly temporal locks; locks that happen for a
912     short time, but at unexpected times, usually at times that create a deadlock,
913         Why is this thing locked right then? Who is locking it? Who am I fighting
914     with for this lock?
915
916         To answer such questions, just call this routine before you would normally try
917         to aquire a lock. It doesn't do anything if the lock is not acquired. If the
918         lock is taken, it will publish a line or two to the console via ast_log().
919
920         Sometimes, the lock message is pretty uninformative. For instance, you might
921         find that the lock is being aquired deep within the astobj2 code; this tells
922         you little about higher level routines that call the astobj2 routines.
923         But, using gdb, you can set a break at the ast_log below, and for that
924         breakpoint, you can set the commands:
925           where
926           cont
927         which will give a stack trace and continue. -- that aught to do the job!
928
929 */
930 void log_show_lock(void *this_lock_addr)
931 {
932         struct thr_lock_info *lock_info;
933         struct ast_str *str;
934
935         if (!(str = ast_str_create(4096))) {
936                 ast_log(LOG_NOTICE,"Could not create str\n");
937                 return;
938         }
939
940
941         pthread_mutex_lock(&lock_infos_lock.mutex);
942         AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
943                 int i;
944                 pthread_mutex_lock(&lock_info->lock);
945                 for (i = 0; str && i < lock_info->num_locks; i++) {
946                         /* ONLY show info about this particular lock, if
947                            it's acquired... */
948                         if (lock_info->locks[i].lock_addr == this_lock_addr) {
949                                 append_lock_information(&str, lock_info, i);
950                                 ast_log(LOG_NOTICE, "%s", ast_str_buffer(str));
951                                 break;
952                         }
953                 }
954                 pthread_mutex_unlock(&lock_info->lock);
955         }
956         pthread_mutex_unlock(&lock_infos_lock.mutex);
957         ast_free(str);
958 }
959
960
961 static char *handle_show_locks(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
962 {
963         struct thr_lock_info *lock_info;
964         struct ast_str *str;
965
966         if (!(str = ast_str_create(4096)))
967                 return CLI_FAILURE;
968
969         switch (cmd) {
970         case CLI_INIT:
971                 e->command = "core show locks";
972                 e->usage =
973                         "Usage: core show locks\n"
974                         "       This command is for lock debugging.  It prints out which locks\n"
975                         "are owned by each active thread.\n";
976                 return NULL;
977
978         case CLI_GENERATE:
979                 return NULL;
980         }
981
982         ast_str_append(&str, 0, "\n"
983                        "=======================================================================\n"
984                        "=== Currently Held Locks ==============================================\n"
985                        "=======================================================================\n"
986                        "===\n"
987                        "=== <pending> <lock#> (<file>): <lock type> <line num> <function> <lock name> <lock addr> (times locked)\n"
988                        "===\n");
989
990         if (!str)
991                 return CLI_FAILURE;
992
993         pthread_mutex_lock(&lock_infos_lock.mutex);
994         AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
995                 int i;
996                 if (lock_info->num_locks) {
997                         ast_str_append(&str, 0, "=== Thread ID: 0x%lx (%s)\n", (long) lock_info->thread_id,
998                                 lock_info->thread_name);
999                         pthread_mutex_lock(&lock_info->lock);
1000                         for (i = 0; str && i < lock_info->num_locks; i++) {
1001                                 append_lock_information(&str, lock_info, i);
1002                         }
1003                         pthread_mutex_unlock(&lock_info->lock);
1004                         if (!str)
1005                                 break;
1006                         ast_str_append(&str, 0, "=== -------------------------------------------------------------------\n"
1007                                        "===\n");
1008                         if (!str)
1009                                 break;
1010                 }
1011         }
1012         pthread_mutex_unlock(&lock_infos_lock.mutex);
1013
1014         if (!str)
1015                 return CLI_FAILURE;
1016
1017         ast_str_append(&str, 0, "=======================================================================\n"
1018                        "\n");
1019
1020         if (!str)
1021                 return CLI_FAILURE;
1022
1023         ast_cli(a->fd, "%s", ast_str_buffer(str));
1024
1025         ast_free(str);
1026
1027         return CLI_SUCCESS;
1028 }
1029
1030 static struct ast_cli_entry utils_cli[] = {
1031         AST_CLI_DEFINE(handle_show_locks, "Show which locks are held by which thread"),
1032 };
1033
1034 #endif /* DEBUG_THREADS */
1035
1036 /*
1037  * support for 'show threads'. The start routine is wrapped by
1038  * dummy_start(), so that ast_register_thread() and
1039  * ast_unregister_thread() know the thread identifier.
1040  */
1041 struct thr_arg {
1042         void *(*start_routine)(void *);
1043         void *data;
1044         char *name;
1045 };
1046
1047 /*
1048  * on OS/X, pthread_cleanup_push() and pthread_cleanup_pop()
1049  * are odd macros which start and end a block, so they _must_ be
1050  * used in pairs (the latter with a '1' argument to call the
1051  * handler on exit.
1052  * On BSD we don't need this, but we keep it for compatibility.
1053  */
1054 static void *dummy_start(void *data)
1055 {
1056         void *ret;
1057         struct thr_arg a = *((struct thr_arg *) data);  /* make a local copy */
1058 #ifdef DEBUG_THREADS
1059         struct thr_lock_info *lock_info;
1060         pthread_mutexattr_t mutex_attr;
1061
1062         if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
1063                 return NULL;
1064
1065         lock_info->thread_id = pthread_self();
1066         lock_info->thread_name = strdup(a.name);
1067
1068         pthread_mutexattr_init(&mutex_attr);
1069         pthread_mutexattr_settype(&mutex_attr, AST_MUTEX_KIND);
1070         pthread_mutex_init(&lock_info->lock, &mutex_attr);
1071         pthread_mutexattr_destroy(&mutex_attr);
1072
1073         pthread_mutex_lock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
1074         AST_LIST_INSERT_TAIL(&lock_infos, lock_info, entry);
1075         pthread_mutex_unlock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
1076 #endif /* DEBUG_THREADS */
1077
1078         /* note that even though data->name is a pointer to allocated memory,
1079            we are not freeing it here because ast_register_thread is going to
1080            keep a copy of the pointer and then ast_unregister_thread will
1081            free the memory
1082         */
1083         ast_free(data);
1084         ast_register_thread(a.name);
1085         pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
1086
1087         ret = a.start_routine(a.data);
1088
1089         pthread_cleanup_pop(1);
1090
1091         return ret;
1092 }
1093
1094 #endif /* !LOW_MEMORY */
1095
1096 int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
1097                              void *data, size_t stacksize, const char *file, const char *caller,
1098                              int line, const char *start_fn)
1099 {
1100 #if !defined(LOW_MEMORY)
1101         struct thr_arg *a;
1102 #endif
1103
1104         if (!attr) {
1105                 attr = ast_alloca(sizeof(*attr));
1106                 pthread_attr_init(attr);
1107         }
1108
1109 #ifdef __linux__
1110         /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
1111            which is kind of useless. Change this here to
1112            PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
1113            priority will propagate down to new threads by default.
1114            This does mean that callers cannot set a different priority using
1115            PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
1116            the priority afterwards with pthread_setschedparam(). */
1117         if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
1118                 ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
1119 #endif
1120
1121         if (!stacksize)
1122                 stacksize = AST_STACKSIZE;
1123
1124         if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
1125                 ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
1126
1127 #if !defined(LOW_MEMORY)
1128         if ((a = ast_malloc(sizeof(*a)))) {
1129                 a->start_routine = start_routine;
1130                 a->data = data;
1131                 start_routine = dummy_start;
1132                 if (ast_asprintf(&a->name, "%-20s started at [%5d] %s %s()",
1133                              start_fn, line, file, caller) < 0) {
1134                         a->name = NULL;
1135                 }
1136                 data = a;
1137         }
1138 #endif /* !LOW_MEMORY */
1139
1140         return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
1141 }
1142
1143
1144 int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
1145                              void *data, size_t stacksize, const char *file, const char *caller,
1146                              int line, const char *start_fn)
1147 {
1148         unsigned char attr_destroy = 0;
1149         int res;
1150
1151         if (!attr) {
1152                 attr = ast_alloca(sizeof(*attr));
1153                 pthread_attr_init(attr);
1154                 attr_destroy = 1;
1155         }
1156
1157         if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
1158                 ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
1159
1160         res = ast_pthread_create_stack(thread, attr, start_routine, data,
1161                                        stacksize, file, caller, line, start_fn);
1162
1163         if (attr_destroy)
1164                 pthread_attr_destroy(attr);
1165
1166         return res;
1167 }
1168
1169 int ast_wait_for_input(int fd, int ms)
1170 {
1171         struct pollfd pfd[1];
1172         memset(pfd, 0, sizeof(pfd));
1173         pfd[0].fd = fd;
1174         pfd[0].events = POLLIN|POLLPRI;
1175         return ast_poll(pfd, 1, ms);
1176 }
1177
1178 static int ast_wait_for_output(int fd, int timeoutms)
1179 {
1180         struct pollfd pfd = {
1181                 .fd = fd,
1182                 .events = POLLOUT,
1183         };
1184         int res;
1185         struct timeval start = ast_tvnow();
1186         int elapsed = 0;
1187
1188         /* poll() until the fd is writable without blocking */
1189         while ((res = ast_poll(&pfd, 1, timeoutms - elapsed)) <= 0) {
1190                 if (res == 0) {
1191                         /* timed out. */
1192 #ifndef STANDALONE
1193                         ast_debug(1, "Timed out trying to write\n");
1194 #endif
1195                         return -1;
1196                 } else if (res == -1) {
1197                         /* poll() returned an error, check to see if it was fatal */
1198
1199                         if (errno == EINTR || errno == EAGAIN) {
1200                                 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1201                                 if (elapsed >= timeoutms) {
1202                                         return -1;
1203                                 }
1204                                 /* This was an acceptable error, go back into poll() */
1205                                 continue;
1206                         }
1207
1208                         /* Fatal error, bail. */
1209                         ast_log(LOG_ERROR, "poll returned error: %s\n", strerror(errno));
1210
1211                         return -1;
1212                 }
1213                 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1214                 if (elapsed >= timeoutms) {
1215                         return -1;
1216                 }
1217         }
1218
1219         return 0;
1220 }
1221
1222 /*!
1223  * Try to write string, but wait no more than ms milliseconds before timing out.
1224  *
1225  * \note The code assumes that the file descriptor has NONBLOCK set,
1226  * so there is only one system call made to do a write, unless we actually
1227  * have a need to wait.  This way, we get better performance.
1228  * If the descriptor is blocking, all assumptions on the guaranteed
1229  * detail do not apply anymore.
1230  */
1231 int ast_carefulwrite(int fd, char *s, int len, int timeoutms)
1232 {
1233         struct timeval start = ast_tvnow();
1234         int res = 0;
1235         int elapsed = 0;
1236
1237         while (len) {
1238                 if (ast_wait_for_output(fd, timeoutms - elapsed)) {
1239                         return -1;
1240                 }
1241
1242                 res = write(fd, s, len);
1243
1244                 if (res < 0 && errno != EAGAIN && errno != EINTR) {
1245                         /* fatal error from write() */
1246                         ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
1247                         return -1;
1248                 }
1249
1250                 if (res < 0) {
1251                         /* It was an acceptable error */
1252                         res = 0;
1253                 }
1254
1255                 /* Update how much data we have left to write */
1256                 len -= res;
1257                 s += res;
1258                 res = 0;
1259
1260                 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1261                 if (elapsed >= timeoutms) {
1262                         /* We've taken too long to write
1263                          * This is only an error condition if we haven't finished writing. */
1264                         res = len ? -1 : 0;
1265                         break;
1266                 }
1267         }
1268
1269         return res;
1270 }
1271
1272 int ast_careful_fwrite(FILE *f, int fd, const char *src, size_t len, int timeoutms)
1273 {
1274         struct timeval start = ast_tvnow();
1275         int n = 0;
1276         int elapsed = 0;
1277
1278         while (len) {
1279                 if (ast_wait_for_output(fd, timeoutms - elapsed)) {
1280                         /* poll returned a fatal error, so bail out immediately. */
1281                         return -1;
1282                 }
1283
1284                 /* Clear any errors from a previous write */
1285                 clearerr(f);
1286
1287                 n = fwrite(src, 1, len, f);
1288
1289                 if (ferror(f) && errno != EINTR && errno != EAGAIN) {
1290                         /* fatal error from fwrite() */
1291                         if (!feof(f)) {
1292                                 /* Don't spam the logs if it was just that the connection is closed. */
1293                                 ast_log(LOG_ERROR, "fwrite() returned error: %s\n", strerror(errno));
1294                         }
1295                         n = -1;
1296                         break;
1297                 }
1298
1299                 /* Update for data already written to the socket */
1300                 len -= n;
1301                 src += n;
1302
1303                 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1304                 if (elapsed >= timeoutms) {
1305                         /* We've taken too long to write
1306                          * This is only an error condition if we haven't finished writing. */
1307                         n = len ? -1 : 0;
1308                         break;
1309                 }
1310         }
1311
1312         while (fflush(f)) {
1313                 if (errno == EAGAIN || errno == EINTR) {
1314                         continue;
1315                 }
1316                 if (!feof(f)) {
1317                         /* Don't spam the logs if it was just that the connection is closed. */
1318                         ast_log(LOG_ERROR, "fflush() returned error: %s\n", strerror(errno));
1319                 }
1320                 n = -1;
1321                 break;
1322         }
1323
1324         return n < 0 ? -1 : 0;
1325 }
1326
1327 char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
1328 {
1329         char *e;
1330         char *q;
1331
1332         s = ast_strip(s);
1333         if ((q = strchr(beg_quotes, *s)) && *q != '\0') {
1334                 e = s + strlen(s) - 1;
1335                 if (*e == *(end_quotes + (q - beg_quotes))) {
1336                         s++;
1337                         *e = '\0';
1338                 }
1339         }
1340
1341         return s;
1342 }
1343
1344 char *ast_unescape_semicolon(char *s)
1345 {
1346         char *e;
1347         char *work = s;
1348
1349         while ((e = strchr(work, ';'))) {
1350                 if ((e > work) && (*(e-1) == '\\')) {
1351                         memmove(e - 1, e, strlen(e) + 1);
1352                         work = e;
1353                 } else {
1354                         work = e + 1;
1355                 }
1356         }
1357
1358         return s;
1359 }
1360
1361 /* !\brief unescape some C sequences in place, return pointer to the original string.
1362  */
1363 char *ast_unescape_c(char *src)
1364 {
1365         char c, *ret, *dst;
1366
1367         if (src == NULL)
1368                 return NULL;
1369         for (ret = dst = src; (c = *src++); *dst++ = c ) {
1370                 if (c != '\\')
1371                         continue;       /* copy char at the end of the loop */
1372                 switch ((c = *src++)) {
1373                 case '\0':      /* special, trailing '\' */
1374                         c = '\\';
1375                         break;
1376                 case 'b':       /* backspace */
1377                         c = '\b';
1378                         break;
1379                 case 'f':       /* form feed */
1380                         c = '\f';
1381                         break;
1382                 case 'n':
1383                         c = '\n';
1384                         break;
1385                 case 'r':
1386                         c = '\r';
1387                         break;
1388                 case 't':
1389                         c = '\t';
1390                         break;
1391                 }
1392                 /* default, use the char literally */
1393         }
1394         *dst = '\0';
1395         return ret;
1396 }
1397
1398 int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap)
1399 {
1400         int result;
1401
1402         if (!buffer || !*buffer || !space || !*space)
1403                 return -1;
1404
1405         result = vsnprintf(*buffer, *space, fmt, ap);
1406
1407         if (result < 0)
1408                 return -1;
1409         else if (result > *space)
1410                 result = *space;
1411
1412         *buffer += result;
1413         *space -= result;
1414         return 0;
1415 }
1416
1417 int ast_build_string(char **buffer, size_t *space, const char *fmt, ...)
1418 {
1419         va_list ap;
1420         int result;
1421
1422         va_start(ap, fmt);
1423         result = ast_build_string_va(buffer, space, fmt, ap);
1424         va_end(ap);
1425
1426         return result;
1427 }
1428
1429 int ast_regex_string_to_regex_pattern(const char *regex_string, struct ast_str **regex_pattern)
1430 {
1431         int regex_len = strlen(regex_string);
1432         int ret = 3;
1433
1434         /* Chop off the leading / if there is one */
1435         if ((regex_len >= 1) && (regex_string[0] == '/')) {
1436                 ast_str_set(regex_pattern, 0, "%s", regex_string + 1);
1437                 ret -= 2;
1438         }
1439
1440         /* Chop off the ending / if there is one */
1441         if ((regex_len > 1) && (regex_string[regex_len - 1] == '/')) {
1442                 ast_str_truncate(*regex_pattern, -1);
1443                 ret -= 1;
1444         }
1445
1446         return ret;
1447 }
1448
1449 int ast_true(const char *s)
1450 {
1451         if (ast_strlen_zero(s))
1452                 return 0;
1453
1454         /* Determine if this is a true value */
1455         if (!strcasecmp(s, "yes") ||
1456             !strcasecmp(s, "true") ||
1457             !strcasecmp(s, "y") ||
1458             !strcasecmp(s, "t") ||
1459             !strcasecmp(s, "1") ||
1460             !strcasecmp(s, "on"))
1461                 return -1;
1462
1463         return 0;
1464 }
1465
1466 int ast_false(const char *s)
1467 {
1468         if (ast_strlen_zero(s))
1469                 return 0;
1470
1471         /* Determine if this is a false value */
1472         if (!strcasecmp(s, "no") ||
1473             !strcasecmp(s, "false") ||
1474             !strcasecmp(s, "n") ||
1475             !strcasecmp(s, "f") ||
1476             !strcasecmp(s, "0") ||
1477             !strcasecmp(s, "off"))
1478                 return -1;
1479
1480         return 0;
1481 }
1482
1483 #define ONE_MILLION     1000000
1484 /*
1485  * put timeval in a valid range. usec is 0..999999
1486  * negative values are not allowed and truncated.
1487  */
1488 static struct timeval tvfix(struct timeval a)
1489 {
1490         if (a.tv_usec >= ONE_MILLION) {
1491                 ast_log(LOG_WARNING, "warning too large timestamp %ld.%ld\n",
1492                         (long)a.tv_sec, (long int) a.tv_usec);
1493                 a.tv_sec += a.tv_usec / ONE_MILLION;
1494                 a.tv_usec %= ONE_MILLION;
1495         } else if (a.tv_usec < 0) {
1496                 ast_log(LOG_WARNING, "warning negative timestamp %ld.%ld\n",
1497                         (long)a.tv_sec, (long int) a.tv_usec);
1498                 a.tv_usec = 0;
1499         }
1500         return a;
1501 }
1502
1503 struct timeval ast_tvadd(struct timeval a, struct timeval b)
1504 {
1505         /* consistency checks to guarantee usec in 0..999999 */
1506         a = tvfix(a);
1507         b = tvfix(b);
1508         a.tv_sec += b.tv_sec;
1509         a.tv_usec += b.tv_usec;
1510         if (a.tv_usec >= ONE_MILLION) {
1511                 a.tv_sec++;
1512                 a.tv_usec -= ONE_MILLION;
1513         }
1514         return a;
1515 }
1516
1517 struct timeval ast_tvsub(struct timeval a, struct timeval b)
1518 {
1519         /* consistency checks to guarantee usec in 0..999999 */
1520         a = tvfix(a);
1521         b = tvfix(b);
1522         a.tv_sec -= b.tv_sec;
1523         a.tv_usec -= b.tv_usec;
1524         if (a.tv_usec < 0) {
1525                 a.tv_sec-- ;
1526                 a.tv_usec += ONE_MILLION;
1527         }
1528         return a;
1529 }
1530
1531 int ast_remaining_ms(struct timeval start, int max_ms)
1532 {
1533         int ms;
1534
1535         if (max_ms < 0) {
1536                 ms = max_ms;
1537         } else {
1538                 ms = max_ms - ast_tvdiff_ms(ast_tvnow(), start);
1539                 if (ms < 0) {
1540                         ms = 0;
1541                 }
1542         }
1543
1544         return ms;
1545 }
1546
1547 #undef ONE_MILLION
1548
1549 #ifndef linux
1550 AST_MUTEX_DEFINE_STATIC(randomlock);
1551 #endif
1552
1553 long int ast_random(void)
1554 {
1555         long int res;
1556
1557         if (dev_urandom_fd >= 0) {
1558                 int read_res = read(dev_urandom_fd, &res, sizeof(res));
1559                 if (read_res > 0) {
1560                         long int rm = RAND_MAX;
1561                         res = res < 0 ? ~res : res;
1562                         rm++;
1563                         return res % rm;
1564                 }
1565         }
1566
1567         /* XXX - Thread safety really depends on the libc, not the OS.
1568          *
1569          * But... popular Linux libc's (uClibc, glibc, eglibc), all have a
1570          * somewhat thread safe random(3) (results are random, but not
1571          * reproducible). The libc's for other systems (BSD, et al.), not so
1572          * much.
1573          */
1574 #ifdef linux
1575         res = random();
1576 #else
1577         ast_mutex_lock(&randomlock);
1578         res = random();
1579         ast_mutex_unlock(&randomlock);
1580 #endif
1581         return res;
1582 }
1583
1584 void ast_replace_subargument_delimiter(char *s)
1585 {
1586         for (; *s; s++) {
1587                 if (*s == '^') {
1588                         *s = ',';
1589                 }
1590         }
1591 }
1592
1593 char *ast_process_quotes_and_slashes(char *start, char find, char replace_with)
1594 {
1595         char *dataPut = start;
1596         int inEscape = 0;
1597         int inQuotes = 0;
1598
1599         for (; *start; start++) {
1600                 if (inEscape) {
1601                         *dataPut++ = *start;       /* Always goes verbatim */
1602                         inEscape = 0;
1603                 } else {
1604                         if (*start == '\\') {
1605                                 inEscape = 1;      /* Do not copy \ into the data */
1606                         } else if (*start == '\'') {
1607                                 inQuotes = 1 - inQuotes;   /* Do not copy ' into the data */
1608                         } else {
1609                                 /* Replace , with |, unless in quotes */
1610                                 *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
1611                         }
1612                 }
1613         }
1614         if (start != dataPut)
1615                 *dataPut = 0;
1616         return dataPut;
1617 }
1618
1619 void ast_join(char *s, size_t len, const char * const w[])
1620 {
1621         int x, ofs = 0;
1622         const char *src;
1623
1624         /* Join words into a string */
1625         if (!s)
1626                 return;
1627         for (x = 0; ofs < len && w[x]; x++) {
1628                 if (x > 0)
1629                         s[ofs++] = ' ';
1630                 for (src = w[x]; *src && ofs < len; src++)
1631                         s[ofs++] = *src;
1632         }
1633         if (ofs == len)
1634                 ofs--;
1635         s[ofs] = '\0';
1636 }
1637
1638 /*
1639  * stringfields support routines.
1640  */
1641
1642 /* this is a little complex... string fields are stored with their
1643    allocated size in the bytes preceding the string; even the
1644    constant 'empty' string has to be this way, so the code that
1645    checks to see if there is enough room for a new string doesn't
1646    have to have any special case checks
1647 */
1648
1649 static const struct {
1650         ast_string_field_allocation allocation;
1651         char string[1];
1652 } __ast_string_field_empty_buffer;
1653
1654 ast_string_field __ast_string_field_empty = __ast_string_field_empty_buffer.string;
1655
1656 #define ALLOCATOR_OVERHEAD 48
1657
1658 static size_t optimal_alloc_size(size_t size)
1659 {
1660         unsigned int count;
1661
1662         size += ALLOCATOR_OVERHEAD;
1663
1664         for (count = 1; size; size >>= 1, count++);
1665
1666         return (1 << count) - ALLOCATOR_OVERHEAD;
1667 }
1668
1669 /*! \brief add a new block to the pool.
1670  * We can only allocate from the topmost pool, so the
1671  * fields in *mgr reflect the size of that only.
1672  */
1673 static int add_string_pool(struct ast_string_field_mgr *mgr, struct ast_string_field_pool **pool_head,
1674                            size_t size, const char *file, int lineno, const char *func)
1675 {
1676         struct ast_string_field_pool *pool;
1677         size_t alloc_size = optimal_alloc_size(sizeof(*pool) + size);
1678
1679 #if defined(__AST_DEBUG_MALLOC)
1680         if (!(pool = __ast_calloc(1, alloc_size, file, lineno, func))) {
1681                 return -1;
1682         }
1683 #else
1684         if (!(pool = ast_calloc(1, alloc_size))) {
1685                 return -1;
1686         }
1687 #endif
1688
1689         pool->prev = *pool_head;
1690         pool->size = alloc_size - sizeof(*pool);
1691         *pool_head = pool;
1692         mgr->last_alloc = NULL;
1693
1694         return 0;
1695 }
1696
1697 /*
1698  * This is an internal API, code should not use it directly.
1699  * It initializes all fields as empty, then uses 'size' for 3 functions:
1700  * size > 0 means initialize the pool list with a pool of given size.
1701  *      This must be called right after allocating the object.
1702  * size = 0 means release all pools except the most recent one.
1703  *      If the first pool was allocated via embedding in another
1704  *      object, that pool will be preserved instead.
1705  *      This is useful to e.g. reset an object to the initial value.
1706  * size < 0 means release all pools.
1707  *      This must be done before destroying the object.
1708  */
1709 int __ast_string_field_init(struct ast_string_field_mgr *mgr, struct ast_string_field_pool **pool_head,
1710                             int needed, const char *file, int lineno, const char *func)
1711 {
1712         const char **p = (const char **) pool_head + 1;
1713         struct ast_string_field_pool *cur = NULL;
1714         struct ast_string_field_pool *preserve = NULL;
1715
1716         /* clear fields - this is always necessary */
1717         while ((struct ast_string_field_mgr *) p != mgr) {
1718                 *p++ = __ast_string_field_empty;
1719         }
1720
1721         mgr->last_alloc = NULL;
1722 #if defined(__AST_DEBUG_MALLOC)
1723         mgr->owner_file = file;
1724         mgr->owner_func = func;
1725         mgr->owner_line = lineno;
1726 #endif
1727         if (needed > 0) {               /* allocate the initial pool */
1728                 *pool_head = NULL;
1729                 mgr->embedded_pool = NULL;
1730                 return add_string_pool(mgr, pool_head, needed, file, lineno, func);
1731         }
1732
1733         /* if there is an embedded pool, we can't actually release *all*
1734          * pools, we must keep the embedded one. if the caller is about
1735          * to free the structure that contains the stringfield manager
1736          * and embedded pool anyway, it will be freed as part of that
1737          * operation.
1738          */
1739         if ((needed < 0) && mgr->embedded_pool) {
1740                 needed = 0;
1741         }
1742
1743         if (needed < 0) {               /* reset all pools */
1744                 cur = *pool_head;
1745         } else if (mgr->embedded_pool) { /* preserve the embedded pool */
1746                 preserve = mgr->embedded_pool;
1747                 cur = *pool_head;
1748         } else {                        /* preserve the last pool */
1749                 if (*pool_head == NULL) {
1750                         ast_log(LOG_WARNING, "trying to reset empty pool\n");
1751                         return -1;
1752                 }
1753                 preserve = *pool_head;
1754                 cur = preserve->prev;
1755         }
1756
1757         if (preserve) {
1758                 preserve->prev = NULL;
1759                 preserve->used = preserve->active = 0;
1760         }
1761
1762         while (cur) {
1763                 struct ast_string_field_pool *prev = cur->prev;
1764
1765                 if (cur != preserve) {
1766                         ast_free(cur);
1767                 }
1768                 cur = prev;
1769         }
1770
1771         *pool_head = preserve;
1772
1773         return 0;
1774 }
1775
1776 ast_string_field __ast_string_field_alloc_space(struct ast_string_field_mgr *mgr,
1777                                                 struct ast_string_field_pool **pool_head, size_t needed)
1778 {
1779         char *result = NULL;
1780         size_t space = (*pool_head)->size - (*pool_head)->used;
1781         size_t to_alloc;
1782
1783         /* Make room for ast_string_field_allocation and make it a multiple of that. */
1784         to_alloc = ast_make_room_for(needed, ast_string_field_allocation);
1785         ast_assert(to_alloc % ast_alignof(ast_string_field_allocation) == 0);
1786
1787         if (__builtin_expect(to_alloc > space, 0)) {
1788                 size_t new_size = (*pool_head)->size;
1789
1790                 while (new_size < to_alloc) {
1791                         new_size *= 2;
1792                 }
1793
1794 #if defined(__AST_DEBUG_MALLOC)
1795                 if (add_string_pool(mgr, pool_head, new_size, mgr->owner_file, mgr->owner_line, mgr->owner_func))
1796                         return NULL;
1797 #else
1798                 if (add_string_pool(mgr, pool_head, new_size, __FILE__, __LINE__, __FUNCTION__))
1799                         return NULL;
1800 #endif
1801         }
1802
1803         /* pool->base is always aligned (gcc aligned attribute). We ensure that
1804          * to_alloc is also a multiple of ast_alignof(ast_string_field_allocation)
1805          * causing result to always be aligned as well; which in turn fixes that
1806          * AST_STRING_FIELD_ALLOCATION(result) is aligned. */
1807         result = (*pool_head)->base + (*pool_head)->used;
1808         (*pool_head)->used += to_alloc;
1809         (*pool_head)->active += needed;
1810         result += ast_alignof(ast_string_field_allocation);
1811         AST_STRING_FIELD_ALLOCATION(result) = needed;
1812         mgr->last_alloc = result;
1813
1814         return result;
1815 }
1816
1817 int __ast_string_field_ptr_grow(struct ast_string_field_mgr *mgr,
1818                                 struct ast_string_field_pool **pool_head, size_t needed,
1819                                 const ast_string_field *ptr)
1820 {
1821         ssize_t grow = needed - AST_STRING_FIELD_ALLOCATION(*ptr);
1822         size_t space = (*pool_head)->size - (*pool_head)->used;
1823
1824         if (*ptr != mgr->last_alloc) {
1825                 return 1;
1826         }
1827
1828         if (space < grow) {
1829                 return 1;
1830         }
1831
1832         (*pool_head)->used += grow;
1833         (*pool_head)->active += grow;
1834         AST_STRING_FIELD_ALLOCATION(*ptr) += grow;
1835
1836         return 0;
1837 }
1838
1839 void __ast_string_field_release_active(struct ast_string_field_pool *pool_head,
1840                                        const ast_string_field ptr)
1841 {
1842         struct ast_string_field_pool *pool, *prev;
1843
1844         if (ptr == __ast_string_field_empty) {
1845                 return;
1846         }
1847
1848         for (pool = pool_head, prev = NULL; pool; prev = pool, pool = pool->prev) {
1849                 if ((ptr >= pool->base) && (ptr <= (pool->base + pool->size))) {
1850                         pool->active -= AST_STRING_FIELD_ALLOCATION(ptr);
1851                         if ((pool->active == 0) && prev) {
1852                                 prev->prev = pool->prev;
1853                                 ast_free(pool);
1854                         }
1855                         break;
1856                 }
1857         }
1858 }
1859
1860 void __ast_string_field_ptr_build_va(struct ast_string_field_mgr *mgr,
1861                                      struct ast_string_field_pool **pool_head,
1862                                      ast_string_field *ptr, const char *format, va_list ap)
1863 {
1864         size_t needed;
1865         size_t available;
1866         size_t space = (*pool_head)->size - (*pool_head)->used;
1867         ssize_t grow;
1868         char *target;
1869         va_list ap2;
1870
1871         /* if the field already has space allocated, try to reuse it;
1872            otherwise, try to use the empty space at the end of the current
1873            pool
1874         */
1875         if (*ptr != __ast_string_field_empty) {
1876                 target = (char *) *ptr;
1877                 available = AST_STRING_FIELD_ALLOCATION(*ptr);
1878                 if (*ptr == mgr->last_alloc) {
1879                         available += space;
1880                 }
1881         } else {
1882                 /* pool->used is always a multiple of ast_alignof(ast_string_field_allocation)
1883                  * so we don't need to re-align anything here.
1884                  */
1885                 target = (*pool_head)->base + (*pool_head)->used + ast_alignof(ast_string_field_allocation);
1886                 available = space - ast_alignof(ast_string_field_allocation);
1887         }
1888
1889         va_copy(ap2, ap);
1890         needed = vsnprintf(target, available, format, ap2) + 1;
1891         va_end(ap2);
1892
1893         if (needed > available) {
1894                 /* the allocation could not be satisfied using the field's current allocation
1895                    (if it has one), or the space available in the pool (if it does not). allocate
1896                    space for it, adding a new string pool if necessary.
1897                 */
1898                 if (!(target = (char *) __ast_string_field_alloc_space(mgr, pool_head, needed))) {
1899                         return;
1900                 }
1901                 vsprintf(target, format, ap);
1902                 va_end(ap); /* XXX va_end without va_start? */
1903                 __ast_string_field_release_active(*pool_head, *ptr);
1904                 *ptr = target;
1905         } else if (*ptr != target) {
1906                 /* the allocation was satisfied using available space in the pool, but not
1907                    using the space already allocated to the field
1908                 */
1909                 __ast_string_field_release_active(*pool_head, *ptr);
1910                 mgr->last_alloc = *ptr = target;
1911                 AST_STRING_FIELD_ALLOCATION(target) = needed;
1912                 (*pool_head)->used += ast_make_room_for(needed, ast_string_field_allocation);
1913                 (*pool_head)->active += needed;
1914         } else if ((grow = (needed - AST_STRING_FIELD_ALLOCATION(*ptr))) > 0) {
1915                 /* the allocation was satisfied by using available space in the pool *and*
1916                    the field was the last allocated field from the pool, so it grew
1917                 */
1918                 AST_STRING_FIELD_ALLOCATION(*ptr) += grow;
1919                 (*pool_head)->used += ast_align_for(grow, ast_string_field_allocation);
1920                 (*pool_head)->active += grow;
1921         }
1922 }
1923
1924 void __ast_string_field_ptr_build(struct ast_string_field_mgr *mgr,
1925                                   struct ast_string_field_pool **pool_head,
1926                                   ast_string_field *ptr, const char *format, ...)
1927 {
1928         va_list ap;
1929
1930         va_start(ap, format);
1931         __ast_string_field_ptr_build_va(mgr, pool_head, ptr, format, ap);
1932         va_end(ap);
1933 }
1934
1935 void *__ast_calloc_with_stringfields(unsigned int num_structs, size_t struct_size, size_t field_mgr_offset,
1936                                      size_t field_mgr_pool_offset, size_t pool_size, const char *file,
1937                                      int lineno, const char *func)
1938 {
1939         struct ast_string_field_mgr *mgr;
1940         struct ast_string_field_pool *pool;
1941         struct ast_string_field_pool **pool_head;
1942         size_t pool_size_needed = sizeof(*pool) + pool_size;
1943         size_t size_to_alloc = optimal_alloc_size(struct_size + pool_size_needed);
1944         void *allocation;
1945         unsigned int x;
1946
1947 #if defined(__AST_DEBUG_MALLOC)
1948         if (!(allocation = __ast_calloc(num_structs, size_to_alloc, file, lineno, func))) {
1949                 return NULL;
1950         }
1951 #else
1952         if (!(allocation = ast_calloc(num_structs, size_to_alloc))) {
1953                 return NULL;
1954         }
1955 #endif
1956
1957         for (x = 0; x < num_structs; x++) {
1958                 void *base = allocation + (size_to_alloc * x);
1959                 const char **p;
1960
1961                 mgr = base + field_mgr_offset;
1962                 pool_head = base + field_mgr_pool_offset;
1963                 pool = base + struct_size;
1964
1965                 p = (const char **) pool_head + 1;
1966                 while ((struct ast_string_field_mgr *) p != mgr) {
1967                         *p++ = __ast_string_field_empty;
1968                 }
1969
1970                 mgr->embedded_pool = pool;
1971                 *pool_head = pool;
1972                 pool->size = size_to_alloc - struct_size - sizeof(*pool);
1973 #if defined(__AST_DEBUG_MALLOC)
1974                 mgr->owner_file = file;
1975                 mgr->owner_func = func;
1976                 mgr->owner_line = lineno;
1977 #endif
1978         }
1979
1980         return allocation;
1981 }
1982
1983 /* end of stringfields support */
1984
1985 AST_MUTEX_DEFINE_STATIC(fetchadd_m); /* used for all fetc&add ops */
1986
1987 int ast_atomic_fetchadd_int_slow(volatile int *p, int v)
1988 {
1989         int ret;
1990         ast_mutex_lock(&fetchadd_m);
1991         ret = *p;
1992         *p += v;
1993         ast_mutex_unlock(&fetchadd_m);
1994         return ret;
1995 }
1996
1997 /*! \brief
1998  * get values from config variables.
1999  */
2000 int ast_get_timeval(const char *src, struct timeval *dst, struct timeval _default, int *consumed)
2001 {
2002         long double dtv = 0.0;
2003         int scanned;
2004
2005         if (dst == NULL)
2006                 return -1;
2007
2008         *dst = _default;
2009
2010         if (ast_strlen_zero(src))
2011                 return -1;
2012
2013         /* only integer at the moment, but one day we could accept more formats */
2014         if (sscanf(src, "%30Lf%n", &dtv, &scanned) > 0) {
2015                 dst->tv_sec = dtv;
2016                 dst->tv_usec = (dtv - dst->tv_sec) * 1000000.0;
2017                 if (consumed)
2018                         *consumed = scanned;
2019                 return 0;
2020         } else
2021                 return -1;
2022 }
2023
2024 /*! \brief
2025  * get values from config variables.
2026  */
2027 int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed)
2028 {
2029         long t;
2030         int scanned;
2031
2032         if (dst == NULL)
2033                 return -1;
2034
2035         *dst = _default;
2036
2037         if (ast_strlen_zero(src))
2038                 return -1;
2039
2040         /* only integer at the moment, but one day we could accept more formats */
2041         if (sscanf(src, "%30ld%n", &t, &scanned) == 1) {
2042                 *dst = t;
2043                 if (consumed)
2044                         *consumed = scanned;
2045                 return 0;
2046         } else
2047                 return -1;
2048 }
2049
2050 void ast_enable_packet_fragmentation(int sock)
2051 {
2052 #if defined(HAVE_IP_MTU_DISCOVER)
2053         int val = IP_PMTUDISC_DONT;
2054
2055         if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
2056                 ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
2057 #endif /* HAVE_IP_MTU_DISCOVER */
2058 }
2059
2060 int ast_mkdir(const char *path, int mode)
2061 {
2062         char *ptr;
2063         int len = strlen(path), count = 0, x, piececount = 0;
2064         char *tmp = ast_strdupa(path);
2065         char **pieces;
2066         char *fullpath = ast_alloca(len + 1);
2067         int res = 0;
2068
2069         for (ptr = tmp; *ptr; ptr++) {
2070                 if (*ptr == '/')
2071                         count++;
2072         }
2073
2074         /* Count the components to the directory path */
2075         pieces = ast_alloca(count * sizeof(*pieces));
2076         for (ptr = tmp; *ptr; ptr++) {
2077                 if (*ptr == '/') {
2078                         *ptr = '\0';
2079                         pieces[piececount++] = ptr + 1;
2080                 }
2081         }
2082
2083         *fullpath = '\0';
2084         for (x = 0; x < piececount; x++) {
2085                 /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
2086                 strcat(fullpath, "/");
2087                 strcat(fullpath, pieces[x]);
2088                 res = mkdir(fullpath, mode);
2089                 if (res && errno != EEXIST)
2090                         return errno;
2091         }
2092         return 0;
2093 }
2094
2095 int ast_utils_init(void)
2096 {
2097         dev_urandom_fd = open("/dev/urandom", O_RDONLY);
2098         base64_init();
2099 #ifdef DEBUG_THREADS
2100 #if !defined(LOW_MEMORY)
2101         ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
2102 #endif
2103 #endif
2104         return 0;
2105 }
2106
2107
2108 /*!
2109  *\brief Parse digest authorization header.
2110  *\return Returns -1 if we have no auth or something wrong with digest.
2111  *\note This function may be used for Digest request and responce header.
2112  * request arg is set to nonzero, if we parse Digest Request.
2113  * pedantic arg can be set to nonzero if we need to do addition Digest check.
2114  */
2115 int ast_parse_digest(const char *digest, struct ast_http_digest *d, int request, int pedantic) {
2116         char *c;
2117         struct ast_str *str = ast_str_create(16);
2118
2119         /* table of recognised keywords, and places where they should be copied */
2120         const struct x {
2121                 const char *key;
2122                 const ast_string_field *field;
2123         } *i, keys[] = {
2124                 { "username=", &d->username },
2125                 { "realm=", &d->realm },
2126                 { "nonce=", &d->nonce },
2127                 { "uri=", &d->uri },
2128                 { "domain=", &d->domain },
2129                 { "response=", &d->response },
2130                 { "cnonce=", &d->cnonce },
2131                 { "opaque=", &d->opaque },
2132                 /* Special cases that cannot be directly copied */
2133                 { "algorithm=", NULL },
2134                 { "qop=", NULL },
2135                 { "nc=", NULL },
2136                 { NULL, 0 },
2137         };
2138
2139         if (ast_strlen_zero(digest) || !d || !str) {
2140                 ast_free(str);
2141                 return -1;
2142         }
2143
2144         ast_str_set(&str, 0, "%s", digest);
2145
2146         c = ast_skip_blanks(ast_str_buffer(str));
2147
2148         if (strncasecmp(c, "Digest ", strlen("Digest "))) {
2149                 ast_log(LOG_WARNING, "Missing Digest.\n");
2150                 ast_free(str);
2151                 return -1;
2152         }
2153         c += strlen("Digest ");
2154
2155         /* lookup for keys/value pair */
2156         while (c && *c && *(c = ast_skip_blanks(c))) {
2157                 /* find key */
2158                 for (i = keys; i->key != NULL; i++) {
2159                         char *src, *separator;
2160                         int unescape = 0;
2161                         if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
2162                                 continue;
2163                         }
2164
2165                         /* Found. Skip keyword, take text in quotes or up to the separator. */
2166                         c += strlen(i->key);
2167                         if (*c == '"') {
2168                                 src = ++c;
2169                                 separator = "\"";
2170                                 unescape = 1;
2171                         } else {
2172                                 src = c;
2173                                 separator = ",";
2174                         }
2175                         strsep(&c, separator); /* clear separator and move ptr */
2176                         if (unescape) {
2177                                 ast_unescape_c(src);
2178                         }
2179                         if (i->field) {
2180                                 ast_string_field_ptr_set(d, i->field, src);
2181                         } else {
2182                                 /* Special cases that require additional procesing */
2183                                 if (!strcasecmp(i->key, "algorithm=")) {
2184                                         if (strcasecmp(src, "MD5")) {
2185                                                 ast_log(LOG_WARNING, "Digest algorithm: \"%s\" not supported.\n", src);
2186                                                 ast_free(str);
2187                                                 return -1;
2188                                         }
2189                                 } else if (!strcasecmp(i->key, "qop=") && !strcasecmp(src, "auth")) {
2190                                         d->qop = 1;
2191                                 } else if (!strcasecmp(i->key, "nc=")) {
2192                                         unsigned long u;
2193                                         if (sscanf(src, "%30lx", &u) != 1) {
2194                                                 ast_log(LOG_WARNING, "Incorrect Digest nc value: \"%s\".\n", src);
2195                                                 ast_free(str);
2196                                                 return -1;
2197                                         }
2198                                         ast_string_field_set(d, nc, src);
2199                                 }
2200                         }
2201                         break;
2202                 }
2203                 if (i->key == NULL) { /* not found, try ',' */
2204                         strsep(&c, ",");
2205                 }
2206         }
2207         ast_free(str);
2208
2209         /* Digest checkout */
2210         if (ast_strlen_zero(d->realm) || ast_strlen_zero(d->nonce)) {
2211                 /* "realm" and "nonce" MUST be always exist */
2212                 return -1;
2213         }
2214
2215         if (!request) {
2216                 /* Additional check for Digest response */
2217                 if (ast_strlen_zero(d->username) || ast_strlen_zero(d->uri) || ast_strlen_zero(d->response)) {
2218                         return -1;
2219                 }
2220
2221                 if (pedantic && d->qop && (ast_strlen_zero(d->cnonce) || ast_strlen_zero(d->nc))) {
2222                         return -1;
2223                 }
2224         }
2225
2226         return 0;
2227 }
2228
2229 #ifndef __AST_DEBUG_MALLOC
2230 int _ast_asprintf(char **ret, const char *file, int lineno, const char *func, const char *fmt, ...)
2231 {
2232         int res;
2233         va_list ap;
2234
2235         va_start(ap, fmt);
2236         if ((res = vasprintf(ret, fmt, ap)) == -1) {
2237                 MALLOC_FAILURE_MSG;
2238         }
2239         va_end(ap);
2240
2241         return res;
2242 }
2243 #endif
2244
2245 int ast_get_tid(void)
2246 {
2247         int ret = -1;
2248 #if defined (__linux) && defined(SYS_gettid)
2249         ret = syscall(SYS_gettid); /* available since Linux 1.4.11 */
2250 #elif defined(__sun)
2251         ret = pthread_self();
2252 #elif defined(__APPLE__)
2253         ret = mach_thread_self();
2254         mach_port_deallocate(mach_task_self(), ret);
2255 #elif defined(__FreeBSD__) && defined(HAVE_SYS_THR_H)
2256         long lwpid;
2257         thr_self(&lwpid); /* available since sys/thr.h creation 2003 */
2258         ret = lwpid;
2259 #endif
2260         return ret;
2261 }
2262
2263 char *ast_utils_which(const char *binary, char *fullpath, size_t fullpath_size)
2264 {
2265         const char *envPATH = getenv("PATH");
2266         char *tpath, *path;
2267         struct stat unused;
2268         if (!envPATH) {
2269                 return NULL;
2270         }
2271         tpath = ast_strdupa(envPATH);
2272         while ((path = strsep(&tpath, ":"))) {
2273                 snprintf(fullpath, fullpath_size, "%s/%s", path, binary);
2274                 if (!stat(fullpath, &unused)) {
2275                         return fullpath;
2276                 }
2277         }
2278         return NULL;
2279 }
2280
2281 void ast_do_crash(void)
2282 {
2283 #if defined(DO_CRASH)
2284         abort();
2285         /*
2286          * Just in case abort() doesn't work or something else super
2287          * silly, and for Qwell's amusement.
2288          */
2289         *((int *) 0) = 0;
2290 #endif  /* defined(DO_CRASH) */
2291 }
2292
2293 #if defined(AST_DEVMODE)
2294 void __ast_assert_failed(int condition, const char *condition_str, const char *file, int line, const char *function)
2295 {
2296         /*
2297          * Attempt to put it into the logger, but hope that at least
2298          * someone saw the message on stderr ...
2299          */
2300         ast_log(__LOG_ERROR, file, line, function, "FRACK!, Failed assertion %s (%d)\n",
2301                 condition_str, condition);
2302         fprintf(stderr, "FRACK!, Failed assertion %s (%d) at line %d in %s of %s\n",
2303                 condition_str, condition, line, function, file);
2304         /*
2305          * Give the logger a chance to get the message out, just in case
2306          * we abort(), or Asterisk crashes due to whatever problem just
2307          * happened after we exit ast_assert().
2308          */
2309         usleep(1);
2310         ast_do_crash();
2311 }
2312 #endif  /* defined(AST_DEVMODE) */