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