main/utils.c File Reference

Utility functions. More...

#include "asterisk.h"
#include <ctype.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.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/astobj2.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"

Include dependency graph for main/utils.c:

Go to the source code of this file.

Data Structures

struct  thr_arg

Defines

#define ALLOCATOR_OVERHEAD   48
#define AST_API_MODULE
#define AST_API_MODULE
#define AST_API_MODULE
#define AST_API_MODULE
#define AST_API_MODULE
#define AST_API_MODULE
#define AST_API_MODULE
#define ERANGE   34
#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 ap)
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.
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
int ast_base64encode (char *dst, const unsigned char *src, int srclen, int max)
 Encode data in base64.
int ast_base64encode_full (char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
 encode text to BASE64 coding
int ast_build_string (char **buffer, size_t *space, const char *fmt,...)
 Build a string in a buffer, designed to be called repeatedly.
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.
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.
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.
void ast_do_crash (void)
 Force a crash if DO_CRASH is defined.
int ast_eid_cmp (const struct ast_eid *eid1, const struct ast_eid *eid2)
 Compare two EIDs.
char * ast_eid_to_str (char *s, int maxlen, struct ast_eid *eid)
 Convert an EID to a string.
void ast_enable_packet_fragmentation (int sock)
 Disable PMTU discovery on a socket.
char * ast_escape_quoted (const char *string, char *outbuf, int buflen)
 Escape characters found in a quoted string.
char * ast_escape_semicolons (const char *string, char *outbuf, int buflen)
 Escape semicolons found in a string.
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".
void ast_format_duration_hh_mm_ss (int duration, char *buf, size_t length)
 Formats a duration into HH:MM:SS.
int ast_get_tid (void)
 Get current thread ID.
int ast_get_time_t (const char *src, time_t *dst, time_t _default, int *consumed)
 get values from config variables.
int ast_get_timeval (const char *src, struct timeval *dst, struct timeval _default, int *consumed)
 get values from config variables.
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).
const char * ast_inet_ntoa (struct in_addr ia)
 ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa
void ast_join_delim (char *s, size_t len, const char *const w[], unsigned int size, char delim)
void ast_md5_hash (char *output, const char *input)
 Produce 32 char MD5 hash of value.
int ast_mkdir (const char *path, int mode)
 Recursively create directory path.
int ast_parse_digest (const char *digest, struct ast_http_digest *d, int request, int pedantic)
 Parse digest authorization header.
char * ast_process_quotes_and_slashes (char *start, char find, char replace_with)
 Process a string to find and replace characters.
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_regex_string_to_regex_pattern (const char *regex_string, struct ast_str **regex_pattern)
 Given a string regex_string in the form of "/regex/", convert it into the form of "regex".
int ast_remaining_ms (struct timeval start, int max_ms)
 Calculate remaining milliseconds given a starting timestamp and upper bound.
void ast_replace_subargument_delimiter (char *s)
 Replace '^' in a string with ','.
int ast_safe_mkdir (const char *base_path, const char *path, int mode)
 Recursively create directory path, but only if it resolves within the given base_path.
void ast_set_default_eid (struct ast_eid *eid)
 Fill in an ast_eid with the default eid of this machine.
void ast_sha1_hash (char *output, const char *input)
 Produce 40 char SHA1 hash of value.
void ast_sha1_hash_uint (uint8_t *digest, const char *input)
 Produce a 20 byte SHA1 hash of value.
int ast_str_to_eid (struct ast_eid *eid, const char *s)
 Convert a string into an EID.
char * ast_strip_quoted (char *s, const char *beg_quotes, const char *end_quotes)
 Strip leading/trailing whitespace and quotes from a string.
char * ast_strsep (char **iss, const char sep, uint32_t flags)
 Act like strsep but ignore separators inside quotes.
char * ast_to_camel_case_delim (const char *s, const char *delim)
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".
struct timeval ast_tvadd (struct timeval a, struct timeval b)
 Returns the sum of two timevals a + b.
struct timeval ast_tvsub (struct timeval a, struct timeval b)
 Returns the difference of two timevals a - b.
char * ast_unescape_c (char *src)
 Convert some C escape sequences.
void ast_unescape_quoted (char *quote_str)
 Unescape quotes in a string.
char * ast_unescape_semicolon (char *s)
 Strip backslash for "escaped" semicolons, the string to be stripped (will be modified).
void ast_uri_decode (char *s, struct ast_flags spec)
 Decode URI, URN, URL (overwrite string).
char * ast_uri_encode (const char *string, char *outbuf, int buflen, struct ast_flags spec)
 Turn text string to URI-encoded XX version.
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.
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.
static void base64_init (void)
static void * dummy_start (void *data)
static int gethostbyname_r (const char *name, struct hostent *ret, char *buf, size_t buflen, struct hostent **result, int *h_errnop)
 Reentrant replacement for gethostbyname for BSD-based systems.
static size_t optimal_alloc_size (size_t size)
static int safe_mkdir (const char *base_path, char *path, int mode)
static struct timeval tvfix (struct timeval a)
static void utils_shutdown (void)
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 ast_mutex_t __mutex = { PTHREAD_MUTEX_INITIALIZER , NULL, 1 }
struct ast_flags ast_uri_http = {AST_URI_UNRESERVED}
struct ast_flags ast_uri_http_legacy = {AST_URI_LEGACY_SPACE | AST_URI_UNRESERVED}
struct ast_flags ast_uri_sip_user = {AST_URI_UNRESERVED | AST_URI_SIP_USER_UNRESERVED}
static char b2a [256]
static char base64 [64]
static int dev_urandom_fd = -1
static ast_mutex_t fetchadd_m = { PTHREAD_MUTEX_INITIALIZER , 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_MUTEX_INITIALIZER , NULL, 1 }


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 main/utils.c.


Define Documentation

#define ALLOCATOR_OVERHEAD   48

Definition at line 1907 of file main/utils.c.

Referenced by optimal_alloc_size().

#define AST_API_MODULE

Definition at line 72 of file main/utils.c.

#define AST_API_MODULE

Definition at line 72 of file main/utils.c.

#define AST_API_MODULE

Definition at line 72 of file main/utils.c.

#define AST_API_MODULE

Definition at line 72 of file main/utils.c.

#define AST_API_MODULE

Definition at line 72 of file main/utils.c.

#define AST_API_MODULE

Definition at line 72 of file main/utils.c.

#define AST_API_MODULE

Definition at line 72 of file main/utils.c.

#define ERANGE   34

duh? ERANGE value copied from web...

Definition at line 82 of file main/utils.c.

Referenced by ast_parse_arg(), gethostbyname_r(), and reload_queue_members().

#define ONE_MILLION   1000000

Definition at line 1706 of file main/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 2207 of file main/utils.c.

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

02210 {
02211    struct ast_string_field_mgr *mgr;
02212    struct ast_string_field_pool *pool;
02213    struct ast_string_field_pool **pool_head;
02214    size_t pool_size_needed = sizeof(*pool) + pool_size;
02215    size_t size_to_alloc = optimal_alloc_size(struct_size + pool_size_needed);
02216    void *allocation;
02217    unsigned int x;
02218 
02219 #if defined(__AST_DEBUG_MALLOC)
02220    if (!(allocation = __ast_calloc(num_structs, size_to_alloc, file, lineno, func))) {
02221       return NULL;
02222    }
02223 #else
02224    if (!(allocation = ast_calloc(num_structs, size_to_alloc))) {
02225       return NULL;
02226    }
02227 #endif
02228 
02229    for (x = 0; x < num_structs; x++) {
02230       void *base = allocation + (size_to_alloc * x);
02231       const char **p;
02232 
02233       mgr = base + field_mgr_offset;
02234       pool_head = base + field_mgr_pool_offset;
02235       pool = base + struct_size;
02236 
02237       p = (const char **) pool_head + 1;
02238       while ((struct ast_string_field_mgr *) p != mgr) {
02239          *p++ = __ast_string_field_empty;
02240       }
02241 
02242       mgr->embedded_pool = pool;
02243       *pool_head = pool;
02244       pool->size = size_to_alloc - struct_size - sizeof(*pool);
02245 #if defined(__AST_DEBUG_MALLOC)
02246       mgr->owner_file = file;
02247       mgr->owner_func = func;
02248       mgr->owner_line = lineno;
02249 #endif
02250    }
02251 
02252    return allocation;
02253 }

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 2027 of file main/utils.c.

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

Referenced by __ast_string_field_ptr_build_va().

02029 {
02030    char *result = NULL;
02031    size_t space = (*pool_head)->size - (*pool_head)->used;
02032    size_t to_alloc;
02033 
02034    /* Make room for ast_string_field_allocation and make it a multiple of that. */
02035    to_alloc = ast_make_room_for(needed, ast_string_field_allocation);
02036    ast_assert(to_alloc % ast_alignof(ast_string_field_allocation) == 0);
02037 
02038    if (__builtin_expect(to_alloc > space, 0)) {
02039       size_t new_size = (*pool_head)->size;
02040 
02041       while (new_size < to_alloc) {
02042          new_size *= 2;
02043       }
02044 
02045 #if defined(__AST_DEBUG_MALLOC)
02046       if (add_string_pool(mgr, pool_head, new_size, mgr->owner_file, mgr->owner_line, mgr->owner_func))
02047          return NULL;
02048 #else
02049       if (add_string_pool(mgr, pool_head, new_size, __FILE__, __LINE__, __FUNCTION__))
02050          return NULL;
02051 #endif
02052    }
02053 
02054    /* pool->base is always aligned (gcc aligned attribute). We ensure that
02055     * to_alloc is also a multiple of ast_alignof(ast_string_field_allocation)
02056     * causing result to always be aligned as well; which in turn fixes that
02057     * AST_STRING_FIELD_ALLOCATION(result) is aligned. */
02058    result = (*pool_head)->base + (*pool_head)->used;
02059    (*pool_head)->used += to_alloc;
02060    (*pool_head)->active += needed;
02061    result += ast_alignof(ast_string_field_allocation);
02062    AST_STRING_FIELD_ALLOCATION(result) = needed;
02063    mgr->last_alloc = result;
02064 
02065    return result;
02066 }

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 1960 of file main/utils.c.

References 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, NULL, ast_string_field_pool::prev, and ast_string_field_pool::used.

01962 {
01963    const char **p = (const char **) pool_head + 1;
01964    struct ast_string_field_pool *cur = NULL;
01965    struct ast_string_field_pool *preserve = NULL;
01966 
01967    /* clear fields - this is always necessary */
01968    while ((struct ast_string_field_mgr *) p != mgr) {
01969       *p++ = __ast_string_field_empty;
01970    }
01971 
01972    mgr->last_alloc = NULL;
01973 #if defined(__AST_DEBUG_MALLOC)
01974    mgr->owner_file = file;
01975    mgr->owner_func = func;
01976    mgr->owner_line = lineno;
01977 #endif
01978    if (needed > 0) {    /* allocate the initial pool */
01979       *pool_head = NULL;
01980       mgr->embedded_pool = NULL;
01981       return add_string_pool(mgr, pool_head, needed, file, lineno, func);
01982    }
01983 
01984    /* if there is an embedded pool, we can't actually release *all*
01985     * pools, we must keep the embedded one. if the caller is about
01986     * to free the structure that contains the stringfield manager
01987     * and embedded pool anyway, it will be freed as part of that
01988     * operation.
01989     */
01990    if ((needed < 0) && mgr->embedded_pool) {
01991       needed = 0;
01992    }
01993 
01994    if (needed < 0) {    /* reset all pools */
01995       cur = *pool_head;
01996    } else if (mgr->embedded_pool) { /* preserve the embedded pool */
01997       preserve = mgr->embedded_pool;
01998       cur = *pool_head;
01999    } else {       /* preserve the last pool */
02000       if (*pool_head == NULL) {
02001          ast_log(LOG_WARNING, "trying to reset empty pool\n");
02002          return -1;
02003       }
02004       preserve = *pool_head;
02005       cur = preserve->prev;
02006    }
02007 
02008    if (preserve) {
02009       preserve->prev = NULL;
02010       preserve->used = preserve->active = 0;
02011    }
02012 
02013    while (cur) {
02014       struct ast_string_field_pool *prev = cur->prev;
02015 
02016       if (cur != preserve) {
02017          ast_free(cur);
02018       }
02019       cur = prev;
02020    }
02021 
02022    *pool_head = preserve;
02023 
02024    return 0;
02025 }

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 2196 of file main/utils.c.

References __ast_string_field_ptr_build_va().

02199 {
02200    va_list ap;
02201 
02202    va_start(ap, format);
02203    __ast_string_field_ptr_build_va(mgr, pool_head, ptr, format, ap);
02204    va_end(ap);
02205 }

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  ap 
)

Definition at line 2115 of file main/utils.c.

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

Referenced by __ast_string_field_ptr_build().

02118 {
02119    size_t needed;
02120    size_t available;
02121    size_t space = (*pool_head)->size - (*pool_head)->used;
02122    int res;
02123    ssize_t grow;
02124    char *target;
02125    va_list ap2;
02126 
02127    /* if the field already has space allocated, try to reuse it;
02128       otherwise, try to use the empty space at the end of the current
02129       pool
02130    */
02131    if (*ptr != __ast_string_field_empty) {
02132       target = (char *) *ptr;
02133       available = AST_STRING_FIELD_ALLOCATION(*ptr);
02134       if (*ptr == mgr->last_alloc) {
02135          available += space;
02136       }
02137    } else {
02138       /* pool->used is always a multiple of ast_alignof(ast_string_field_allocation)
02139        * so we don't need to re-align anything here.
02140        */
02141       target = (*pool_head)->base + (*pool_head)->used + ast_alignof(ast_string_field_allocation);
02142       if (space > ast_alignof(ast_string_field_allocation)) {
02143          available = space - ast_alignof(ast_string_field_allocation);
02144       } else {
02145          available = 0;
02146       }
02147    }
02148 
02149    va_copy(ap2, ap);
02150    res = vsnprintf(target, available, format, ap2);
02151    va_end(ap2);
02152 
02153    if (res < 0) {
02154       /* Are we out of memory? */
02155       return;
02156    }
02157    if (res == 0) {
02158       __ast_string_field_release_active(*pool_head, *ptr);
02159       *ptr = __ast_string_field_empty;
02160       return;
02161    }
02162    needed = (size_t)res + 1; /* NUL byte */
02163 
02164    if (needed > available) {
02165       /* the allocation could not be satisfied using the field's current allocation
02166          (if it has one), or the space available in the pool (if it does not). allocate
02167          space for it, adding a new string pool if necessary.
02168       */
02169       if (!(target = (char *) __ast_string_field_alloc_space(mgr, pool_head, needed))) {
02170          return;
02171       }
02172       vsprintf(target, format, ap);
02173       va_end(ap); /* XXX va_end without va_start? */
02174       __ast_string_field_release_active(*pool_head, *ptr);
02175       *ptr = target;
02176    } else if (*ptr != target) {
02177       /* the allocation was satisfied using available space in the pool, but not
02178          using the space already allocated to the field
02179       */
02180       __ast_string_field_release_active(*pool_head, *ptr);
02181       mgr->last_alloc = *ptr = target;
02182            ast_assert(needed < (ast_string_field_allocation)-1);
02183       AST_STRING_FIELD_ALLOCATION(target) = (ast_string_field_allocation)needed;
02184       (*pool_head)->used += ast_make_room_for(needed, ast_string_field_allocation);
02185       (*pool_head)->active += needed;
02186    } else if ((grow = (needed - AST_STRING_FIELD_ALLOCATION(*ptr))) > 0) {
02187       /* the allocation was satisfied by using available space in the pool *and*
02188          the field was the last allocated field from the pool, so it grew
02189       */
02190       AST_STRING_FIELD_ALLOCATION(*ptr) += grow;
02191       (*pool_head)->used += ast_align_for(grow, ast_string_field_allocation);
02192       (*pool_head)->active += grow;
02193    }
02194 }

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 2068 of file main/utils.c.

References AST_STRING_FIELD_ALLOCATION, grow(), and ast_string_field_mgr::last_alloc.

02071 {
02072    ssize_t grow = needed - AST_STRING_FIELD_ALLOCATION(*ptr);
02073    size_t space = (*pool_head)->size - (*pool_head)->used;
02074 
02075    if (*ptr != mgr->last_alloc) {
02076       return 1;
02077    }
02078 
02079    if (space < grow) {
02080       return 1;
02081    }
02082 
02083    (*pool_head)->used += grow;
02084    (*pool_head)->active += grow;
02085    AST_STRING_FIELD_ALLOCATION(*ptr) += grow;
02086 
02087    return 0;
02088 }

void __ast_string_field_release_active ( struct ast_string_field_pool pool_head,
const ast_string_field  ptr 
)

Definition at line 2090 of file main/utils.c.

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

Referenced by __ast_string_field_ptr_build_va().

02092 {
02093    struct ast_string_field_pool *pool, *prev;
02094 
02095    if (ptr == __ast_string_field_empty) {
02096       return;
02097    }
02098 
02099    for (pool = pool_head, prev = NULL; pool; prev = pool, pool = pool->prev) {
02100       if ((ptr >= pool->base) && (ptr <= (pool->base + pool->size))) {
02101          pool->active -= AST_STRING_FIELD_ALLOCATION(ptr);
02102          if (pool->active == 0) {
02103             if (prev) {
02104                prev->prev = pool->prev;
02105                ast_free(pool);
02106             } else {
02107                pool->used = 0;
02108             }
02109          }
02110          break;
02111       }
02112    }
02113 }

static void __init_inet_ntoa_buf ( void   )  [static]

Definition at line 78 of file main/utils.c.

00095 {

int _ast_asprintf ( char **  ret,
const char *  file,
int  lineno,
const char *  func,
const char *  fmt,
  ... 
) [inline]

Definition at line 2606 of file main/utils.c.

References MALLOC_FAILURE_MSG, and vasprintf.

02607 {
02608    int res;
02609    va_list ap;
02610 
02611    va_start(ap, fmt);
02612    if ((res = vasprintf(ret, fmt, ap)) == -1) {
02613       MALLOC_FAILURE_MSG;
02614    }
02615    va_end(ap);
02616 
02617    return res;
02618 }

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 1924 of file main/utils.c.

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

Referenced by __ast_string_field_alloc_space(), and __ast_string_field_init().

01926 {
01927    struct ast_string_field_pool *pool;
01928    size_t alloc_size = optimal_alloc_size(sizeof(*pool) + size);
01929 
01930 #if defined(__AST_DEBUG_MALLOC)
01931    if (!(pool = __ast_calloc(1, alloc_size, file, lineno, func))) {
01932       return -1;
01933    }
01934 #else
01935    if (!(pool = ast_calloc(1, alloc_size))) {
01936       return -1;
01937    }
01938 #endif
01939 
01940    pool->prev = *pool_head;
01941    pool->size = alloc_size - sizeof(*pool);
01942    *pool_head = pool;
01943    mgr->last_alloc = NULL;
01944 
01945    return 0;
01946 }

int ast_atomic_fetchadd_int_slow ( volatile int *  p,
int  v 
)

Definition at line 2259 of file main/utils.c.

References ast_mutex_lock, ast_mutex_unlock, and fetchadd_m.

02260 {
02261    int ret;
02262    ast_mutex_lock(&fetchadd_m);
02263    ret = *p;
02264    *p += v;
02265    ast_mutex_unlock(&fetchadd_m);
02266    return ret;
02267 }

int ast_base64decode ( unsigned char *  dst,
const char *  src,
int  max 
)

decode BASE64 encoded text

Decode data from base64.

Definition at line 288 of file main/utils.c.

Referenced by action_messagesend(), aes_helper(), ast_check_signature(), ast_http_get_auth(), ast_sdp_crypto_alloc(), ast_sdp_crypto_process(), AST_TEST_DEFINE(), base64_helper(), custom_presence_callback(), osp_validate_token(), and presence_write().

00289 {
00290    int cnt = 0;
00291    unsigned int byte = 0;
00292    unsigned int bits = 0;
00293    int incnt = 0;
00294    while(*src && *src != '=' && (cnt < max)) {
00295       /* Shift in 6 bits of input */
00296       byte <<= 6;
00297       byte |= (b2a[(int)(*src)]) & 0x3f;
00298       bits += 6;
00299       src++;
00300       incnt++;
00301       /* If we have at least 8 bits left over, take that character
00302          off the top */
00303       if (bits >= 8)  {
00304          bits -= 8;
00305          *dst = (byte >> bits) & 0xff;
00306          dst++;
00307          cnt++;
00308       }
00309    }
00310    /* Don't worry about left over bits, they're extra anyway */
00311    return cnt;
00312 }

int ast_base64encode ( char *  dst,
const unsigned char *  src,
int  srclen,
int  max 
)

Encode data in base64.

Parameters:
dst the destination buffer
src the source data to be encoded
srclen the number of bytes present in the source buffer
max the maximum number of bytes to write into the destination buffer, *including* the terminating NULL character.

Definition at line 366 of file main/utils.c.

References ast_base64encode_full().

Referenced by aes_helper(), ast_sdp_crypto_alloc(), ast_sign(), AST_TEST_DEFINE(), base64_helper(), build_secret(), osp_check_destination(), presence_read(), websocket_client_create_key(), websocket_combine_key(), and xmpp_client_authenticate_sasl().

00367 {
00368    return ast_base64encode_full(dst, src, srclen, max, 0);
00369 }

int ast_base64encode_full ( char *  dst,
const unsigned char *  src,
int  srclen,
int  max,
int  linebreaks 
)

encode text to BASE64 coding

Definition at line 315 of file main/utils.c.

Referenced by ast_base64encode().

00316 {
00317    int cnt = 0;
00318    int col = 0;
00319    unsigned int byte = 0;
00320    int bits = 0;
00321    int cntin = 0;
00322    /* Reserve space for null byte at end of string */
00323    max--;
00324    while ((cntin < srclen) && (cnt < max)) {
00325       byte <<= 8;
00326       byte |= *(src++);
00327       bits += 8;
00328       cntin++;
00329       if ((bits == 24) && (cnt + 4 <= max)) {
00330          *dst++ = base64[(byte >> 18) & 0x3f];
00331          *dst++ = base64[(byte >> 12) & 0x3f];
00332          *dst++ = base64[(byte >> 6) & 0x3f];
00333          *dst++ = base64[byte & 0x3f];
00334          cnt += 4;
00335          col += 4;
00336          bits = 0;
00337          byte = 0;
00338       }
00339       if (linebreaks && (cnt < max) && (col == 64)) {
00340          *dst++ = '\n';
00341          cnt++;
00342          col = 0;
00343       }
00344    }
00345    if (bits && (cnt + 4 <= max)) {
00346       /* Add one last character for the remaining bits,
00347          padding the rest with 0 */
00348       byte <<= 24 - bits;
00349       *dst++ = base64[(byte >> 18) & 0x3f];
00350       *dst++ = base64[(byte >> 12) & 0x3f];
00351       if (bits == 16)
00352          *dst++ = base64[(byte >> 6) & 0x3f];
00353       else
00354          *dst++ = '=';
00355       *dst++ = '=';
00356       cnt += 4;
00357    }
00358    if (linebreaks && (cnt < max)) {
00359       *dst++ = '\n';
00360       cnt++;
00361    }
00362    *dst = '\0';
00363    return cnt;
00364 }

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:
buffer current position in buffer to place string into (will be updated on return)
space remaining space in buffer (will be updated on return)
fmt printf-style format string
Return values:
0 on success
non-zero on failure.

Definition at line 1640 of file main/utils.c.

References ast_build_string_va(), and result.

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

01641 {
01642    va_list ap;
01643    int result;
01644 
01645    va_start(ap, fmt);
01646    result = ast_build_string_va(buffer, space, fmt, ap);
01647    va_end(ap);
01648 
01649    return result;
01650 }

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:
buffer current position in buffer to place string into (will be updated on return)
space remaining space in buffer (will be updated on return)
fmt printf-style format string
ap varargs list of arguments for format

Definition at line 1621 of file main/utils.c.

References result.

Referenced by ast_build_string().

01622 {
01623    int result;
01624 
01625    if (!buffer || !*buffer || !space || !*space)
01626       return -1;
01627 
01628    result = vsnprintf(*buffer, *space, fmt, ap);
01629 
01630    if (result < 0)
01631       return -1;
01632    else if (result > *space)
01633       result = *space;
01634 
01635    *buffer += result;
01636    *space -= result;
01637    return 0;
01638 }

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:
f the file stream to write to
fd the file description to poll on to know when the file stream can be written to without blocking.
s the buffer to write from
len the number of bytes to write
timeoutms The 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:
0 success
-1 error

Definition at line 1428 of file main/utils.c.

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

Referenced by ast_websocket_close(), ast_websocket_write(), and send_string().

01429 {
01430    struct timeval start = ast_tvnow();
01431    int n = 0;
01432    int elapsed = 0;
01433 
01434    while (len) {
01435       if (wait_for_output(fd, timeoutms - elapsed)) {
01436          /* poll returned a fatal error, so bail out immediately. */
01437          return -1;
01438       }
01439 
01440       /* Clear any errors from a previous write */
01441       clearerr(f);
01442 
01443       n = fwrite(src, 1, len, f);
01444 
01445       if (ferror(f) && errno != EINTR && errno != EAGAIN) {
01446          /* fatal error from fwrite() */
01447          if (!feof(f)) {
01448             /* Don't spam the logs if it was just that the connection is closed. */
01449             ast_log(LOG_ERROR, "fwrite() returned error: %s\n", strerror(errno));
01450          }
01451          n = -1;
01452          break;
01453       }
01454 
01455       /* Update for data already written to the socket */
01456       len -= n;
01457       src += n;
01458 
01459       elapsed = ast_tvdiff_ms(ast_tvnow(), start);
01460       if (elapsed >= timeoutms) {
01461          /* We've taken too long to write
01462           * This is only an error condition if we haven't finished writing. */
01463          n = len ? -1 : 0;
01464          break;
01465       }
01466    }
01467 
01468    errno = 0;
01469    while (fflush(f)) {
01470       if (errno == EAGAIN || errno == EINTR) {
01471          /* fflush() does not appear to reset errno if it flushes
01472           * and reaches EOF at the same time. It returns EOF with
01473           * the last seen value of errno, causing a possible loop.
01474           * Also usleep() to reduce CPU eating if it does loop */
01475          errno = 0;
01476          usleep(1);
01477          continue;
01478       }
01479       if (errno && !feof(f)) {
01480          /* Don't spam the logs if it was just that the connection is closed. */
01481          ast_log(LOG_ERROR, "fflush() returned error: %s\n", strerror(errno));
01482       }
01483       n = -1;
01484       break;
01485    }
01486 
01487    return n < 0 ? -1 : 0;
01488 }

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 1387 of file main/utils.c.

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

Referenced by ast_agi_send(), ast_cli(), and cleanup_module().

01388 {
01389    struct timeval start = ast_tvnow();
01390    int res = 0;
01391    int elapsed = 0;
01392 
01393    while (len) {
01394       if (wait_for_output(fd, timeoutms - elapsed)) {
01395          return -1;
01396       }
01397 
01398       res = write(fd, s, len);
01399 
01400       if (res < 0 && errno != EAGAIN && errno != EINTR) {
01401          /* fatal error from write() */
01402          ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
01403          return -1;
01404       }
01405 
01406       if (res < 0) {
01407          /* It was an acceptable error */
01408          res = 0;
01409       }
01410 
01411       /* Update how much data we have left to write */
01412       len -= res;
01413       s += res;
01414       res = 0;
01415 
01416       elapsed = ast_tvdiff_ms(ast_tvnow(), start);
01417       if (elapsed >= timeoutms) {
01418          /* We've taken too long to write
01419           * This is only an error condition if we haven't finished writing. */
01420          res = len ? -1 : 0;
01421          break;
01422       }
01423    }
01424 
01425    return res;
01426 }

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 2657 of file main/utils.c.

Referenced by sip_route_process_header().

02658 {
02659 #if defined(DO_CRASH)
02660    abort();
02661    /*
02662     * Just in case abort() doesn't work or something else super
02663     * silly, and for Qwell's amusement.
02664     */
02665    *((int *) 0) = 0;
02666 #endif   /* defined(DO_CRASH) */
02667 }

int ast_eid_cmp ( const struct ast_eid eid1,
const struct ast_eid eid2 
)

char* ast_eid_to_str ( char *  s,
int  maxlen,
struct ast_eid eid 
)

void ast_enable_packet_fragmentation ( int  sock  ) 

Disable PMTU discovery on a socket.

Parameters:
sock The 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 2322 of file main/utils.c.

References ast_log, and LOG_WARNING.

Referenced by ast_netsock_bindaddr(), and reload_config().

02323 {
02324 #if defined(HAVE_IP_MTU_DISCOVER)
02325    int val = IP_PMTUDISC_DONT;
02326 
02327    if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
02328       ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
02329 #endif /* HAVE_IP_MTU_DISCOVER */
02330 }

char* ast_escape_quoted ( const char *  string,
char *  outbuf,
int  buflen 
)

Escape characters found in a quoted string.

Note:
This function escapes quoted characters based on the 'qdtext' set of allowed characters from RFC 3261 section 25.1.
Parameters:
string string to be escaped
outbuf resulting escaped string
buflen size of output buffer
Returns:
a pointer to the escaped string

Definition at line 457 of file main/utils.c.

References out.

Referenced by add_diversion(), add_rpid(), ast_callerid_merge(), AST_TEST_DEFINE(), channel_read_pjsip(), create_new_id_hdr(), initreqprep(), modify_id_header(), and receive_message().

00458 {
00459    const char *ptr  = string;
00460    char *out = outbuf;
00461    char *allow = "\t\v !"; /* allow LWS (minus \r and \n) and "!" */
00462 
00463    while (*ptr && out - outbuf < buflen - 1) {
00464       if (!(strchr(allow, *ptr))
00465          && !(*ptr >= '#' && *ptr <= '[') /* %x23 - %x5b */
00466          && !(*ptr >= ']' && *ptr <= '~') /* %x5d - %x7e */
00467          && !((unsigned char) *ptr > 0x7f)) {             /* UTF8-nonascii */
00468 
00469          if (out - outbuf >= buflen - 2) {
00470             break;
00471          }
00472          out += sprintf(out, "\\%c", (unsigned char) *ptr);
00473       } else {
00474          *out = *ptr;
00475          out++;
00476       }
00477       ptr++;
00478    }
00479 
00480    if (buflen) {
00481       *out = '\0';
00482    }
00483 
00484    return outbuf;
00485 }

char* ast_escape_semicolons ( const char *  string,
char *  outbuf,
int  buflen 
)

Escape semicolons found in a string.

Parameters:
string string to be escaped
outbuf resulting escaped string
buflen size of output buffer
Returns:
a pointer to the escaped string

Definition at line 487 of file main/utils.c.

References ast_assert, NULL, and out.

Referenced by ast_config_text_file_save2(), handle_cli_dialplan_save(), and test_semi().

00488 {
00489    const char *ptr = string;
00490    char *out = outbuf;
00491 
00492    if (string == NULL || outbuf == NULL) {
00493       ast_assert(string != NULL && outbuf != NULL);
00494       return NULL;
00495    }
00496 
00497    while (*ptr && out - outbuf < buflen - 1) {
00498       if (*ptr == ';') {
00499          if (out - outbuf >= buflen - 2) {
00500             break;
00501          }
00502          strcpy(out, "\\;");
00503          out += 2;
00504       } else {
00505          *out = *ptr;
00506          out++;
00507       }
00508       ptr++;
00509    }
00510 
00511    if (buflen) {
00512       *out = '\0';
00513    }
00514 
00515    return outbuf;
00516 }

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:
0 if val is a NULL pointer.
-1 if "true".
0 otherwise.

Definition at line 1689 of file main/utils.c.

References ast_strlen_zero.

Referenced by acf_faxopt_write(), acf_transaction_write(), actual_load_config(), announce_user_count_all_handler(), aoc_cli_debug_enable(), bool_handler_fn(), boolflag_handler_fn(), build_peer(), build_user(), check_debug(), dahdi_set_dnd(), find_realtime(), func_channel_write_real(), function_ooh323_write(), handle_common_options(), handle_queue_set_member_ringinuse(), hook_write(), init_acf_query(), load_config(), load_odbc_config(), manager_mute_mixmonitor(), manager_queue_member_ringinuse(), parking_feature_flag_cfg(), parse_empty_options(), parse_playtone(), prack_handler(), process_dahdi(), reload_config(), reload_single_member(), rt_handle_member_record(), rtp_reload(), run_agi(), set_config(), set_insecure_flags(), sip_parse_nat_option(), sla_build_trunk(), strings_to_mask(), and timers_handler().

01690 {
01691    if (ast_strlen_zero(s))
01692       return 0;
01693 
01694    /* Determine if this is a false value */
01695    if (!strcasecmp(s, "no") ||
01696        !strcasecmp(s, "false") ||
01697        !strcasecmp(s, "n") ||
01698        !strcasecmp(s, "f") ||
01699        !strcasecmp(s, "0") ||
01700        !strcasecmp(s, "off"))
01701       return -1;
01702 
01703    return 0;
01704 }

void ast_format_duration_hh_mm_ss ( int  duration,
char *  buf,
size_t  length 
)

Formats a duration into HH:MM:SS.

Since:
12
Parameters:
duration The time (in seconds) to format
buf A buffer to hold the formatted string'
length The size of the buffer

Definition at line 1770 of file main/utils.c.

Referenced by show_chanstats_cb().

01771 {
01772    int durh, durm, durs;
01773    durh = duration / 3600;
01774    durm = (duration % 3600) / 60;
01775    durs = duration % 60;
01776    snprintf(buf, length, "%02d:%02d:%02d", durh, durm, durs);
01777 }

int ast_get_tid ( void   ) 

Get current thread ID.

Returns:
the ID if platform is supported, else -1

Definition at line 2621 of file main/utils.c.

Referenced by __ao2_alloc_debug(), __ao2_ref_debug(), ast_log_full(), ast_register_thread(), and dummy_start().

02622 {
02623    int ret = -1;
02624 #if defined (__linux) && defined(SYS_gettid)
02625    ret = syscall(SYS_gettid); /* available since Linux 1.4.11 */
02626 #elif defined(__sun)
02627    ret = pthread_self();
02628 #elif defined(__APPLE__)
02629    ret = mach_thread_self();
02630    mach_port_deallocate(mach_task_self(), ret);
02631 #elif defined(__FreeBSD__) && defined(HAVE_SYS_THR_H)
02632    long lwpid;
02633    thr_self(&lwpid); /* available since sys/thr.h creation 2003 */
02634    ret = lwpid;
02635 #endif
02636    return ret;
02637 }

int ast_get_time_t ( const char *  src,
time_t *  dst,
time_t  _default,
int *  consumed 
)

get values from config variables.

Definition at line 2299 of file main/utils.c.

References ast_strlen_zero, and NULL.

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

02300 {
02301    long t;
02302    int scanned;
02303 
02304    if (dst == NULL)
02305       return -1;
02306 
02307    *dst = _default;
02308 
02309    if (ast_strlen_zero(src))
02310       return -1;
02311 
02312    /* only integer at the moment, but one day we could accept more formats */
02313    if (sscanf(src, "%30ld%n", &t, &scanned) == 1) {
02314       *dst = t;
02315       if (consumed)
02316          *consumed = scanned;
02317       return 0;
02318    } else
02319       return -1;
02320 }

int ast_get_timeval ( const char *  src,
struct timeval *  dst,
struct timeval  _default,
int *  consumed 
)

get values from config variables.

Definition at line 2272 of file main/utils.c.

References ast_strlen_zero, and NULL.

Referenced by acf_strftime(), expiration_str2struct(), persistence_expires_str2struct(), and timeval_str2struct().

02273 {
02274    long double dtv = 0.0;
02275    int scanned;
02276 
02277    if (dst == NULL)
02278       return -1;
02279 
02280    *dst = _default;
02281 
02282    if (ast_strlen_zero(src))
02283       return -1;
02284 
02285    /* only integer at the moment, but one day we could accept more formats */
02286    if (sscanf(src, "%30Lf%n", &dtv, &scanned) > 0) {
02287       dst->tv_sec = dtv;
02288       dst->tv_usec = (dtv - dst->tv_sec) * 1000000.0;
02289       if (consumed)
02290          *consumed = scanned;
02291       return 0;
02292    } else
02293       return -1;
02294 }

struct hostent* ast_gethostbyname ( const char *  host,
struct ast_hostent hp 
) [read]

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 192 of file main/utils.c.

References ast_hostent::buf, gethostbyname_r(), ast_hostent::hp, NULL, and result.

Referenced by ast_parse_arg(), build_peer(), config_load(), config_parse_variables(), festival_exec(), iax_template_parse(), process_sdp(), reload_config(), and set_config().

00193 {
00194    int res;
00195    int herrno;
00196    int dots = 0;
00197    const char *s;
00198    struct hostent *result = NULL;
00199    /* Although it is perfectly legitimate to lookup a pure integer, for
00200       the sake of the sanity of people who like to name their peers as
00201       integers, we break with tradition and refuse to look up a
00202       pure integer */
00203    s = host;
00204    res = 0;
00205    while (s && *s) {
00206       if (*s == '.')
00207          dots++;
00208       else if (!isdigit(*s))
00209          break;
00210       s++;
00211    }
00212    if (!s || !*s) {
00213       /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
00214       if (dots != 3)
00215          return NULL;
00216       memset(hp, 0, sizeof(struct ast_hostent));
00217       hp->hp.h_addrtype = AF_INET;
00218       hp->hp.h_addr_list = (void *) hp->buf;
00219       hp->hp.h_addr = hp->buf + sizeof(void *);
00220       /* For AF_INET, this will always be 4 */
00221       hp->hp.h_length = 4;
00222       if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
00223          return &hp->hp;
00224       return NULL;
00225 
00226    }
00227 #ifdef HAVE_GETHOSTBYNAME_R_5
00228    result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);
00229 
00230    if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
00231       return NULL;
00232 #else
00233    res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
00234 
00235    if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
00236       return NULL;
00237 #endif
00238    return &hp->hp;
00239 }

const char* ast_inet_ntoa ( struct in_addr  ia  ) 

void ast_join_delim ( char *  s,
size_t  len,
const char *const   w[],
unsigned int  size,
char  delim 
)

Definition at line 1851 of file main/utils.c.

Referenced by ast_sip_auths_to_str().

01852 {
01853    int x, ofs = 0;
01854    const char *src;
01855 
01856    /* Join words into a string */
01857    if (!s)
01858       return;
01859    for (x = 0; ofs < len && x < size && w[x] ; x++) {
01860       if (x > 0)
01861          s[ofs++] = delim;
01862       for (src = w[x]; *src && ofs < len; src++)
01863          s[ofs++] = *src;
01864    }
01865    if (ofs == len)
01866       ofs--;
01867    s[ofs] = '\0';
01868 }

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 242 of file main/utils.c.

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

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

00243 {
00244    struct MD5Context md5;
00245    unsigned char digest[16];
00246    char *ptr;
00247    int x;
00248 
00249    MD5Init(&md5);
00250    MD5Update(&md5, (const unsigned char *) input, strlen(input));
00251    MD5Final(digest, &md5);
00252    ptr = output;
00253    for (x = 0; x < 16; x++)
00254       ptr += sprintf(ptr, "%02hhx", digest[x]);
00255 }

int ast_mkdir ( const char *  path,
int  mode 
)

Recursively create directory path.

Parameters:
path The directory path to create
mode The 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 2332 of file main/utils.c.

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

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

02333 {
02334    char *ptr;
02335    int len = strlen(path), count = 0, x, piececount = 0;
02336    char *tmp = ast_strdupa(path);
02337    char **pieces;
02338    char *fullpath = ast_alloca(len + 1);
02339    int res = 0;
02340 
02341    for (ptr = tmp; *ptr; ptr++) {
02342       if (*ptr == '/')
02343          count++;
02344    }
02345 
02346    /* Count the components to the directory path */
02347    pieces = ast_alloca(count * sizeof(*pieces));
02348    for (ptr = tmp; *ptr; ptr++) {
02349       if (*ptr == '/') {
02350          *ptr = '\0';
02351          pieces[piececount++] = ptr + 1;
02352       }
02353    }
02354 
02355    *fullpath = '\0';
02356    for (x = 0; x < piececount; x++) {
02357       /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
02358       strcat(fullpath, "/");
02359       strcat(fullpath, pieces[x]);
02360       res = mkdir(fullpath, mode);
02361       if (res && errno != EEXIST)
02362          return errno;
02363    }
02364    return 0;
02365 }

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 2491 of file main/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(), c, ast_http_digest::cnonce, ast_http_digest::domain, LOG_WARNING, ast_http_digest::nc, ast_http_digest::nonce, NULL, 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().

02491                                                                                                {
02492    char *c;
02493    struct ast_str *str = ast_str_create(16);
02494 
02495    /* table of recognised keywords, and places where they should be copied */
02496    const struct x {
02497       const char *key;
02498       const ast_string_field *field;
02499    } *i, keys[] = {
02500       { "username=", &d->username },
02501       { "realm=", &d->realm },
02502       { "nonce=", &d->nonce },
02503       { "uri=", &d->uri },
02504       { "domain=", &d->domain },
02505       { "response=", &d->response },
02506       { "cnonce=", &d->cnonce },
02507       { "opaque=", &d->opaque },
02508       /* Special cases that cannot be directly copied */
02509       { "algorithm=", NULL },
02510       { "qop=", NULL },
02511       { "nc=", NULL },
02512       { NULL, 0 },
02513    };
02514 
02515    if (ast_strlen_zero(digest) || !d || !str) {
02516       ast_free(str);
02517       return -1;
02518    }
02519 
02520    ast_str_set(&str, 0, "%s", digest);
02521 
02522    c = ast_skip_blanks(ast_str_buffer(str));
02523 
02524    if (strncasecmp(c, "Digest ", strlen("Digest "))) {
02525       ast_log(LOG_WARNING, "Missing Digest.\n");
02526       ast_free(str);
02527       return -1;
02528    }
02529    c += strlen("Digest ");
02530 
02531    /* lookup for keys/value pair */
02532    while (c && *c && *(c = ast_skip_blanks(c))) {
02533       /* find key */
02534       for (i = keys; i->key != NULL; i++) {
02535          char *src, *separator;
02536          int unescape = 0;
02537          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
02538             continue;
02539          }
02540 
02541          /* Found. Skip keyword, take text in quotes or up to the separator. */
02542          c += strlen(i->key);
02543          if (*c == '"') {
02544             src = ++c;
02545             separator = "\"";
02546             unescape = 1;
02547          } else {
02548             src = c;
02549             separator = ",";
02550          }
02551          strsep(&c, separator); /* clear separator and move ptr */
02552          if (unescape) {
02553             ast_unescape_c(src);
02554          }
02555          if (i->field) {
02556             ast_string_field_ptr_set(d, i->field, src);
02557          } else {
02558             /* Special cases that require additional procesing */
02559             if (!strcasecmp(i->key, "algorithm=")) {
02560                if (strcasecmp(src, "MD5")) {
02561                   ast_log(LOG_WARNING, "Digest algorithm: \"%s\" not supported.\n", src);
02562                   ast_free(str);
02563                   return -1;
02564                }
02565             } else if (!strcasecmp(i->key, "qop=") && !strcasecmp(src, "auth")) {
02566                d->qop = 1;
02567             } else if (!strcasecmp(i->key, "nc=")) {
02568                unsigned long u;
02569                if (sscanf(src, "%30lx", &u) != 1) {
02570                   ast_log(LOG_WARNING, "Incorrect Digest nc value: \"%s\".\n", src);
02571                   ast_free(str);
02572                   return -1;
02573                }
02574                ast_string_field_set(d, nc, src);
02575             }
02576          }
02577          break;
02578       }
02579       if (i->key == NULL) { /* not found, try ',' */
02580          strsep(&c, ",");
02581       }
02582    }
02583    ast_free(str);
02584 
02585    /* Digest checkout */
02586    if (ast_strlen_zero(d->realm) || ast_strlen_zero(d->nonce)) {
02587       /* "realm" and "nonce" MUST be always exist */
02588       return -1;
02589    }
02590 
02591    if (!request) {
02592       /* Additional check for Digest response */
02593       if (ast_strlen_zero(d->username) || ast_strlen_zero(d->uri) || ast_strlen_zero(d->response)) {
02594          return -1;
02595       }
02596 
02597       if (pedantic && d->qop && (ast_strlen_zero(d->cnonce) || ast_strlen_zero(d->nc))) {
02598          return -1;
02599       }
02600    }
02601 
02602    return 0;
02603 }

char* ast_process_quotes_and_slashes ( char *  start,
char  find,
char  replace_with 
)

Process a string to find and replace characters.

Parameters:
start The string to analyze
find The character to find
replace_with The character that will replace the one we are looking for

Definition at line 1825 of file main/utils.c.

Referenced by pbx_load_config().

01826 {
01827    char *dataPut = start;
01828    int inEscape = 0;
01829    int inQuotes = 0;
01830 
01831    for (; *start; start++) {
01832       if (inEscape) {
01833          *dataPut++ = *start;       /* Always goes verbatim */
01834          inEscape = 0;
01835       } else {
01836          if (*start == '\\') {
01837             inEscape = 1;      /* Do not copy \ into the data */
01838          } else if (*start == '\'') {
01839             inQuotes = 1 - inQuotes;   /* Do not copy ' into the data */
01840          } else {
01841             /* Replace , with |, unless in quotes */
01842             *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
01843          }
01844       }
01845    }
01846    if (start != dataPut)
01847       *dataPut = 0;
01848    return dataPut;
01849 }

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 1289 of file main/utils.c.

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

01292 {
01293    unsigned char attr_destroy = 0;
01294    int res;
01295 
01296    if (!attr) {
01297       attr = ast_alloca(sizeof(*attr));
01298       pthread_attr_init(attr);
01299       attr_destroy = 1;
01300    }
01301 
01302    if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
01303       ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
01304 
01305    res = ast_pthread_create_stack(thread, attr, start_routine, data,
01306                                   stacksize, file, caller, line, start_fn);
01307 
01308    if (attr_destroy)
01309       pthread_attr_destroy(attr);
01310 
01311    return res;
01312 }

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 1241 of file main/utils.c.

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

Referenced by ast_pthread_create_detached_stack().

01244 {
01245 #if !defined(LOW_MEMORY)
01246    struct thr_arg *a;
01247 #endif
01248 
01249    if (!attr) {
01250       attr = ast_alloca(sizeof(*attr));
01251       pthread_attr_init(attr);
01252    }
01253 
01254 #ifdef __linux__
01255    /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
01256       which is kind of useless. Change this here to
01257       PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
01258       priority will propagate down to new threads by default.
01259       This does mean that callers cannot set a different priority using
01260       PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
01261       the priority afterwards with pthread_setschedparam(). */
01262    if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
01263       ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
01264 #endif
01265 
01266    if (!stacksize)
01267       stacksize = AST_STACKSIZE;
01268 
01269    if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
01270       ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
01271 
01272 #if !defined(LOW_MEMORY)
01273    if ((a = ast_malloc(sizeof(*a)))) {
01274       a->start_routine = start_routine;
01275       a->data = data;
01276       start_routine = dummy_start;
01277       if (ast_asprintf(&a->name, "%-20s started at [%5d] %s %s()",
01278               start_fn, line, file, caller) < 0) {
01279          a->name = NULL;
01280       }
01281       data = a;
01282    }
01283 #endif /* !LOW_MEMORY */
01284 
01285    return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
01286 }

long int ast_random ( void   ) 

Definition at line 1785 of file main/utils.c.

References ast_mutex_lock, ast_mutex_unlock, and randomlock.

Referenced by __sip_alloc(), acf_rand_exec(), action_challenge(), add_sdp(), agi_handle_command(), app_exec(), ast_generate_random_string(), ast_lock_path_lockfile(), ast_moh_files_next(), ast_rtp_change_source(), ast_rtp_new(), AST_TEST_DEFINE(), ast_udptl_new_with_bindaddr(), astobj2_test_1_helper(), auth_http_callback(), authenticate_request(), build_gateway(), build_iv(), build_localtag_registry(), build_nonce(), build_rand_pad(), build_reply_digest(), calc_metric(), calc_rxstamp(), caldav_write_event(), create_channel_name(), create_local_sdp(), dns_srv_sort(), generate_parked_user(), generate_random_string(), generic_http_callback(), get_trans_id(), get_unused_callno(), handle_cli_sched_bench(), handle_incoming(), handle_response_invite(), iax2_key_rotate(), jingle_add_ice_udp_candidates_to_transport(), jingle_alloc(), jingle_new(), load_module(), make_email_file(), make_our_tag(), mbl_new(), mktemp_internal(), moh_files_alloc(), multicast_rtp_new(), ogg_vorbis_rewrite(), osp_create_uuid(), page_exec(), process_weights(), reg_source_db(), registry_authrequest(), reqprep(), reschedule_reinvite(), say_periodic_announcement(), sendmail(), sip_outbound_registration_perform(), socket_read(), start_rtp(), stun_req_id(), test_ao2_find_w_no_flags(), test_ao2_find_w_OBJ_KEY(), test_ao2_find_w_OBJ_PARTIAL_KEY(), test_ao2_find_w_OBJ_POINTER(), transmit_invite(), transmit_register(), transmit_response_using_temp(), try_calling(), try_firmware(), and websocket_client_create_key().

01786 {
01787    long int res;
01788 
01789    if (dev_urandom_fd >= 0) {
01790       int read_res = read(dev_urandom_fd, &res, sizeof(res));
01791       if (read_res > 0) {
01792          long int rm = RAND_MAX;
01793          res = res < 0 ? ~res : res;
01794          rm++;
01795          return res % rm;
01796       }
01797    }
01798 
01799    /* XXX - Thread safety really depends on the libc, not the OS.
01800     *
01801     * But... popular Linux libc's (uClibc, glibc, eglibc), all have a
01802     * somewhat thread safe random(3) (results are random, but not
01803     * reproducible). The libc's for other systems (BSD, et al.), not so
01804     * much.
01805     */
01806 #ifdef linux
01807    res = random();
01808 #else
01809    ast_mutex_lock(&randomlock);
01810    res = random();
01811    ast_mutex_unlock(&randomlock);
01812 #endif
01813    return res;
01814 }

int ast_regex_string_to_regex_pattern ( const char *  regex_string,
struct ast_str **  regex_pattern 
)

Given a string regex_string in the form of "/regex/", convert it into the form of "regex".

This function will trim one leading / and one trailing / from a given input string ast_str regex_pattern must be preallocated before calling this function

Returns:
0 on success, non-zero on failure.

1 if we only stripped a leading /

2 if we only stripped a trailing /

3 if we did not strip any / characters

Parameters:
regex_string the string containing /regex/
regex_pattern the destination ast_str which will contain "regex" after execution

Definition at line 1652 of file main/utils.c.

References ast_str_set(), and ast_str_truncate().

Referenced by action_hangup(), mwi_mailbox_delete(), and mwi_mailbox_get().

01653 {
01654    int regex_len = strlen(regex_string);
01655    int ret = 3;
01656 
01657    /* Chop off the leading / if there is one */
01658    if ((regex_len >= 1) && (regex_string[0] == '/')) {
01659       ast_str_set(regex_pattern, 0, "%s", regex_string + 1);
01660       ret -= 2;
01661    }
01662 
01663    /* Chop off the ending / if there is one */
01664    if ((regex_len > 1) && (regex_string[regex_len - 1] == '/')) {
01665       ast_str_truncate(*regex_pattern, -1);
01666       ret -= 1;
01667    }
01668 
01669    return ret;
01670 }

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:
start When timing started being calculated
max_ms The 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 1754 of file main/utils.c.

References ast_tvdiff_ms(), and ast_tvnow().

Referenced by __analog_ss_thread(), __ast_answer(), __ast_request_and_dial(), analog_ss_thread(), ast_recvtext(), ast_safe_sleep_conditional(), ast_waitfordigit_full(), disable_t38(), find_cache(), generic_fax_exec(), parking_set_duration(), receivefax_t38_init(), record_exec(), sendfax_t38_init(), tcptls_stream_read(), tcptls_stream_write(), wait_for_answer(), and waitforring_exec().

01755 {
01756    int ms;
01757 
01758    if (max_ms < 0) {
01759       ms = max_ms;
01760    } else {
01761       ms = max_ms - ast_tvdiff_ms(ast_tvnow(), start);
01762       if (ms < 0) {
01763          ms = 0;
01764       }
01765    }
01766 
01767    return ms;
01768 }

void ast_replace_subargument_delimiter ( char *  s  ) 

Replace '^' in a string with ','.

Parameters:
s String within which to replace characters

Definition at line 1816 of file main/utils.c.

Referenced by app_exec(), ast_bridge_set_after_go_on(), ast_dial_prerun(), begin_dial(), dial_exec_full(), handle_call_forward(), and page_exec().

01817 {
01818    for (; *s; s++) {
01819       if (*s == '^') {
01820          *s = ',';
01821       }
01822    }
01823 }

int ast_safe_mkdir ( const char *  base_path,
const char *  path,
int  mode 
)

Recursively create directory path, but only if it resolves within the given base_path.

If base_path does not exist, it will not be created and this function returns EPERM.

Parameters:
path The directory path to create
mode The permissions with which to try to create the directory
Returns:
0 on success or an error code otherwise

Definition at line 2437 of file main/utils.c.

References ast_free, ast_std_free, ast_strdup, errno, NULL, RAII_VAR, and safe_mkdir().

Referenced by AST_TEST_DEFINE(), stasis_app_control_record(), and stasis_app_stored_recording_copy().

02438 {
02439    RAII_VAR(char *, absolute_base_path, NULL, ast_std_free);
02440    RAII_VAR(char *, p, NULL, ast_free);
02441 
02442    if (base_path == NULL || path == NULL) {
02443       errno = EFAULT;
02444       return errno;
02445    }
02446 
02447    p = ast_strdup(path);
02448    if (p == NULL) {
02449       errno = ENOMEM;
02450       return errno;
02451    }
02452 
02453    absolute_base_path = realpath(base_path, NULL);
02454    if (absolute_base_path == NULL) {
02455       return errno;
02456    }
02457 
02458    return safe_mkdir(absolute_base_path, p, mode);
02459 }

void ast_set_default_eid ( struct ast_eid eid  ) 

Fill in an ast_eid with the default eid of this machine.

Since:
1.6.1

Definition at line 2712 of file main/utils.c.

References ARRAY_LEN, ast_debug, ast_eid_to_str(), and ast_eid::eid.

Referenced by ast_readconfig().

02713 {
02714 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_IFRU_IFRU_HWADDR)
02715    int s, x = 0;
02716    char eid_str[20];
02717    struct ifreq ifr;
02718    static const unsigned int MAXIF = 10;
02719 
02720    s = socket(AF_INET, SOCK_STREAM, 0);
02721    if (s < 0) {
02722       return;
02723    }
02724    for (x = 0; x < MAXIF; x++) {
02725       static const char *prefixes[] = { "eth", "em" };
02726       unsigned int i;
02727 
02728       for (i = 0; i < ARRAY_LEN(prefixes); i++) {
02729          memset(&ifr, 0, sizeof(ifr));
02730          snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", prefixes[i], x);
02731          if (!ioctl(s, SIOCGIFHWADDR, &ifr)) {
02732             break;
02733          }
02734       }
02735 
02736       if (i == ARRAY_LEN(prefixes)) {
02737          /* Try pciX#[1..N] */
02738          for (i = 0; i < MAXIF; i++) {
02739             memset(&ifr, 0, sizeof(ifr));
02740             snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "pci%d#%u", x, i);
02741             if (!ioctl(s, SIOCGIFHWADDR, &ifr)) {
02742                break;
02743             }
02744          }
02745          if (i == MAXIF) {
02746             continue;
02747          }
02748       }
02749 
02750       memcpy(eid, ((unsigned char *)&ifr.ifr_hwaddr) + 2, sizeof(*eid));
02751       ast_debug(1, "Seeding global EID '%s' from '%s' using 'siocgifhwaddr'\n", ast_eid_to_str(eid_str, sizeof(eid_str), eid), ifr.ifr_name);
02752       close(s);
02753       return;
02754    }
02755    close(s);
02756 #else
02757 #if defined(ifa_broadaddr) && !defined(SOLARIS)
02758    char eid_str[20];
02759    struct ifaddrs *ifap;
02760 
02761    if (getifaddrs(&ifap) == 0) {
02762       struct ifaddrs *p;
02763       for (p = ifap; p; p = p->ifa_next) {
02764          if ((p->ifa_addr->sa_family == AF_LINK) && !(p->ifa_flags & IFF_LOOPBACK) && (p->ifa_flags & IFF_RUNNING)) {
02765             struct sockaddr_dl* sdp = (struct sockaddr_dl*) p->ifa_addr;
02766             memcpy(&(eid->eid), sdp->sdl_data + sdp->sdl_nlen, 6);
02767             ast_debug(1, "Seeding global EID '%s' from '%s' using 'getifaddrs'\n", ast_eid_to_str(eid_str, sizeof(eid_str), eid), p->ifa_name);
02768             freeifaddrs(ifap);
02769             return;
02770          }
02771       }
02772       freeifaddrs(ifap);
02773    }
02774 #endif
02775 #endif
02776    ast_debug(1, "No ethernet interface found for seeding global EID. You will have to set it manually.\n");
02777 }

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 258 of file main/utils.c.

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

Referenced by AST_TEST_DEFINE(), handle_call_token(), sha1(), xmpp_client_authenticate_digest(), and xmpp_component_authenticate().

00259 {
00260    struct SHA1Context sha;
00261    char *ptr;
00262    int x;
00263    uint8_t Message_Digest[20];
00264 
00265    SHA1Reset(&sha);
00266 
00267    SHA1Input(&sha, (const unsigned char *) input, strlen(input));
00268 
00269    SHA1Result(&sha, Message_Digest);
00270    ptr = output;
00271    for (x = 0; x < 20; x++)
00272       ptr += sprintf(ptr, "%02hhx", Message_Digest[x]);
00273 }

void ast_sha1_hash_uint ( uint8_t *  digest,
const char *  input 
)

Produce a 20 byte SHA1 hash of value.

Produces SHA1 hash based on input string, stored in uint8_t array.

Definition at line 276 of file main/utils.c.

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

Referenced by websocket_combine_key().

00277 {
00278         struct SHA1Context sha;
00279 
00280         SHA1Reset(&sha);
00281 
00282         SHA1Input(&sha, (const unsigned char *) input, strlen(input));
00283 
00284         SHA1Result(&sha, digest);
00285 }

int ast_str_to_eid ( struct ast_eid eid,
const char *  s 
)

Convert a string into an EID.

This function expects an EID in the format: 00:11:22:33:44:55

Returns:
0 success, non-zero failure
Since:
1.6.1

Definition at line 2779 of file main/utils.c.

References ast_eid::eid.

Referenced by ast_readconfig(), asterisk_publication_devicestate_state_change(), asterisk_publication_mwi_state_change(), build_peer(), dundi_do_query(), set_config(), and xmpp_pubsub_handle_event().

02780 {
02781    unsigned int eid_int[6];
02782    int x;
02783 
02784    if (sscanf(s, "%2x:%2x:%2x:%2x:%2x:%2x", &eid_int[0], &eid_int[1], &eid_int[2],
02785        &eid_int[3], &eid_int[4], &eid_int[5]) != 6) {
02786          return -1;
02787    }
02788 
02789    for (x = 0; x < 6; x++) {
02790       eid->eid[x] = eid_int[x];
02791    }
02792 
02793    return 0;
02794 }

char* ast_strip_quoted ( char *  s,
const char *  beg_quotes,
const char *  end_quotes 
)

Strip leading/trailing whitespace and quotes from a string.

Parameters:
s The string to be stripped (will be modified).
beg_quotes The list of possible beginning quote characters.
end_quotes The 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 1490 of file main/utils.c.

References ast_strip().

Referenced by applicationmap_handler(), ast_callerid_parse(), ast_register_file_version(), ast_strsep(), dialog_info_generate_body_content(), get_rdnis(), iftime(), load_values_config(), parse_allowed_methods(), parse_cookies(), parse_dial_string(), pidf_allocate_body(), sip_parse_register_line(), and xpidf_allocate_body().

01491 {
01492    char *e;
01493    char *q;
01494 
01495    s = ast_strip(s);
01496    if ((q = strchr(beg_quotes, *s)) && *q != '\0') {
01497       e = s + strlen(s) - 1;
01498       if (*e == *(end_quotes + (q - beg_quotes))) {
01499          s++;
01500          *e = '\0';
01501       }
01502    }
01503 
01504    return s;
01505 }

char* ast_strsep ( char **  s,
const char  sep,
uint32_t  flags 
)

Act like strsep but ignore separators inside quotes.

Parameters:
s Pointer to address of the the string to be processed. Will be modified and can't be constant.
sep A single character delimiter.
flags Controls post-processing of the result. AST_STRSEP_TRIM trims all leading and trailing whitespace from the result. AST_STRSEP_STRIP does a trim then strips the outermost quotes. You may want to trim again after the strip. Just OR both the TRIM and STRIP flags. AST_STRSEP_UNESCAPE unescapes '\' sequences. AST_STRSEP_ALL does all of the above processing.
Returns:
The next token or NULL if done or if there are more than 8 levels of nested quotes.
This function acts like strsep with three exceptions... The separator is a single character instead of a string. Separators inside quotes are treated literally instead of like separators. You can elect to have leading and trailing whitespace and quotes stripped from the result and have '\' sequences unescaped.

Like strsep, ast_strsep maintains no internal state and you can call it recursively using different separators on the same storage.

Also like strsep, for consistent results, consecutive separators are not collapsed so you may get an empty string as a valid result.

Examples:

   char *mystr = ast_strdupa("abc=def,ghi='zzz=yyy,456',jkl");
   char *token, *token2, *token3;

   while((token = ast_strsep(&mystr, ',', AST_SEP_STRIP))) {
      // 1st token will be aaa=def
      // 2nd token will be ghi='zzz=yyy,456'
      while((token2 = ast_strsep(&token, '=', AST_SEP_STRIP))) {
         // 1st token2 will be ghi
         // 2nd token2 will be zzz=yyy,456
         while((token3 = ast_strsep(&token2, ',', AST_SEP_STRIP))) {
            // 1st token3 will be zzz=yyy
            // 2nd token3 will be 456
            // and so on
         }
      }
      // 3rd token will be jkl
   }

Definition at line 1507 of file main/utils.c.

References ast_strip(), ast_strip_quoted(), AST_STRSEP_STRIP, AST_STRSEP_TRIM, AST_STRSEP_UNESCAPE, ast_unescape_quoted(), and NULL.

Referenced by AST_TEST_DEFINE(), does_category_match(), handle_updates(), and wizard_apply_handler().

01508 {
01509    char *st = *iss;
01510    char *is;
01511    int inquote = 0;
01512    int found = 0;
01513    char stack[8];
01514 
01515    if (iss == NULL || *iss == '\0') {
01516       return NULL;
01517    }
01518 
01519    memset(stack, 0, sizeof(stack));
01520 
01521    for(is = st; *is; is++) {
01522       if (*is == '\\') {
01523          if (*++is != '\0') {
01524             is++;
01525          } else {
01526             break;
01527          }
01528       }
01529 
01530       if (*is == '\'' || *is == '"') {
01531          if (*is == stack[inquote]) {
01532             stack[inquote--] = '\0';
01533          } else {
01534             if (++inquote >= sizeof(stack)) {
01535                return NULL;
01536             }
01537             stack[inquote] = *is;
01538          }
01539       }
01540 
01541       if (*is == sep && !inquote) {
01542          *is = '\0';
01543          found = 1;
01544          *iss = is + 1;
01545          break;
01546       }
01547    }
01548    if (!found) {
01549       *iss = NULL;
01550    }
01551 
01552    if (flags & AST_STRSEP_STRIP) {
01553       st = ast_strip_quoted(st, "'\"", "'\"");
01554    }
01555 
01556    if (flags & AST_STRSEP_TRIM) {
01557       st = ast_strip(st);
01558    }
01559 
01560    if (flags & AST_STRSEP_UNESCAPE) {
01561       ast_unescape_quoted(st);
01562    }
01563 
01564    return st;
01565 }

char* ast_to_camel_case_delim ( const char *  s,
const char *  delim 
)

Definition at line 1870 of file main/utils.c.

References ast_copy_string(), ast_strdup, buf, and NULL.

01871 {
01872    char *res = ast_strdup(s);
01873    char *front, *back, *buf = res;
01874    int size;
01875 
01876    front = strtok_r(buf, delim, &back);
01877 
01878    while (front) {
01879       size = strlen(front);
01880       *front = toupper(*front);
01881       ast_copy_string(buf, front, size + 1);
01882       buf += size;
01883       front = strtok_r(NULL, delim, &back);
01884    }
01885 
01886    return res;
01887 }

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:
0 if val is a NULL pointer.
-1 if "true".
0 otherwise.

Definition at line 1672 of file main/utils.c.

References ast_strlen_zero.

Referenced by __ast_http_load(), __init_manager(), _parse(), acf_curlopt_write(), acf_faxopt_write(), acf_transaction_write(), action_agent_logoff(), action_originate(), action_status(), action_updateconfig(), actual_load_config(), agent_login_channel_config(), announce_user_count_all_handler(), aoc_cli_debug_enable(), apply_general_options(), apply_option(), apply_outgoing(), ast_ari_bridges_record_cb(), ast_ari_channels_record_cb(), ast_bridge_timelimit(), ast_jb_read_conf(), ast_plc_reload(), ast_readconfig(), ast_rtp_dtls_cfg_parse(), AST_TEST_DEFINE(), ast_tls_read_conf(), autopause2int(), bool_handler_fn(), boolflag_handler_fn(), build_device(), build_gateway(), build_peer(), build_user(), cdr_prop_write_callback(), check_debug(), client_bitfield_handler(), config_parse_variables(), custom_bitfield_handler(), customopt_handler(), dahdi_set_dnd(), data_search_cmp_bool(), do_reload(), encoding_format_handler(), festival_exec(), func_channel_write_real(), func_mute_write(), function_ooh323_write(), get_encrypt_methods(), global_bitfield_handler(), handle_common_options(), handle_logger_set_level(), handle_queue_set_member_ringinuse(), handle_t38_options(), hook_write(), init_logger_chain(), internal_feature_write(), is_variable_true(), load_config(), load_config_meetme(), load_module(), load_modules(), load_moh_classes(), load_odbc_config(), load_users(), manager_add_queue_member(), manager_dialplan_extension_add(), manager_mutestream(), manager_pause_queue_member(), manager_queue_member_ringinuse(), mbl_load_adapter(), mbl_load_device(), message_template_build(), misdn_answer(), moh_parse_options(), my_load_module(), new_realtime_sqlite3_db(), odbc_load_module(), osp_load(), osplookup_exec(), parse_config(), parse_empty_options(), parse_playtone(), pbx_builtin_saycharacters(), pbx_builtin_saycharacters_case(), pbx_builtin_saydigits(), pbx_builtin_saynumber(), pbx_builtin_sayphonetic(), pbx_load_config(), pbx_load_users(), prack_handler(), process_dahdi(), process_echocancel(), process_my_load_module(), queue_rules_set_global_params(), queue_set_global_params(), queue_set_param(), realtime_directory(), reload_config(), reload_single_member(), rt_handle_member_record(), rtp_reload(), run_agi(), run_startup_commands(), sayunixtime_exec(), 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(), timers_handler(), transport_tls_bool_handler(), and xfer_set().

01673 {
01674    if (ast_strlen_zero(s))
01675       return 0;
01676 
01677    /* Determine if this is a true value */
01678    if (!strcasecmp(s, "yes") ||
01679        !strcasecmp(s, "true") ||
01680        !strcasecmp(s, "y") ||
01681        !strcasecmp(s, "t") ||
01682        !strcasecmp(s, "1") ||
01683        !strcasecmp(s, "on"))
01684       return -1;
01685 
01686    return 0;
01687 }

struct timeval ast_tvadd ( struct timeval  a,
struct timeval  b 
) [read]

struct timeval ast_tvsub ( struct timeval  a,
struct timeval  b 
) [read]

Returns the difference of two timevals a - b.

Definition at line 1740 of file main/utils.c.

References a, b, ONE_MILLION, and tvfix().

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

01741 {
01742    /* consistency checks to guarantee usec in 0..999999 */
01743    a = tvfix(a);
01744    b = tvfix(b);
01745    a.tv_sec -= b.tv_sec;
01746    a.tv_usec -= b.tv_usec;
01747    if (a.tv_usec < 0) {
01748       a.tv_sec-- ;
01749       a.tv_usec += ONE_MILLION;
01750    }
01751    return a;
01752 }

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 1586 of file main/utils.c.

References c, and NULL.

Referenced by ast_parse_digest().

01587 {
01588    char c, *ret, *dst;
01589 
01590    if (src == NULL)
01591       return NULL;
01592    for (ret = dst = src; (c = *src++); *dst++ = c ) {
01593       if (c != '\\')
01594          continue;   /* copy char at the end of the loop */
01595       switch ((c = *src++)) {
01596       case '\0':  /* special, trailing '\' */
01597          c = '\\';
01598          break;
01599       case 'b':   /* backspace */
01600          c = '\b';
01601          break;
01602       case 'f':   /* form feed */
01603          c = '\f';
01604          break;
01605       case 'n':
01606          c = '\n';
01607          break;
01608       case 'r':
01609          c = '\r';
01610          break;
01611       case 't':
01612          c = '\t';
01613          break;
01614       }
01615       /* default, use the char literally */
01616    }
01617    *dst = '\0';
01618    return ret;
01619 }

void ast_unescape_quoted ( char *  quote_str  ) 

Unescape quotes in a string.

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

Definition at line 518 of file main/utils.c.

Referenced by ast_callerid_parse(), ast_strsep(), and AST_TEST_DEFINE().

00519 {
00520    int esc_pos;
00521    int unesc_pos;
00522    int quote_str_len = strlen(quote_str);
00523 
00524    for (esc_pos = 0, unesc_pos = 0;
00525       esc_pos < quote_str_len;
00526       esc_pos++, unesc_pos++) {
00527       if (quote_str[esc_pos] == '\\') {
00528          /* at least one more char and current is \\ */
00529          esc_pos++;
00530          if (esc_pos >= quote_str_len) {
00531             break;
00532          }
00533       }
00534 
00535       quote_str[unesc_pos] = quote_str[esc_pos];
00536    }
00537    quote_str[unesc_pos] = '\0';
00538 }

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 1567 of file main/utils.c.

Referenced by sip_cli_notify().

01568 {
01569    char *e;
01570    char *work = s;
01571 
01572    while ((e = strchr(work, ';'))) {
01573       if ((e > work) && (*(e-1) == '\\')) {
01574          memmove(e - 1, e, strlen(e) + 1);
01575          work = e;
01576       } else {
01577          work = e + 1;
01578       }
01579    }
01580 
01581    return s;
01582 }

void ast_uri_decode ( char *  s,
struct ast_flags  spec 
)

Decode URI, URN, URL (overwrite string).

Note:
The ast_uri_http_legacy decode spec flag will cause this function to decode '+' as ' '.
Parameters:
s string to be decoded
spec flags describing how the decoding should be performed

Definition at line 438 of file main/utils.c.

References ast_test_flag, AST_URI_LEGACY_SPACE, and tmp().

Referenced by acf_curl_helper(), ast_ari_invoke(), ast_http_get_post_vars(), AST_TEST_DEFINE(), config_curl(), get_destination(), get_name_and_number(), get_refer_info(), handle_request_invite(), handle_uri(), parse_moved_contact(), realtime_curl(), realtime_multi_curl(), sip_new(), sip_uri_cmp(), and uridecode().

00439 {
00440    char *o;
00441    unsigned int tmp;
00442 
00443    for (o = s; *s; s++, o++) {
00444       if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *s == '+') {
00445          /* legacy mode, decode '+' as space */
00446          *o = ' ';
00447       } else if (*s == '%' && s[1] != '\0' && s[2] != '\0' && sscanf(s + 1, "%2x", &tmp) == 1) {
00448          /* have '%', two chars and correct parsing */
00449          *o = tmp;
00450          s += 2;  /* Will be incremented once more when we break out */
00451       } else /* all other cases, just copy */
00452          *o = *s;
00453    }
00454    *o = '\0';
00455 }

char* ast_uri_encode ( const char *  string,
char *  outbuf,
int  buflen,
struct ast_flags  spec 
)

Turn text string to URI-encoded XX version.

This function encodes characters according to the rules presented in RFC 2396 and/or RFC 3261 section 19.1.2 and section 25.1.

Outbuf needs to have more memory allocated than the instring to have room for the expansion. Every byte that is converted is replaced by three ASCII characters.

Parameters:
string string to be converted
outbuf resulting encoded string
buflen size of output buffer
spec flags describing how the encoding should be performed
Returns:
a pointer to the uri encoded string

Definition at line 399 of file main/utils.c.

References ast_test_flag, AST_URI_ALPHANUM, AST_URI_LEGACY_SPACE, AST_URI_MARK, AST_URI_SIP_USER_UNRESERVED, and out.

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

00400 {
00401    const char *ptr  = string; /* Start with the string */
00402    char *out = outbuf;
00403    const char *mark = "-_.!~*'()"; /* no encode set, RFC 2396 section 2.3, RFC 3261 sec 25 */
00404    const char *user_unreserved = "&=+$,;?/"; /* user-unreserved set, RFC 3261 sec 25 */
00405 
00406    while (*ptr && out - outbuf < buflen - 1) {
00407       if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *ptr == ' ') {
00408          /* for legacy encoding, encode spaces as '+' */
00409          *out = '+';
00410          out++;
00411       } else if (!(ast_test_flag(&spec, AST_URI_MARK)
00412             && strchr(mark, *ptr))
00413          && !(ast_test_flag(&spec, AST_URI_ALPHANUM)
00414             && ((*ptr >= '0' && *ptr <= '9')
00415             || (*ptr >= 'A' && *ptr <= 'Z')
00416             || (*ptr >= 'a' && *ptr <= 'z')))
00417          && !(ast_test_flag(&spec, AST_URI_SIP_USER_UNRESERVED)
00418             && strchr(user_unreserved, *ptr))) {
00419 
00420          if (out - outbuf >= buflen - 3) {
00421             break;
00422          }
00423          out += sprintf(out, "%%%02hhX", (unsigned char) *ptr);
00424       } else {
00425          *out = *ptr;   /* Continue copying the string */
00426          out++;
00427       }
00428       ptr++;
00429    }
00430 
00431    if (buflen) {
00432       *out = '\0';
00433    }
00434 
00435    return outbuf;
00436 }

int ast_utils_init ( void   ) 

Definition at line 2470 of file main/utils.c.

References ARRAY_LEN, ast_cli_register_multiple(), ast_register_cleanup(), base64_init(), and utils_shutdown().

Referenced by main().

02471 {
02472    dev_urandom_fd = open("/dev/urandom", O_RDONLY);
02473    base64_init();
02474 #ifdef DEBUG_THREADS
02475 #if !defined(LOW_MEMORY)
02476    ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
02477 #endif
02478 #endif
02479    ast_register_cleanup(utils_shutdown);
02480    return 0;
02481 }

char* ast_utils_which ( const char *  binary,
char *  fullpath,
size_t  fullpath_size 
)

Resolve a binary to a full pathname.

Parameters:
binary Name of the executable to resolve
fullpath Buffer to hold the complete pathname
fullpath_size Size of fullpath
Return values:
NULL binary was not found or the environment variable PATH is not set
Returns:
fullpath

Definition at line 2639 of file main/utils.c.

References ast_strdupa, NULL, and strsep().

02640 {
02641    const char *envPATH = getenv("PATH");
02642    char *tpath, *path;
02643    struct stat unused;
02644    if (!envPATH) {
02645       return NULL;
02646    }
02647    tpath = ast_strdupa(envPATH);
02648    while ((path = strsep(&tpath, ":"))) {
02649       snprintf(fullpath, fullpath_size, "%s/%s", path, binary);
02650       if (!stat(fullpath, &unused)) {
02651          return fullpath;
02652       }
02653    }
02654    return NULL;
02655 }

int ast_wait_for_input ( int  fd,
int  ms 
)

Definition at line 1314 of file main/utils.c.

References ast_poll.

Referenced by action_waitevent(), ast_ari_websocket_session_read(), ast_tcptls_server_root(), dahdi_test_timer(), get_input(), moh_class_destructor(), sip_tcptls_read(), sip_websocket_callback(), tcptls_stream_read(), tcptls_stream_write(), unbound_resolver_thread(), websocket_cb(), websocket_echo_callback(), and ws_safe_read().

01315 {
01316    struct pollfd pfd[1];
01317 
01318    memset(pfd, 0, sizeof(pfd));
01319    pfd[0].fd = fd;
01320    pfd[0].events = POLLIN | POLLPRI;
01321    return ast_poll(pfd, 1, ms);
01322 }

int ast_wait_for_output ( int  fd,
int  ms 
)

Definition at line 1324 of file main/utils.c.

References ast_poll.

Referenced by tcptls_stream_read(), and tcptls_stream_write().

01325 {
01326    struct pollfd pfd[1];
01327 
01328    memset(pfd, 0, sizeof(pfd));
01329    pfd[0].fd = fd;
01330    pfd[0].events = POLLOUT;
01331    return ast_poll(pfd, 1, ms);
01332 }

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:
string String to be converted
outbuf Resulting encoded string
buflen Size of output buffer
Returns:
0 for success

-1 if buflen is too short.

Definition at line 540 of file main/utils.c.

References ast_assert, end, entity, len(), and NULL.

Referenced by ast_http_create_response(), state_notify_build_xml(), and test_xml().

00541 {
00542    char *dst = outbuf;
00543    char *end = outbuf + buflen - 1; /* save one for the null terminator */
00544 
00545    /* Handle the case for the empty output buffer */
00546    if (buflen == 0) {
00547       return -1;
00548    }
00549 
00550    /* Escaping rules from http://www.w3.org/TR/REC-xml/#syntax */
00551    /* This also prevents partial entities at the end of a string */
00552    while (*string && dst < end) {
00553       const char *entity = NULL;
00554       int len = 0;
00555 
00556       switch (*string) {
00557       case '<':
00558          entity = "&lt;";
00559          len = 4;
00560          break;
00561       case '&':
00562          entity = "&amp;";
00563          len = 5;
00564          break;
00565       case '>':
00566          /* necessary if ]]> is in the string; easier to escape them all */
00567          entity = "&gt;";
00568          len = 4;
00569          break;
00570       case '\'':
00571          /* necessary in single-quoted strings; easier to escape them all */
00572          entity = "&apos;";
00573          len = 6;
00574          break;
00575       case '"':
00576          /* necessary in double-quoted strings; easier to escape them all */
00577          entity = "&quot;";
00578          len = 6;
00579          break;
00580       default:
00581          *dst++ = *string++;
00582          break;
00583       }
00584 
00585       if (entity) {
00586          ast_assert(len == strlen(entity));
00587          if (end - dst < len) {
00588             /* no room for the entity; stop */
00589             break;
00590          }
00591          /* just checked for length; strcpy is fine */
00592          strcpy(dst, entity);
00593          dst += len;
00594          ++string;
00595       }
00596    }
00597    /* Write null terminator */
00598    *dst = '\0';
00599    /* If any chars are left in string, return failure */
00600    return *string == '\0' ? 0 : -1;
00601 }

static void base64_init ( void   )  [static]

Definition at line 371 of file main/utils.c.

Referenced by ast_utils_init().

00372 {
00373    int x;
00374    memset(b2a, -1, sizeof(b2a));
00375    /* Initialize base-64 Conversion table */
00376    for (x = 0; x < 26; x++) {
00377       /* A-Z */
00378       base64[x] = 'A' + x;
00379       b2a['A' + x] = x;
00380       /* a-z */
00381       base64[x + 26] = 'a' + x;
00382       b2a['a' + x] = x + 26;
00383       /* 0-9 */
00384       if (x < 10) {
00385          base64[x + 52] = '0' + x;
00386          b2a['0' + x] = x + 52;
00387       }
00388    }
00389    base64[62] = '+';
00390    base64[63] = '/';
00391    b2a[(int)'+'] = 62;
00392    b2a[(int)'/'] = 63;
00393 }

static void* dummy_start ( void *  data  )  [static]

Definition at line 1198 of file main/utils.c.

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

Referenced by ast_pthread_create_stack().

01199 {
01200    void *ret;
01201    struct thr_arg a = *((struct thr_arg *) data);  /* make a local copy */
01202 #ifdef DEBUG_THREADS
01203    struct thr_lock_info *lock_info;
01204    pthread_mutexattr_t mutex_attr;
01205 
01206    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
01207       return NULL;
01208 
01209    lock_info->thread_id = pthread_self();
01210    lock_info->lwp = ast_get_tid();
01211    lock_info->thread_name = strdup(a.name);
01212 
01213    pthread_mutexattr_init(&mutex_attr);
01214    pthread_mutexattr_settype(&mutex_attr, AST_MUTEX_KIND);
01215    pthread_mutex_init(&lock_info->lock, &mutex_attr);
01216    pthread_mutexattr_destroy(&mutex_attr);
01217 
01218    pthread_mutex_lock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
01219    AST_LIST_INSERT_TAIL(&lock_infos, lock_info, entry);
01220    pthread_mutex_unlock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
01221 #endif /* DEBUG_THREADS */
01222 
01223    /* note that even though data->name is a pointer to allocated memory,
01224       we are not freeing it here because ast_register_thread is going to
01225       keep a copy of the pointer and then ast_unregister_thread will
01226       free the memory
01227    */
01228    ast_free(data);
01229    ast_register_thread(a.name);
01230    pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
01231 
01232    ret = a.start_routine(a.data);
01233 
01234    pthread_cleanup_pop(1);
01235 
01236    return ret;
01237 }

static int gethostbyname_r ( const char *  name,
struct hostent *  ret,
char *  buf,
size_t  buflen,
struct hostent **  result,
int *  h_errnop 
) [static]

Reentrant replacement for gethostbyname for BSD-based systems.

Note:
This routine is derived from code originally written and placed in the public domain by Enzo Michelangeli <em@em.no-ip.com>

Definition at line 92 of file main/utils.c.

References __mutex, ast_mutex_lock, ast_mutex_unlock, ERANGE, gethostbyname, and NULL.

Referenced by ast_gethostbyname().

00095 {
00096    int hsave;
00097    struct hostent *ph;
00098    ast_mutex_lock(&__mutex); /* begin critical area */
00099    hsave = h_errno;
00100 
00101    ph = gethostbyname(name);
00102    *h_errnop = h_errno; /* copy h_errno to *h_herrnop */
00103    if (ph == NULL) {
00104       *result = NULL;
00105    } else {
00106       char **p, **q;
00107       char *pbuf;
00108       int nbytes = 0;
00109       int naddr = 0, naliases = 0;
00110       /* determine if we have enough space in buf */
00111 
00112       /* count how many addresses */
00113       for (p = ph->h_addr_list; *p != 0; p++) {
00114          nbytes += ph->h_length; /* addresses */
00115          nbytes += sizeof(*p); /* pointers */
00116          naddr++;
00117       }
00118       nbytes += sizeof(*p); /* one more for the terminating NULL */
00119 
00120       /* count how many aliases, and total length of strings */
00121       for (p = ph->h_aliases; *p != 0; p++) {
00122          nbytes += (strlen(*p)+1); /* aliases */
00123          nbytes += sizeof(*p);  /* pointers */
00124          naliases++;
00125       }
00126       nbytes += sizeof(*p); /* one more for the terminating NULL */
00127 
00128       /* here nbytes is the number of bytes required in buffer */
00129       /* as a terminator must be there, the minimum value is ph->h_length */
00130       if (nbytes > buflen) {
00131          *result = NULL;
00132          ast_mutex_unlock(&__mutex); /* end critical area */
00133          return ERANGE; /* not enough space in buf!! */
00134       }
00135 
00136       /* There is enough space. Now we need to do a deep copy! */
00137       /* Allocation in buffer:
00138          from [0] to [(naddr-1) * sizeof(*p)]:
00139          pointers to addresses
00140          at [naddr * sizeof(*p)]:
00141          NULL
00142          from [(naddr+1) * sizeof(*p)] to [(naddr+naliases) * sizeof(*p)] :
00143          pointers to aliases
00144          at [(naddr+naliases+1) * sizeof(*p)]:
00145          NULL
00146          then naddr addresses (fixed length), and naliases aliases (asciiz).
00147       */
00148 
00149       *ret = *ph;   /* copy whole structure (not its address!) */
00150 
00151       /* copy addresses */
00152       q = (char **)buf; /* pointer to pointers area (type: char **) */
00153       ret->h_addr_list = q; /* update pointer to address list */
00154       pbuf = buf + ((naddr + naliases + 2) * sizeof(*p)); /* skip that area */
00155       for (p = ph->h_addr_list; *p != 0; p++) {
00156          memcpy(pbuf, *p, ph->h_length); /* copy address bytes */
00157          *q++ = pbuf; /* the pointer is the one inside buf... */
00158          pbuf += ph->h_length; /* advance pbuf */
00159       }
00160       *q++ = NULL; /* address list terminator */
00161 
00162       /* copy aliases */
00163       ret->h_aliases = q; /* update pointer to aliases list */
00164       for (p = ph->h_aliases; *p != 0; p++) {
00165          strcpy(pbuf, *p); /* copy alias strings */
00166          *q++ = pbuf; /* the pointer is the one inside buf... */
00167          pbuf += strlen(*p); /* advance pbuf */
00168          *pbuf++ = 0; /* string terminator */
00169       }
00170       *q++ = NULL; /* terminator */
00171 
00172       strcpy(pbuf, ph->h_name); /* copy alias strings */
00173       ret->h_name = pbuf;
00174       pbuf += strlen(ph->h_name); /* advance pbuf */
00175       *pbuf++ = 0; /* string terminator */
00176 
00177       *result = ret;  /* and let *result point to structure */
00178 
00179    }
00180    h_errno = hsave;  /* restore h_errno */
00181    ast_mutex_unlock(&__mutex); /* end critical area */
00182 
00183    return (*result == NULL); /* return 0 on success, non-zero on error */
00184 }

static size_t optimal_alloc_size ( size_t  size  )  [static]

Definition at line 1909 of file main/utils.c.

References ALLOCATOR_OVERHEAD.

Referenced by __ast_calloc_with_stringfields(), and add_string_pool().

01910 {
01911    unsigned int count;
01912 
01913    size += ALLOCATOR_OVERHEAD;
01914 
01915    for (count = 1; size; size >>= 1, count++);
01916 
01917    return (1 << count) - ALLOCATOR_OVERHEAD;
01918 }

static int safe_mkdir ( const char *  base_path,
char *  path,
int  mode 
) [static]

Definition at line 2367 of file main/utils.c.

References ast_assert, ast_begins_with(), ast_std_free, c, errno, NULL, and RAII_VAR.

Referenced by ast_safe_mkdir().

02368 {
02369    RAII_VAR(char *, absolute_path, NULL, ast_std_free);
02370 
02371    absolute_path = realpath(path, NULL);
02372 
02373    if (absolute_path) {
02374       /* Path exists, but is it in the right place? */
02375       if (!ast_begins_with(absolute_path, base_path)) {
02376          return EPERM;
02377       }
02378 
02379       /* It is in the right place! */
02380       return 0;
02381    } else {
02382       /* Path doesn't exist. */
02383 
02384       /* The slash terminating the subpath we're checking */
02385       char *path_term = strchr(path, '/');
02386       /* True indicates the parent path is within base_path */
02387       int parent_is_safe = 0;
02388       int res;
02389 
02390       while (path_term) {
02391          RAII_VAR(char *, absolute_subpath, NULL, ast_std_free);
02392 
02393          /* Truncate the path one past the slash */
02394          char c = *(path_term + 1);
02395          *(path_term + 1) = '\0';
02396          absolute_subpath = realpath(path, NULL);
02397 
02398          if (absolute_subpath) {
02399             /* Subpath exists, but is it safe? */
02400             parent_is_safe = ast_begins_with(
02401                absolute_subpath, base_path);
02402          } else if (parent_is_safe) {
02403             /* Subpath does not exist, but parent is safe
02404              * Create it */
02405             res = mkdir(path, mode);
02406             if (res != 0) {
02407                ast_assert(errno != EEXIST);
02408                return errno;
02409             }
02410          } else {
02411             /* Subpath did not exist, parent was not safe
02412              * Fail! */
02413             errno = EPERM;
02414             return errno;
02415          }
02416          /* Restore the path */
02417          *(path_term + 1) = c;
02418          /* Move on to the next slash */
02419          path_term = strchr(path_term + 1, '/');
02420       }
02421 
02422       /* Now to build the final path, but only if it's safe */
02423       if (!parent_is_safe) {
02424          errno = EPERM;
02425          return errno;
02426       }
02427 
02428       res = mkdir(path, mode);
02429       if (res != 0 && errno != EEXIST) {
02430          return errno;
02431       }
02432 
02433       return 0;
02434    }
02435 }

static struct timeval tvfix ( struct timeval  a  )  [static, read]

Definition at line 1711 of file main/utils.c.

References ast_log, LOG_WARNING, and ONE_MILLION.

Referenced by ast_tvadd(), and ast_tvsub().

01712 {
01713    if (a.tv_usec >= ONE_MILLION) {
01714       ast_log(LOG_WARNING, "warning too large timestamp %ld.%ld\n",
01715          (long)a.tv_sec, (long int) a.tv_usec);
01716       a.tv_sec += a.tv_usec / ONE_MILLION;
01717       a.tv_usec %= ONE_MILLION;
01718    } else if (a.tv_usec < 0) {
01719       ast_log(LOG_WARNING, "warning negative timestamp %ld.%ld\n",
01720          (long)a.tv_sec, (long int) a.tv_usec);
01721       a.tv_usec = 0;
01722    }
01723    return a;
01724 }

static void utils_shutdown ( void   )  [static]

Definition at line 2461 of file main/utils.c.

References ARRAY_LEN, and ast_cli_unregister_multiple().

Referenced by ast_utils_init().

02462 {
02463    close(dev_urandom_fd);
02464    dev_urandom_fd = -1;
02465 #if defined(DEBUG_THREADS) && !defined(LOW_MEMORY)
02466    ast_cli_unregister_multiple(utils_cli, ARRAY_LEN(utils_cli));
02467 #endif
02468 }

static int wait_for_output ( int  fd,
int  timeoutms 
) [static]

Definition at line 1334 of file main/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().

01335 {
01336    struct pollfd pfd = {
01337       .fd = fd,
01338       .events = POLLOUT,
01339    };
01340    int res;
01341    struct timeval start = ast_tvnow();
01342    int elapsed = 0;
01343 
01344    /* poll() until the fd is writable without blocking */
01345    while ((res = ast_poll(&pfd, 1, timeoutms - elapsed)) <= 0) {
01346       if (res == 0) {
01347          /* timed out. */
01348 #ifndef STANDALONE
01349          ast_debug(1, "Timed out trying to write\n");
01350 #endif
01351          return -1;
01352       } else if (res == -1) {
01353          /* poll() returned an error, check to see if it was fatal */
01354 
01355          if (errno == EINTR || errno == EAGAIN) {
01356             elapsed = ast_tvdiff_ms(ast_tvnow(), start);
01357             if (elapsed >= timeoutms) {
01358                return -1;
01359             }
01360             /* This was an acceptable error, go back into poll() */
01361             continue;
01362          }
01363 
01364          /* Fatal error, bail. */
01365          ast_log(LOG_ERROR, "poll returned error: %s\n", strerror(errno));
01366 
01367          return -1;
01368       }
01369       elapsed = ast_tvdiff_ms(ast_tvnow(), start);
01370       if (elapsed >= timeoutms) {
01371          return -1;
01372       }
01373    }
01374 
01375    return 0;
01376 }


Variable Documentation

Definition at line 1905 of file main/utils.c.

Referenced by AST_TEST_DEFINE().

struct { ... } __ast_string_field_empty_buffer [static]

ast_mutex_t __mutex = { PTHREAD_MUTEX_INITIALIZER , NULL, 1 } [static]

Definition at line 85 of file main/utils.c.

Referenced by gethostbyname_r().

Definition at line 1901 of file main/utils.c.

Referenced by __ast_calloc_with_stringfields().

struct ast_flags ast_uri_http = {AST_URI_UNRESERVED}

struct ast_flags ast_uri_http_legacy = {AST_URI_LEGACY_SPACE | AST_URI_UNRESERVED}

struct ast_flags ast_uri_sip_user = {AST_URI_UNRESERVED | AST_URI_SIP_USER_UNRESERVED}

char b2a[256] [static]

Definition at line 76 of file main/utils.c.

char base64[64] [static]

int dev_urandom_fd = -1 [static]

Definition at line 614 of file main/utils.c.

Referenced by ast_uuid_init().

ast_mutex_t fetchadd_m = { PTHREAD_MUTEX_INITIALIZER , NULL, 1 } [static]

Definition at line 2257 of file main/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 78 of file main/utils.c.

Referenced by ast_inet_ntoa().

ast_mutex_t randomlock = { PTHREAD_MUTEX_INITIALIZER , NULL, 1 } [static]

Definition at line 1782 of file main/utils.c.

Referenced by ast_random().

char string[1]

Definition at line 1902 of file main/utils.c.


Generated on Thu Apr 16 06:34:37 2015 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.6