Wed Jan 8 2020 09:50:21

Asterisk developer's documentation


utils.c File Reference

Utility functions. More...

#include "asterisk.h"
#include <ctype.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <fcntl.h>
#include "asterisk/network.h"
#include "asterisk/ast_version.h"
#include "asterisk/lock.h"
#include "asterisk/io.h"
#include "asterisk/md5.h"
#include "asterisk/sha1.h"
#include "asterisk/cli.h"
#include "asterisk/linkedlists.h"
#include "asterisk/strings.h"
#include "asterisk/time.h"
#include "asterisk/stringfields.h"
#include "asterisk/utils.h"
#include "asterisk/threadstorage.h"
#include "asterisk/config.h"

Go to the source code of this file.

Data Structures

struct  thr_arg
 

Macros

#define ALLOCATOR_OVERHEAD   48
 
#define AST_API_MODULE   /* ensure that inlinable API functions will be built in lock.h if required */
 
#define AST_API_MODULE   /* ensure that inlinable API functions will be built in this module if required */
 
#define AST_API_MODULE   /* ensure that inlinable API functions will be built in this module if required */
 
#define AST_API_MODULE   /* ensure that inlinable API functions will be built in this module if required */
 
#define AST_API_MODULE   /* ensure that inlinable API functions will be built in this module if required */
 
#define AST_API_MODULE
 
#define AST_API_MODULE
 
#define ONE_MILLION   1000000
 

Functions

void * __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)
 
ast_string_field __ast_string_field_alloc_space (struct ast_string_field_mgr *mgr, struct ast_string_field_pool **pool_head, size_t needed)
 
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)
 
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,...)
 
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 ap1, va_list ap2)
 
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)
 
void __ast_string_field_release_active (struct ast_string_field_pool *pool_head, const ast_string_field ptr)
 
static void __init_inet_ntoa_buf (void)
 
int _ast_asprintf (char **ret, const char *file, int lineno, const char *func, const char *fmt,...)
 
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 reflect the size of that only. More...
 
int ast_atomic_fetchadd_int_slow (volatile int *p, int v)
 
int ast_base64decode (unsigned char *dst, const char *src, int max)
 decode BASE64 encoded text More...
 
int ast_base64encode (char *dst, const unsigned char *src, int srclen, int max)
 Encode data in base64. More...
 
int ast_base64encode_full (char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
 encode text to BASE64 coding More...
 
int ast_build_string (char **buffer, size_t *space, const char *fmt,...)
 Build a string in a buffer, designed to be called repeatedly. More...
 
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. More...
 
int ast_careful_fwrite (FILE *f, int fd, const char *src, size_t len, int timeoutms)
 Write data to a file stream with a timeout. More...
 
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. More...
 
void ast_do_crash (void)
 Force a crash if DO_CRASH is defined. More...
 
void ast_enable_packet_fragmentation (int sock)
 Disable PMTU discovery on a socket. More...
 
char * ast_escape_quoted (const char *string, char *outbuf, int buflen)
 escapes characters specified for quoted portions of sip messages More...
 
int ast_false (const char *s)
 Make sure something is false. Determine if a string containing a boolean value is "false". This function checks to see whether a string passed to it is an indication of an "false" value. It checks to see if the string is "no", "false", "n", "f", "off" or "0". More...
 
int ast_get_tid (void)
 Get current thread ID. More...
 
int ast_get_time_t (const char *src, time_t *dst, time_t _default, int *consumed)
 get values from config variables. More...
 
int ast_get_timeval (const char *src, struct timeval *dst, struct timeval _default, int *consumed)
 get values from config variables. More...
 
struct hostent * ast_gethostbyname (const char *host, struct ast_hostent *hp)
 Re-entrant (thread safe) version of gethostbyname that replaces the standard gethostbyname (which is not thread safe) More...
 
const char * ast_inet_ntoa (struct in_addr ia)
 ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa More...
 
void ast_join (char *s, size_t len, const char *const w[])
 
void ast_md5_hash (char *output, const char *input)
 Produce 32 char MD5 hash of value. More...
 
int ast_mkdir (const char *path, int mode)
 Recursively create directory path. More...
 
int ast_parse_digest (const char *digest, struct ast_http_digest *d, int request, int pedantic)
 Parse digest authorization header. More...
 
char * ast_process_quotes_and_slashes (char *start, char find, char replace_with)
 Process a string to find and replace characters. More...
 
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)
 
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)
 
long int ast_random (void)
 
int ast_remaining_ms (struct timeval start, int max_ms)
 Calculate remaining milliseconds given a starting timestamp and upper bound. More...
 
void ast_sha1_hash (char *output, const char *input)
 Produce 40 char SHA1 hash of value. More...
 
char * ast_strip_quoted (char *s, const char *beg_quotes, const char *end_quotes)
 Strip leading/trailing whitespace and quotes from a string. More...
 
int ast_true (const char *s)
 Make sure something is true. Determine if a string containing a boolean value is "true". This function checks to see whether a string passed to it is an indication of an "true" value. It checks to see if the string is "yes", "true", "y", "t", "on" or "1". More...
 
struct timeval ast_tvadd (struct timeval a, struct timeval b)
 Returns the sum of two timevals a + b. More...
 
struct timeval ast_tvsub (struct timeval a, struct timeval b)
 Returns the difference of two timevals a - b. More...
 
char * ast_unescape_c (char *src)
 Convert some C escape sequences. More...
 
void ast_unescape_quoted (char *quote_str)
 Unescape quotes in a string. More...
 
char * ast_unescape_semicolon (char *s)
 Strip backslash for "escaped" semicolons, the string to be stripped (will be modified). More...
 
void ast_uri_decode (char *s)
 ast_uri_decode: Decode SIP URI, URN, URL (overwrite the string) More...
 
char * ast_uri_encode (const char *string, char *outbuf, int buflen, int do_special_char)
 Turn text string to URI-encoded XX version. More...
 
int ast_utils_init (void)
 
char * ast_utils_which (const char *binary, char *fullpath, size_t fullpath_size)
 Resolve a binary to a full pathname. More...
 
int ast_wait_for_input (int fd, int ms)
 
int ast_wait_for_output (int fd, int ms)
 
int ast_xml_escape (const char *string, char *const outbuf, const size_t buflen)
 Escape reserved characters for use in XML. More...
 
static void base64_init (void)
 
static void * dummy_start (void *data)
 
static size_t optimal_alloc_size (size_t size)
 
static struct timeval tvfix (struct timeval a)
 
static int wait_for_output (int fd, int timeoutms)
 

Variables

ast_string_field __ast_string_field_empty = __ast_string_field_empty_buffer.string
 
struct {
   ast_string_field_allocation   allocation
 
   char   string [1]
 
__ast_string_field_empty_buffer
 
static char b2a [256]
 
static char base64 [64]
 
static int dev_urandom_fd
 
static ast_mutex_t fetchadd_m = { PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP , NULL, 1 }
 
static struct ast_threadstorage inet_ntoa_buf = { .once = PTHREAD_ONCE_INIT , .key_init = __init_inet_ntoa_buf , .custom_init = NULL , }
 
static ast_mutex_t randomlock = { PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP , NULL, 1 }
 glibc puts a lock inside random(3), so that the results are thread-safe. BSD libc (and others) do not. More...
 

Detailed Description

Utility functions.

Note
These are important for portability and security, so please use them in favour of other routines. Please consult the CODING GUIDELINES for more information.

Definition in file utils.c.

Macro Definition Documentation

#define ALLOCATOR_OVERHEAD   48

Definition at line 1727 of file utils.c.

Referenced by optimal_alloc_size().

#define AST_API_MODULE   /* ensure that inlinable API functions will be built in lock.h if required */

Definition at line 75 of file utils.c.

#define AST_API_MODULE   /* ensure that inlinable API functions will be built in this module if required */

Definition at line 75 of file utils.c.

#define AST_API_MODULE   /* ensure that inlinable API functions will be built in this module if required */

Definition at line 75 of file utils.c.

#define AST_API_MODULE   /* ensure that inlinable API functions will be built in this module if required */

Definition at line 75 of file utils.c.

#define AST_API_MODULE   /* ensure that inlinable API functions will be built in this module if required */

Definition at line 75 of file utils.c.

#define AST_API_MODULE

Definition at line 75 of file utils.c.

#define AST_API_MODULE

Definition at line 75 of file utils.c.

#define ONE_MILLION   1000000

Definition at line 1567 of file utils.c.

Referenced by ast_tvadd(), ast_tvsub(), and tvfix().

Function Documentation

void* __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 at line 2026 of file utils.c.

References __ast_calloc(), __ast_string_field_empty, allocation, ast_calloc, ast_string_field_pool::base, ast_string_field_mgr::embedded_pool, optimal_alloc_size(), and ast_string_field_pool::size.

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 }
ast_string_field_allocation allocation
Definition: utils.c:1721
struct ast_string_field_pool * embedded_pool
Definition: stringfields.h:147
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)
static size_t optimal_alloc_size(size_t size)
Definition: utils.c:1729
#define ast_calloc(a, b)
Definition: astmm.h:82
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 at line 1847 of file utils.c.

References add_string_pool(), ast_alignof, ast_assert, ast_make_room_for, AST_STRING_FIELD_ALLOCATION, and ast_string_field_mgr::last_alloc.

Referenced by __ast_string_field_ptr_build_va().

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 }
uint16_t ast_string_field_allocation
Definition: stringfields.h:119
#define ast_alignof(type)
Return the number of bytes used in the alignment of type.
Definition: utils.h:760
#define ast_assert(a)
Definition: utils.h:738
#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 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
ast_string_field last_alloc
Definition: stringfields.h:146
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
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 at line 1780 of file utils.c.

References __ast_string_field_empty, ast_string_field_pool::active, add_string_pool(), ast_free, ast_log(), ast_string_field_mgr::embedded_pool, ast_string_field_mgr::last_alloc, LOG_WARNING, ast_string_field_pool::prev, and ast_string_field_pool::used.

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 }
struct ast_string_field_pool * embedded_pool
Definition: stringfields.h:147
#define LOG_WARNING
Definition: logger.h:144
const char * __ast_string_field_empty
Definition: utils.c:1725
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
#define ast_free(a)
Definition: astmm.h:97
struct ast_string_field_pool * prev
Definition: stringfields.h:134
ast_string_field last_alloc
Definition: stringfields.h:146
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
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 at line 2011 of file utils.c.

References __ast_string_field_ptr_build_va().

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 }
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
static snd_pcm_format_t format
Definition: chan_alsa.c:93
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  ap1,
va_list  ap2 
)

Definition at line 1935 of file utils.c.

References __ast_string_field_alloc_space(), __ast_string_field_empty, __ast_string_field_release_active(), ast_align_for, ast_alignof, ast_assert, ast_make_room_for, AST_STRING_FIELD_ALLOCATION, available(), and ast_string_field_mgr::last_alloc.

Referenced by __ast_string_field_ptr_build().

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 }
uint16_t ast_string_field_allocation
Definition: stringfields.h:119
#define ast_alignof(type)
Return the number of bytes used in the alignment of type.
Definition: utils.h:760
const char * __ast_string_field_empty
Definition: utils.c:1725
#define ast_assert(a)
Definition: utils.h:738
#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 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
void __ast_string_field_release_active(struct ast_string_field_pool *pool_head, const ast_string_field ptr)
Definition: utils.c:1910
static int available(struct dahdi_pvt **pvt, int is_specific_channel)
Definition: chan_dahdi.c:13288
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
#define ast_align_for(offset, type)
Increase offset so it is a multiple of the required alignment of type.
Definition: utils.h:780
static snd_pcm_format_t format
Definition: chan_alsa.c:93
ast_string_field last_alloc
Definition: stringfields.h:146
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 at line 1888 of file utils.c.

References AST_STRING_FIELD_ALLOCATION, and ast_string_field_mgr::last_alloc.

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 }
#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
ast_string_field last_alloc
Definition: stringfields.h:146
void __ast_string_field_release_active ( struct ast_string_field_pool pool_head,
const ast_string_field  ptr 
)

Definition at line 1910 of file utils.c.

References ast_string_field_pool::active, ast_free, AST_STRING_FIELD_ALLOCATION, and ast_string_field_pool::prev.

Referenced by __ast_string_field_ptr_build_va().

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 }
const char * __ast_string_field_empty
Definition: utils.c:1725
#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 ast_free(a)
Definition: astmm.h:97
struct ast_string_field_pool * prev
Definition: stringfields.h:134
static void __init_inet_ntoa_buf ( void  )
static

Definition at line 81 of file utils.c.

98 {
int _ast_asprintf ( char **  ret,
const char *  file,
int  lineno,
const char *  func,
const char *  fmt,
  ... 
)

Definition at line 2331 of file utils.c.

References MALLOC_FAILURE_MSG, and vasprintf().

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 }
int vasprintf(char **strp, const char *fmt, va_list ap)
#define MALLOC_FAILURE_MSG
Definition: utils.h:464
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 
)
static

add a new block to the pool. We can only allocate from the topmost pool, so the fields in *mgr reflect the size of that only.

Definition at line 1744 of file utils.c.

References __ast_calloc(), ast_calloc, ast_string_field_mgr::last_alloc, optimal_alloc_size(), ast_string_field_pool::prev, and ast_string_field_pool::size.

Referenced by __ast_string_field_alloc_space(), and __ast_string_field_init().

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 }
void * __ast_calloc(size_t nmemb, size_t size, const char *file, int lineno, const char *func)
static size_t optimal_alloc_size(size_t size)
Definition: utils.c:1729
#define ast_calloc(a, b)
Definition: astmm.h:82
struct ast_string_field_pool * prev
Definition: stringfields.h:134
ast_string_field last_alloc
Definition: stringfields.h:146
int ast_atomic_fetchadd_int_slow ( volatile int *  p,
int  v 
)

Definition at line 2078 of file utils.c.

References ast_mutex_lock, ast_mutex_unlock, and fetchadd_m.

2079 {
2080  int ret;
2082  ret = *p;
2083  *p += v;
2085  return ret;
2086 }
#define ast_mutex_lock(a)
Definition: lock.h:155
static ast_mutex_t fetchadd_m
Definition: utils.c:2076
#define ast_mutex_unlock(a)
Definition: lock.h:156
int ast_base64decode ( unsigned char *  dst,
const char *  src,
int  max 
)

decode BASE64 encoded text

Decode data from base64.

Definition at line 279 of file utils.c.

Referenced by aes_helper(), ast_check_signature(), base64_helper(), osp_validate_token(), sdp_crypto_process(), and sdp_crypto_setup().

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 }
static char b2a[256]
Definition: utils.c:79
int ast_base64encode ( char *  dst,
const unsigned char *  src,
int  srclen,
int  max 
)

Encode data in base64.

Parameters
dstthe destination buffer
srcthe source data to be encoded
srclenthe number of bytes present in the source buffer
maxthe maximum number of bytes to write into the destination buffer, including the terminating NULL character.

Definition at line 357 of file utils.c.

References ast_base64encode_full().

Referenced by aes_helper(), aji_start_sasl(), ast_sign(), base64_helper(), build_secret(), osp_check_destination(), and sdp_crypto_setup().

358 {
359  return ast_base64encode_full(dst, src, srclen, max, 0);
360 }
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
int ast_base64encode_full ( char *  dst,
const unsigned char *  src,
int  srclen,
int  max,
int  linebreaks 
)

encode text to BASE64 coding

Definition at line 306 of file utils.c.

Referenced by ast_base64encode().

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 }
static char base64[64]
Definition: utils.c:78
int ast_build_string ( char **  buffer,
size_t *  space,
const char *  fmt,
  ... 
)

Build a string in a buffer, designed to be called repeatedly.

Note
This method is not recommended. New code should use ast_str_*() instead.

This is a wrapper for snprintf, that properly handles the buffer pointer and buffer space available.

Parameters
buffercurrent position in buffer to place string into (will be updated on return)
spaceremaining space in buffer (will be updated on return)
fmtprintf-style format string
Return values
0on success
non-zeroon failure.

Definition at line 1521 of file utils.c.

References ast_build_string_va().

Referenced by ast_fax_caps_to_str(), config_odbc(), generate_filenames_string(), and handle_speechrecognize().

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 }
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
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.

This is a wrapper for snprintf, that properly handles the buffer pointer and buffer space available.

Returns
0 on success, non-zero on failure.
Parameters
buffercurrent position in buffer to place string into (will be updated on return)
spaceremaining space in buffer (will be updated on return)
fmtprintf-style format string
apvarargs list of arguments for format

Definition at line 1502 of file utils.c.

Referenced by ast_build_string().

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 }
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.

Parameters
fthe file stream to write to
fdthe file description to poll on to know when the file stream can be written to without blocking.
sthe buffer to write from
lenthe number of bytes to write
timeoutmsThe maximum amount of time to block in this function trying to write, specified in milliseconds.
Note
This function assumes that the associated file stream has been set up as non-blocking.
Return values
0success
-1error

Definition at line 1369 of file utils.c.

References ast_log(), ast_tvdiff_ms(), ast_tvnow(), errno, LOG_ERROR, and wait_for_output().

Referenced by send_string().

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 }
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:142
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:155
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
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
int errno
static struct ast_format f[]
Definition: format_g726.c:181
static int wait_for_output(int fd, int timeoutms)
Definition: utils.c:1275
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.

Try to write string, but wait no more than ms milliseconds before timing out.

Note
The code assumes that the file descriptor has NONBLOCK set, so there is only one system call made to do a write, unless we actually have a need to wait. This way, we get better performance. If the descriptor is blocking, all assumptions on the guaranteed detail do not apply anymore.

Definition at line 1328 of file utils.c.

References ast_log(), ast_tvdiff_ms(), ast_tvnow(), errno, LOG_ERROR, and wait_for_output().

Referenced by ast_agi_send(), and ast_cli().

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 }
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:142
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:155
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
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
int errno
static int wait_for_output(int fd, int timeoutms)
Definition: utils.c:1275
void ast_do_crash ( void  )

Force a crash if DO_CRASH is defined.

Note
If DO_CRASH is not defined then the function returns.
Returns
Nothing

Definition at line 2382 of file utils.c.

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 }
void ast_enable_packet_fragmentation ( int  sock)

Disable PMTU discovery on a socket.

Parameters
sockThe socket to manipulate
Returns
Nothing

On Linux, UDP sockets default to sending packets with the Dont Fragment (DF) bit set. This is supposedly done to allow the application to do PMTU discovery, but Asterisk does not do this.

Because of this, UDP packets sent by Asterisk that are larger than the MTU of any hop in the path will be lost. This function can be called on a socket to ensure that the DF bit will not be set.

Definition at line 2141 of file utils.c.

References ast_log(), and LOG_WARNING.

Referenced by ast_netsock_bindaddr(), and reload_config().

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 }
Definition: ast_expr2.c:325
#define LOG_WARNING
Definition: logger.h:144
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
char* ast_escape_quoted ( const char *  string,
char *  outbuf,
int  buflen 
)

escapes characters specified for quoted portions of sip messages

Escape characters found in a quoted string.

Definition at line 431 of file utils.c.

References string.

Referenced by add_diversion_header(), add_rpid(), ast_callerid_merge(), and initreqprep().

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 }
char string[1]
Definition: utils.c:1722
int ast_false ( const char *  val)

Make sure something is false. Determine if a string containing a boolean value is "false". This function checks to see whether a string passed to it is an indication of an "false" value. It checks to see if the string is "no", "false", "n", "f", "off" or "0".

Return values
0if val is a NULL pointer.
-1if "true".
0otherwise.

Definition at line 1550 of file utils.c.

References ast_strlen_zero().

Referenced by __ast_udptl_reload(), acf_faxopt_write(), acf_transaction_write(), actual_load_config(), aji_create_client(), aji_load_config(), aoc_cli_debug_enable(), build_peer(), build_user(), dahdi_set_dnd(), find_realtime(), func_channel_write_real(), handle_common_options(), init_acf_query(), load_config(), load_odbc_config(), manager_mute_mixmonitor(), parse_empty_options(), reload_config(), rtp_reload(), run_agi(), set_config(), set_insecure_flags(), sla_build_trunk(), and strings_to_mask().

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 }
static force_inline int attribute_pure ast_strlen_zero(const char *s)
Definition: strings.h:63
int ast_get_tid ( void  )

Get current thread ID.

Since
1.8.28.0
Returns
the ID if platform is supported, else -1

Definition at line 2346 of file utils.c.

Referenced by __ao2_alloc_debug(), __ao2_ref_debug(), and ast_log().

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 }
int ast_get_time_t ( const char *  src,
time_t *  dst,
time_t  _default,
int *  consumed 
)

get values from config variables.

Definition at line 2118 of file utils.c.

References ast_strlen_zero().

Referenced by build_peer(), cache_lookup_internal(), handle_saydatetime(), load_password(), play_message_datetime(), process_clearcache(), realtime_peer(), and sayunixtime_exec().

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 }
static force_inline int attribute_pure ast_strlen_zero(const char *s)
Definition: strings.h:63
int ast_get_timeval ( const char *  src,
struct timeval *  dst,
struct timeval  _default,
int *  consumed 
)

get values from config variables.

Definition at line 2091 of file utils.c.

References ast_strlen_zero().

Referenced by acf_strftime().

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 }
static force_inline int attribute_pure ast_strlen_zero(const char *s)
Definition: strings.h:63
struct hostent* ast_gethostbyname ( const char *  host,
struct ast_hostent hp 
)

Re-entrant (thread safe) version of gethostbyname that replaces the standard gethostbyname (which is not thread safe)

Thread-safe gethostbyname function to use in Asterisk.

Definition at line 195 of file utils.c.

References ast_hostent::buf, and ast_hostent::hp.

Referenced by __ast_http_load(), app_exec(), ast_parse_arg(), build_peer(), config_load(), config_parse_variables(), create_addr(), festival_exec(), gtalk_load_config(), gtalk_update_stun(), iax_template_parse(), jingle_load_config(), jingle_update_stun(), launch_netscript(), process_sdp(), realtime_peer(), realtime_user(), reload_config(), and set_config().

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 }
char buf[1024]
Definition: utils.h:212
struct hostent hp
Definition: utils.h:211
const char* ast_inet_ntoa ( struct in_addr  ia)

ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa

thread-safe replacement for inet_ntoa().

Definition at line 564 of file utils.c.

References ast_threadstorage_get(), and inet_ntoa_buf.

Referenced by __attempt_transmit(), __find_callno(), __iax2_show_peers(), _skinny_show_device(), _skinny_show_devices(), acf_channel_read(), action_login(), add_ipv4_ie(), add_sdp(), ast_apply_ha(), ast_netsock_bindaddr(), ast_parse_arg(), auth_http_callback(), authenticate(), calltoken_required(), check_access(), config_load(), create_client(), data_get_xml_add_child(), data_result_manager_output(), data_result_print_cli_node(), do_message(), dump_addr(), dump_ipaddr(), dundi_rexmit(), dundi_show_peer(), dundi_show_peers(), dundi_show_trans(), dundi_showframe(), dundi_xmit(), external_rtp_create(), find_command(), find_peer(), find_subchannel_and_lock(), find_tpeer(), function_iaxpeer(), generic_http_callback(), get_input(), gtalk_update_externip(), gtalk_update_stun(), handle_call_token(), handle_cli_iax2_set_debug(), handle_cli_iax2_show_callno_limits(), handle_cli_iax2_show_channels(), handle_cli_iax2_show_peer(), handle_cli_iax2_show_registry(), handle_command_response(), handle_error(), handle_mgcp_show_endpoints(), handle_open_receive_channel_ack_message(), handle_request(), handle_show_http(), handle_showmanconn(), handle_skinny_show_settings(), iax2_ack_registry(), iax2_prov_app(), iax2_trunk_queue(), iax_server(), iax_showframe(), jingle_create_candidates(), load_module(), manager_iax2_show_peer_list(), manager_iax2_show_registry(), mgcpsock_read(), oh323_addrcmp_str(), oh323_call(), oh323_set_rtp_peer(), parsing(), peercnt_add(), peercnt_modify(), peercnt_remove(), peers_data_provider_get(), process_request(), process_sdp(), purge_sessions(), raw_hangup(), realtime_peer(), realtime_user(), register_verify(), registry_rerequest(), reload_config(), resend_response(), sched_delay_remove(), score_address(), send_packet(), send_raw_client(), send_request(), send_response(), send_trunk(), session_do(), set_config(), set_peercnt_limit(), setup_incoming_call(), show_main_page(), skinny_session(), skinny_set_rtp_peer(), socket_process(), socket_process_meta(), start_rtp(), stun_monitor_request(), timing_read(), unistim_info(), unistimsock_read(), and update_registry().

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 }
void * ast_threadstorage_get(struct ast_threadstorage *ts, size_t init_size)
Retrieve thread storage.
static struct ast_threadstorage inet_ntoa_buf
Definition: utils.c:81
void ast_join ( char *  s,
size_t  len,
const char *const  w[] 
)

Definition at line 1690 of file utils.c.

References len().

Referenced by __ast_cli_generator(), ast_agi_register(), ast_agi_unregister(), ast_cli_command_full(), cli_console_sendtext(), console_sendtext(), find_best(), handle_cli_agi_show(), handle_cli_check_permissions(), handle_help(), help1(), help_workhorse(), set_full_cmd(), and write_htmldump().

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 }
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
void ast_md5_hash ( char *  output,
const char *  input 
)

Produce 32 char MD5 hash of value.

Produces MD5 hash based on input string.

Definition at line 245 of file utils.c.

References MD5Final(), MD5Init(), and MD5Update().

Referenced by __init_manager(), auth_exec(), auth_http_callback(), build_reply_digest(), check_auth(), and md5().

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 }
void MD5Final(unsigned char digest[16], struct MD5Context *context)
Definition: md5.c:122
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1575
void MD5Init(struct MD5Context *context)
Definition: md5.c:59
void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len)
Definition: md5.c:74
static int md5(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: func_md5.c:54
Definition: md5.h:26
int ast_mkdir ( const char *  path,
int  mode 
)

Recursively create directory path.

Parameters
pathThe directory path to create
modeThe permissions with which to try to create the directory
Returns
0 on success or an error code otherwise

Creates a directory path, creating parent directories as needed.

Definition at line 2151 of file utils.c.

References ast_alloca, ast_strdupa, errno, and len().

Referenced by ast_monitor_change_fname(), ast_monitor_start(), conf_run(), create_dirpath(), dictate_exec(), filename_parse(), init_logger(), load_module(), mixmonitor_exec(), record_exec(), reload_logger(), remove_from_queue(), setup_privacy_args(), sms_nextoutgoing(), sms_writefile(), testclient_exec(), testserver_exec(), and write_history().

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 }
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition: utils.h:653
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition: utils.h:663
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
int errno
int ast_parse_digest ( const char *  digest,
struct ast_http_digest d,
int  request,
int  pedantic 
)

Parse digest authorization header.

Returns
Returns -1 if we have no auth or something wrong with digest.
Note
This function may be used for Digest request and responce header. request arg is set to nonzero, if we parse Digest Request. pedantic arg can be set to nonzero if we need to do addition Digest check.

Definition at line 2216 of file utils.c.

References ast_free, ast_log(), ast_skip_blanks(), ast_str_buffer(), ast_str_create(), ast_str_set(), ast_string_field_ptr_set, ast_string_field_set, ast_strlen_zero(), ast_unescape_c(), ast_http_digest::cnonce, ast_http_digest::domain, LOG_WARNING, ast_http_digest::nc, ast_http_digest::nonce, ast_http_digest::opaque, ast_http_digest::qop, ast_http_digest::realm, ast_http_digest::response, strsep(), ast_http_digest::uri, and ast_http_digest::username.

Referenced by auth_http_callback().

2216  {
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 }
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
char * strsep(char **str, const char *delims)
#define LOG_WARNING
Definition: logger.h:144
char * ast_str_buffer(const struct ast_str *buf)
Returns the string buffer within the ast_str buf.
Definition: strings.h:497
const ast_string_field opaque
Definition: utils.h:714
const ast_string_field domain
Definition: utils.h:714
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
const ast_string_field username
Definition: utils.h:714
const char * str
Definition: app_jack.c:144
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
const ast_string_field uri
Definition: utils.h:714
const ast_string_field response
Definition: utils.h:714
static force_inline int attribute_pure ast_strlen_zero(const char *s)
Definition: strings.h:63
The descriptor of a dynamic string XXX storage will be optimized later if needed We use the ts field ...
Definition: strings.h:364
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 ast_free(a)
Definition: astmm.h:97
const ast_string_field realm
Definition: utils.h:714
const ast_string_field nonce
Definition: utils.h:714
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
char* ast_process_quotes_and_slashes ( char *  start,
char  find,
char  replace_with 
)

Process a string to find and replace characters.

Parameters
startThe string to analyze
findThe character to find
replace_withThe character that will replace the one we are looking for

Definition at line 1664 of file utils.c.

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 }
int ast_pthread_create_detached_stack ( pthread_t *  thread,
pthread_attr_t *  attr,
void *(*)(void *)  start_routine,
void *  data,
size_t  stacksize,
const char *  file,
const char *  caller,
int  line,
const char *  start_fn 
)

Definition at line 1230 of file utils.c.

References ast_alloca, ast_log(), ast_pthread_create_stack(), errno, LOG_WARNING, and thr_arg::start_routine.

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 }
pthread_t thread
Definition: app_meetme.c:962
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition: utils.h:653
#define LOG_WARNING
Definition: logger.h:144
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
int errno
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
int ast_pthread_create_stack ( pthread_t *  thread,
pthread_attr_t *  attr,
void *(*)(void *)  start_routine,
void *  data,
size_t  stacksize,
const char *  file,
const char *  caller,
int  line,
const char *  start_fn 
)

Definition at line 1182 of file utils.c.

References ast_alloca, ast_asprintf, ast_log(), ast_malloc, AST_STACKSIZE, thr_arg::data, dummy_start(), errno, LOG_WARNING, thr_arg::name, pthread_create, and thr_arg::start_routine.

Referenced by ast_pthread_create_detached_stack().

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 }
pthread_t thread
Definition: app_meetme.c:962
#define AST_STACKSIZE
Definition: utils.h:399
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition: utils.h:653
#define LOG_WARNING
Definition: logger.h:144
void *(* start_routine)(void *)
Definition: utils.c:1128
#define ast_asprintf(a, b, c...)
Definition: astmm.h:121
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
int errno
#define pthread_create
Definition: lock.h:573
static void * dummy_start(void *data)
Definition: utils.c:1140
void * data
Definition: utils.c:1129
char * name
Definition: utils.c:1130
#define ast_malloc(a)
Definition: astmm.h:91
long int ast_random ( void  )

Definition at line 1640 of file utils.c.

References ast_mutex_lock, ast_mutex_unlock, and randomlock.

Referenced by acf_rand_exec(), action_challenge(), add_sdp(), agent_new(), agi_handle_command(), ast_lock_path_lockfile(), ast_moh_files_next(), ast_rtp_change_source(), ast_rtp_new(), ast_udptl_new_with_bindaddr(), auth_http_callback(), authenticate_request(), build_gateway(), build_iv(), build_localtag_registry(), build_rand_pad(), build_reply_digest(), calc_metric(), calc_rxstamp(), caldav_write_event(), callno_hash(), create_channel_name(), generate_exchange_uuid(), generate_random_string(), generic_http_callback(), get_trans_id(), gtalk_alloc(), gtalk_create_candidates(), gtalk_new(), handle_incoming(), handle_response_invite(), iax2_key_rotate(), iax2_start_transfer(), jingle_alloc(), jingle_create_candidates(), jingle_new(), load_module(), make_email_file(), make_our_tag(), moh_files_alloc(), multicast_rtp_new(), ogg_vorbis_rewrite(), osp_create_uuid(), page_exec(), park_space_reserve(), process_weights(), reg_source_db(), registry_authrequest(), reqprep(), say_periodic_announcement(), sendmail(), set_nonce_randdata(), sip_alloc(), socket_read(), start_rtp(), stun_req_id(), transmit_invite(), transmit_register(), transmit_response_using_temp(), try_calling(), and try_firmware().

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 }
#define ast_mutex_lock(a)
Definition: lock.h:155
static int dev_urandom_fd
Definition: utils.c:575
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
#define ast_mutex_unlock(a)
Definition: lock.h:156
int ast_remaining_ms ( struct timeval  start,
int  max_ms 
)

Calculate remaining milliseconds given a starting timestamp and upper bound.

If the upper bound is negative, then this indicates that there is no upper bound on the amount of time to wait. This will result in a negative return.

Parameters
startWhen timing started being calculated
max_msThe maximum number of milliseconds to wait from start. May be negative.
Returns
The number of milliseconds left to wait for. May be negative.

Definition at line 1615 of file utils.c.

References ast_tvdiff_ms(), and ast_tvnow().

Referenced by __analog_ss_thread(), __ast_answer(), __ast_request_and_dial(), agent_ack_sleep(), analog_ss_thread(), ast_recvtext(), ast_safe_sleep_conditional(), ast_waitfordigit_full(), async_wait(), dahdi_bridge(), disable_t38(), do_idle_thread(), find_cache(), generic_fax_exec(), local_bridge_loop(), receivefax_t38_init(), record_exec(), remote_bridge_loop(), sendfax_t38_init(), tcptls_stream_read(), tcptls_stream_write(), wait_for_answer(), and waitforring_exec().

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 }
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:142
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
void ast_sha1_hash ( char *  output,
const char *  input 
)

Produce 40 char SHA1 hash of value.

Produces SHA1 hash based on input string.

Definition at line 261 of file utils.c.

References SHA1Input(), SHA1Reset(), and SHA1Result().

Referenced by aji_act_hook(), handle_call_token(), jabber_make_auth(), and sha1().

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 }
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1575
int SHA1Result(SHA1Context *, uint8_t Message_Digest[SHA1HashSize])
Definition: sha1.c:226
int SHA1Reset(SHA1Context *)
SHA1Reset.
Definition: sha1.c:101
int SHA1Input(SHA1Context *, const uint8_t *bytes, unsigned int bytecount)
char* ast_strip_quoted ( char *  s,
const char *  beg_quotes,
const char *  end_quotes 
)

Strip leading/trailing whitespace and quotes from a string.

Parameters
sThe string to be stripped (will be modified).
beg_quotesThe list of possible beginning quote characters.
end_quotesThe list of matching ending quote characters.
Returns
The stripped string.

This functions strips all leading and trailing whitespace characters from the input string, and returns a pointer to the resulting string. The string is modified in place.

It can also remove beginning and ending quote (or quote-like) characters, in matching pairs. If the first character of the string matches any character in beg_quotes, and the last character of the string is the matching character in end_quotes, then they are removed from the string.

Examples:

ast_strip_quoted(buf, "\"", "\"");
ast_strip_quoted(buf, "'", "'");
ast_strip_quoted(buf, "[{(", "]})");

Definition at line 1431 of file utils.c.

References ast_strip().

Referenced by ast_callerid_parse(), ast_register_file_version(), get_rdnis(), iftime(), load_values_config(), parse_allowed_methods(), parse_cookies(), parse_dial_string(), and sip_parse_register_line().

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 }
char * ast_strip(char *s)
Strip leading/trailing whitespace from a string.
Definition: strings.h:155
int ast_true ( const char *  val)

Make sure something is true. Determine if a string containing a boolean value is "true". This function checks to see whether a string passed to it is an indication of an "true" value. It checks to see if the string is "yes", "true", "y", "t", "on" or "1".

Return values
0if val is a NULL pointer.
-1if "true".
0otherwise.

Definition at line 1533 of file utils.c.

References ast_strlen_zero().

Referenced by __ast_http_load(), __ast_udptl_reload(), __init_manager(), _parse(), acf_curlopt_write(), acf_faxopt_write(), acf_transaction_write(), action_agent_logoff(), action_bridge(), action_originate(), action_updateconfig(), actual_load_config(), aji_create_client(), aji_load_config(), aoc_cli_debug_enable(), apply_general_options(), apply_option(), apply_outgoing(), ast_bridge_timelimit(), ast_jb_read_conf(), ast_plc_reload(), ast_readconfig(), ast_tls_read_conf(), autopause2int(), build_device(), build_gateway(), build_peer(), build_user(), config_parse_variables(), dahdi_accept_r2_call_exec(), dahdi_r2_answer(), dahdi_set_dnd(), data_search_cmp_bool(), do_reload(), festival_exec(), func_channel_write_real(), func_inheritance_write(), func_mute_write(), get_encrypt_methods(), gtalk_load_config(), handle_common_options(), handle_logger_set_level(), handle_mfcr2_call_files(), handle_t38_options(), init_logger_chain(), jingle_load_config(), load_config(), load_config_meetme(), load_module(), load_modules(), load_moh_classes(), load_odbc_config(), local_ast_moh_start(), login_exec(), manager_add_queue_member(), manager_mutestream(), manager_pause_queue_member(), message_template_build(), misdn_answer(), odbc_load_module(), osp_load(), osplookup_exec(), parkinglot_config_read(), parse_config(), parse_empty_options(), pbx_load_config(), pbx_load_users(), process_config(), process_dahdi(), process_echocancel(), queue_set_global_params(), queue_set_param(), read_agent_config(), realtime_directory(), reload_config(), rtp_reload(), run_startup_commands(), search_directory(), search_directory_sub(), set_active(), set_config(), sla_load_config(), smdi_load(), speex_write(), stackpeek_read(), start_monitor_action(), strings_to_mask(), tds_load_module(), update_common_options(), xmldoc_get_syntax_cmd(), xmldoc_get_syntax_fun(), and xmldoc_get_syntax_manager().

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 }
static force_inline int attribute_pure ast_strlen_zero(const char *s)
Definition: strings.h:63
struct timeval ast_tvadd ( struct timeval  a,
struct timeval  b 
)

Returns the sum of two timevals a + b.

Definition at line 1587 of file utils.c.

References ONE_MILLION, and tvfix().

Referenced by __get_from_jb(), acf_jabberreceive_read(), agent_hangup(), ast_audiohook_trigger_wait(), ast_channel_bridge(), ast_channel_cmpwhentohangup_tv(), ast_channel_setwhentohangup_tv(), ast_generic_bridge(), ast_poll2(), ast_rtp_dtmf_begin(), ast_rtp_dtmf_end_with_duration(), ast_rtp_sendcng(), ast_sched_runq(), ast_smoother_read(), ast_translate(), calc_rxstamp(), calc_timestamp(), cli_tps_ping(), conf_run(), dial_exec_full(), do_cdr(), do_timing(), iax2_process_thread(), jb_get_and_deliver(), mb_poll_thread(), monmp3thread(), mp3_exec(), mwi_monitor_handler(), NBScat_exec(), sched_run(), sched_settime(), schedule_delivery(), sla_process_timers(), smdi_message_wait(), and timeout_write().

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 }
#define ONE_MILLION
Definition: utils.c:1567
static struct timeval tvfix(struct timeval a)
Definition: utils.c:1572
struct timeval ast_tvsub ( struct timeval  a,
struct timeval  b 
)

Returns the difference of two timevals a - b.

Definition at line 1601 of file utils.c.

References ONE_MILLION, and tvfix().

Referenced by ast_channel_bridge(), ast_poll2(), ast_sched_dump(), ast_translate(), ast_waitfor_nandfds(), calc_rxstamp(), calc_timestamp(), cli_tps_ping(), conf_run(), debug_check_frame_for_silence(), handle_showcalls(), handle_showuptime(), and pri_dchannel().

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 }
#define ONE_MILLION
Definition: utils.c:1567
static struct timeval tvfix(struct timeval a)
Definition: utils.c:1572
char* ast_unescape_c ( char *  s)

Convert some C escape sequences.

(\b\f\n\r\t) 

into the equivalent characters. The string to be converted (will be modified).

Returns
The converted string.

Definition at line 1467 of file utils.c.

Referenced by ast_parse_digest().

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 }
void ast_unescape_quoted ( char *  quote_str)

Unescape quotes in a string.

Parameters
quote_strThe string with quotes to be unescaped
Note
This function mutates the passed-in string.

Definition at line 461 of file utils.c.

Referenced by ast_callerid_parse().

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 }
char* ast_unescape_semicolon ( char *  s)

Strip backslash for "escaped" semicolons, the string to be stripped (will be modified).

Returns
The stripped string.

Definition at line 1448 of file utils.c.

Referenced by sip_cli_notify().

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 }
void ast_uri_decode ( char *  s)

ast_uri_decode: Decode SIP URI, URN, URL (overwrite the string)

Decode URI, URN, URL (overwrite string)

Definition at line 484 of file utils.c.

Referenced by acf_curl_helper(), config_curl(), get_destination(), get_name_and_number(), get_refer_info(), handle_request_invite(), http_decode(), parse_moved_contact(), realtime_curl(), realtime_multi_curl(), sip_new(), sip_uri_cmp(), and uridecode().

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 }
char* ast_uri_encode ( const char *  string,
char *  outbuf,
int  buflen,
int  do_special_char 
)

Turn text string to URI-encoded XX version.

Note
At this point, this function is encoding agnostic; it does not check whether it is fed legal UTF-8. We escape control characters (-), '', and all characters above 0x7F. If do_special_char == 1 we will convert all characters except alnum and mark. Outbuf needs to have more memory allocated than the instring to have room for the expansion. Every char that is converted is replaced by three ASCII characters.

Definition at line 398 of file utils.c.

References string.

Referenced by add_rpid(), build_contact(), config_curl(), destroy_curl(), initreqprep(), launch_asyncagi(), realtime_curl(), realtime_multi_curl(), require_curl(), store_curl(), update2_curl(), update_curl(), and uriencode().

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 }
char string[1]
Definition: utils.c:1722
int ast_utils_init ( void  )

Definition at line 2193 of file utils.c.

References ARRAY_LEN, ast_cli_register_multiple(), ast_register_atexit(), and base64_init().

Referenced by main().

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 }
#define ARRAY_LEN(a)
Definition: isdn_lib.c:42
int ast_register_atexit(void(*func)(void))
Register a function to be executed before Asterisk exits.
Definition: asterisk.c:998
static int dev_urandom_fd
Definition: utils.c:575
static void base64_init(void)
Definition: utils.c:362
int ast_cli_register_multiple(struct ast_cli_entry *e, int len)
Register multiple commands.
Definition: cli.c:2167
char* ast_utils_which ( const char *  binary,
char *  fullpath,
size_t  fullpath_size 
)

Resolve a binary to a full pathname.

Parameters
binaryName of the executable to resolve
fullpathBuffer to hold the complete pathname
fullpath_sizeSize of fullpath
Return values
NULLbinary was not found or the environment variable PATH is not set
Returns
fullpath

Definition at line 2364 of file utils.c.

References ast_strdupa, and strsep().

Referenced by ast_bt_get_symbols().

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 }
char * strsep(char **str, const char *delims)
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition: utils.h:663
int ast_wait_for_input ( int  fd,
int  ms 
)

Definition at line 1255 of file utils.c.

References ast_poll.

Referenced by action_waitevent(), ast_tcptls_server_root(), dahdi_test_timer(), get_input(), moh_class_destructor(), sip_tcptls_read(), tcptls_stream_read(), and tcptls_stream_write().

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 }
#define ast_poll(a, b, c)
Definition: poll-compat.h:88
int ast_wait_for_output ( int  fd,
int  ms 
)

Definition at line 1265 of file utils.c.

References ast_poll.

Referenced by tcptls_stream_read(), and tcptls_stream_write().

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 }
#define ast_poll(a, b, c)
Definition: poll-compat.h:88
int ast_xml_escape ( const char *  string,
char *  outbuf,
size_t  buflen 
)

Escape reserved characters for use in XML.

ast_xml_escape If outbuf is too short, the output string will be truncated. Regardless, the output will always be null terminated.

Parameters
stringString to be converted
outbufResulting encoded string
buflenSize of output buffer
Returns
0 for success
-1 if buflen is too short.

Definition at line 500 of file utils.c.

References ast_assert, entity, len(), and string.

Referenced by state_notify_build_xml().

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 }
static int entity
Definition: isdn_lib.c:259
#define ast_assert(a)
Definition: utils.h:738
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
char string[1]
Definition: utils.c:1722
static void base64_init ( void  )
static

Definition at line 362 of file utils.c.

Referenced by ast_utils_init().

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 }
static char b2a[256]
Definition: utils.c:79
static char base64[64]
Definition: utils.c:78
static void* dummy_start ( void *  data)
static

Definition at line 1140 of file utils.c.

References ast_free, AST_LIST_INSERT_TAIL, AST_MUTEX_KIND, ast_register_thread(), ast_threadstorage_get(), ast_unregister_thread(), thr_arg::data, lock_info, thr_arg::name, pthread_mutex_init, pthread_mutex_lock, pthread_mutex_unlock, thr_arg::start_routine, and strdup.

Referenced by ast_pthread_create_stack().

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 }
#define pthread_mutex_init
Definition: lock.h:559
void ast_register_thread(char *name)
Definition: asterisk.c:401
void * ast_threadstorage_get(struct ast_threadstorage *ts, size_t init_size)
Retrieve thread storage.
void *(* start_routine)(void *)
Definition: utils.c:1128
void ast_unregister_thread(void *id)
Definition: asterisk.c:416
#define pthread_mutex_lock
Definition: lock.h:556
#define AST_LIST_INSERT_TAIL(head, elm, field)
Appends a list entry to the tail of a list.
Definition: linkedlists.h:716
#define ast_free(a)
Definition: astmm.h:97
void * data
Definition: utils.c:1129
static struct ast_datastore_info lock_info
Definition: func_lock.c:117
char * name
Definition: utils.c:1130
#define pthread_mutex_unlock
Definition: lock.h:557
#define strdup(a)
Definition: astmm.h:106
#define AST_MUTEX_KIND
Definition: lock.h:76
static size_t optimal_alloc_size ( size_t  size)
static

Definition at line 1729 of file utils.c.

References ALLOCATOR_OVERHEAD.

Referenced by __ast_calloc_with_stringfields(), and add_string_pool().

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 }
#define ALLOCATOR_OVERHEAD
Definition: utils.c:1727
static struct timeval tvfix ( struct timeval  a)
static

Definition at line 1572 of file utils.c.

References ast_log(), LOG_WARNING, and ONE_MILLION.

Referenced by ast_tvadd(), and ast_tvsub().

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 }
#define LOG_WARNING
Definition: logger.h:144
#define ONE_MILLION
Definition: utils.c:1567
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
static int wait_for_output ( int  fd,
int  timeoutms 
)
static

Definition at line 1275 of file utils.c.

References ast_debug, ast_log(), ast_poll, ast_tvdiff_ms(), ast_tvnow(), errno, and LOG_ERROR.

Referenced by ast_careful_fwrite(), and ast_carefulwrite().

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 }
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:142
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 ast_debug(level,...)
Log a DEBUG message.
Definition: logger.h:236
#define ast_poll(a, b, c)
Definition: poll-compat.h:88
#define LOG_ERROR
Definition: logger.h:155
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
int errno

Variable Documentation

struct { ... } __ast_string_field_empty_buffer

Definition at line 1721 of file utils.c.

Referenced by __ast_calloc_with_stringfields().

char b2a[256]
static

Definition at line 79 of file utils.c.

char base64[64]
static

Definition at line 78 of file utils.c.

Referenced by aji_start_sasl().

int dev_urandom_fd
static

Definition at line 575 of file utils.c.

ast_mutex_t fetchadd_m = { PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP , NULL, 1 }
static

Definition at line 2076 of file utils.c.

Referenced by ast_atomic_fetchadd_int_slow().

struct ast_threadstorage inet_ntoa_buf = { .once = PTHREAD_ONCE_INIT , .key_init = __init_inet_ntoa_buf , .custom_init = NULL , }
static

Definition at line 81 of file utils.c.

Referenced by ast_inet_ntoa().

ast_mutex_t randomlock = { PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP , NULL, 1 }
static

glibc puts a lock inside random(3), so that the results are thread-safe. BSD libc (and others) do not.

Definition at line 1637 of file utils.c.

Referenced by ast_random().

char string[1]

Definition at line 1722 of file utils.c.

Referenced by ast_escape_quoted(), ast_uri_encode(), ast_xml_escape(), nword(), and private_enum_init().