Wed Jan 8 2020 09:49:51

Asterisk developer's documentation


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