Thu Jul 9 13:40:41 2009

Asterisk developer's documentation


utils.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * See http://www.asterisk.org for more information about
00007  * the Asterisk project. Please do not directly contact
00008  * any of the maintainers of this project for assistance;
00009  * the project provides a web site, mailing lists and IRC
00010  * channels for your use.
00011  *
00012  * This program is free software, distributed under the terms of
00013  * the GNU General Public License Version 2. See the LICENSE file
00014  * at the top of the source tree.
00015  */
00016 
00017 /*! \file
00018  *
00019  * \brief Utility functions
00020  *
00021  * \note These are important for portability and security,
00022  * so please use them in favour of other routines.
00023  * Please consult the CODING GUIDELINES for more information.
00024  */
00025 
00026 #include "asterisk.h"
00027 
00028 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 197539 $")
00029 
00030 #include <ctype.h>
00031 #include <sys/stat.h>
00032 
00033 #ifdef HAVE_DEV_URANDOM
00034 #include <fcntl.h>
00035 #endif
00036 
00037 #include "asterisk/network.h"
00038 
00039 #define AST_API_MODULE     /* ensure that inlinable API functions will be built in lock.h if required */
00040 #include "asterisk/lock.h"
00041 #include "asterisk/io.h"
00042 #include "asterisk/md5.h"
00043 #include "asterisk/sha1.h"
00044 #include "asterisk/cli.h"
00045 #include "asterisk/linkedlists.h"
00046 
00047 #define AST_API_MODULE     /* ensure that inlinable API functions will be built in this module if required */
00048 #include "asterisk/strings.h"
00049 
00050 #define AST_API_MODULE     /* ensure that inlinable API functions will be built in this module if required */
00051 #include "asterisk/time.h"
00052 
00053 #define AST_API_MODULE     /* ensure that inlinable API functions will be built in this module if required */
00054 #include "asterisk/stringfields.h"
00055 
00056 #define AST_API_MODULE     /* ensure that inlinable API functions will be built in this module if required */
00057 #include "asterisk/utils.h"
00058 
00059 #define AST_API_MODULE
00060 #include "asterisk/threadstorage.h"
00061 
00062 static char base64[64];
00063 static char b2a[256];
00064 
00065 AST_THREADSTORAGE(inet_ntoa_buf);
00066 
00067 #if !defined(HAVE_GETHOSTBYNAME_R_5) && !defined(HAVE_GETHOSTBYNAME_R_6)
00068 
00069 #define ERANGE 34 /*!< duh? ERANGE value copied from web... */
00070 #undef gethostbyname
00071 
00072 AST_MUTEX_DEFINE_STATIC(__mutex);
00073 
00074 /*! \brief Reentrant replacement for gethostbyname for BSD-based systems.
00075 \note This
00076 routine is derived from code originally written and placed in the public 
00077 domain by Enzo Michelangeli <em@em.no-ip.com> */
00078 
00079 static int gethostbyname_r (const char *name, struct hostent *ret, char *buf,
00080             size_t buflen, struct hostent **result, 
00081             int *h_errnop) 
00082 {
00083    int hsave;
00084    struct hostent *ph;
00085    ast_mutex_lock(&__mutex); /* begin critical area */
00086    hsave = h_errno;
00087 
00088    ph = gethostbyname(name);
00089    *h_errnop = h_errno; /* copy h_errno to *h_herrnop */
00090    if (ph == NULL) {
00091       *result = NULL;
00092    } else {
00093       char **p, **q;
00094       char *pbuf;
00095       int nbytes = 0;
00096       int naddr = 0, naliases = 0;
00097       /* determine if we have enough space in buf */
00098 
00099       /* count how many addresses */
00100       for (p = ph->h_addr_list; *p != 0; p++) {
00101          nbytes += ph->h_length; /* addresses */
00102          nbytes += sizeof(*p); /* pointers */
00103          naddr++;
00104       }
00105       nbytes += sizeof(*p); /* one more for the terminating NULL */
00106 
00107       /* count how many aliases, and total length of strings */
00108       for (p = ph->h_aliases; *p != 0; p++) {
00109          nbytes += (strlen(*p)+1); /* aliases */
00110          nbytes += sizeof(*p);  /* pointers */
00111          naliases++;
00112       }
00113       nbytes += sizeof(*p); /* one more for the terminating NULL */
00114 
00115       /* here nbytes is the number of bytes required in buffer */
00116       /* as a terminator must be there, the minimum value is ph->h_length */
00117       if (nbytes > buflen) {
00118          *result = NULL;
00119          ast_mutex_unlock(&__mutex); /* end critical area */
00120          return ERANGE; /* not enough space in buf!! */
00121       }
00122 
00123       /* There is enough space. Now we need to do a deep copy! */
00124       /* Allocation in buffer:
00125          from [0] to [(naddr-1) * sizeof(*p)]:
00126          pointers to addresses
00127          at [naddr * sizeof(*p)]:
00128          NULL
00129          from [(naddr+1) * sizeof(*p)] to [(naddr+naliases) * sizeof(*p)] :
00130          pointers to aliases
00131          at [(naddr+naliases+1) * sizeof(*p)]:
00132          NULL
00133          then naddr addresses (fixed length), and naliases aliases (asciiz).
00134       */
00135 
00136       *ret = *ph;   /* copy whole structure (not its address!) */
00137 
00138       /* copy addresses */
00139       q = (char **)buf; /* pointer to pointers area (type: char **) */
00140       ret->h_addr_list = q; /* update pointer to address list */
00141       pbuf = buf + ((naddr + naliases + 2) * sizeof(*p)); /* skip that area */
00142       for (p = ph->h_addr_list; *p != 0; p++) {
00143          memcpy(pbuf, *p, ph->h_length); /* copy address bytes */
00144          *q++ = pbuf; /* the pointer is the one inside buf... */
00145          pbuf += ph->h_length; /* advance pbuf */
00146       }
00147       *q++ = NULL; /* address list terminator */
00148 
00149       /* copy aliases */
00150       ret->h_aliases = q; /* update pointer to aliases list */
00151       for (p = ph->h_aliases; *p != 0; p++) {
00152          strcpy(pbuf, *p); /* copy alias strings */
00153          *q++ = pbuf; /* the pointer is the one inside buf... */
00154          pbuf += strlen(*p); /* advance pbuf */
00155          *pbuf++ = 0; /* string terminator */
00156       }
00157       *q++ = NULL; /* terminator */
00158 
00159       strcpy(pbuf, ph->h_name); /* copy alias strings */
00160       ret->h_name = pbuf;
00161       pbuf += strlen(ph->h_name); /* advance pbuf */
00162       *pbuf++ = 0; /* string terminator */
00163 
00164       *result = ret;  /* and let *result point to structure */
00165 
00166    }
00167    h_errno = hsave;  /* restore h_errno */
00168    ast_mutex_unlock(&__mutex); /* end critical area */
00169 
00170    return (*result == NULL); /* return 0 on success, non-zero on error */
00171 }
00172 
00173 
00174 #endif
00175 
00176 /*! \brief Re-entrant (thread safe) version of gethostbyname that replaces the 
00177    standard gethostbyname (which is not thread safe)
00178 */
00179 struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp)
00180 {
00181    int res;
00182    int herrno;
00183    int dots = 0;
00184    const char *s;
00185    struct hostent *result = NULL;
00186    /* Although it is perfectly legitimate to lookup a pure integer, for
00187       the sake of the sanity of people who like to name their peers as
00188       integers, we break with tradition and refuse to look up a
00189       pure integer */
00190    s = host;
00191    res = 0;
00192    while (s && *s) {
00193       if (*s == '.')
00194          dots++;
00195       else if (!isdigit(*s))
00196          break;
00197       s++;
00198    }
00199    if (!s || !*s) {
00200       /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
00201       if (dots != 3)
00202          return NULL;
00203       memset(hp, 0, sizeof(struct ast_hostent));
00204       hp->hp.h_addrtype = AF_INET;
00205       hp->hp.h_addr_list = (void *) hp->buf;
00206       hp->hp.h_addr = hp->buf + sizeof(void *);
00207       if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
00208          return &hp->hp;
00209       return NULL;
00210       
00211    }
00212 #ifdef HAVE_GETHOSTBYNAME_R_5
00213    result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);
00214 
00215    if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
00216       return NULL;
00217 #else
00218    res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
00219 
00220    if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
00221       return NULL;
00222 #endif
00223    return &hp->hp;
00224 }
00225 
00226 /*! \brief Produce 32 char MD5 hash of value. */
00227 void ast_md5_hash(char *output, char *input)
00228 {
00229    struct MD5Context md5;
00230    unsigned char digest[16];
00231    char *ptr;
00232    int x;
00233 
00234    MD5Init(&md5);
00235    MD5Update(&md5, (unsigned char *)input, strlen(input));
00236    MD5Final(digest, &md5);
00237    ptr = output;
00238    for (x = 0; x < 16; x++)
00239       ptr += sprintf(ptr, "%2.2x", digest[x]);
00240 }
00241 
00242 /*! \brief Produce 40 char SHA1 hash of value. */
00243 void ast_sha1_hash(char *output, char *input)
00244 {
00245    struct SHA1Context sha;
00246    char *ptr;
00247    int x;
00248    uint8_t Message_Digest[20];
00249 
00250    SHA1Reset(&sha);
00251    
00252    SHA1Input(&sha, (const unsigned char *) input, strlen(input));
00253 
00254    SHA1Result(&sha, Message_Digest);
00255    ptr = output;
00256    for (x = 0; x < 20; x++)
00257       ptr += sprintf(ptr, "%2.2x", Message_Digest[x]);
00258 }
00259 
00260 /*! \brief decode BASE64 encoded text */
00261 int ast_base64decode(unsigned char *dst, const char *src, int max)
00262 {
00263    int cnt = 0;
00264    unsigned int byte = 0;
00265    unsigned int bits = 0;
00266    int incnt = 0;
00267    while (*src && (cnt < max)) {
00268       /* Shift in 6 bits of input */
00269       byte <<= 6;
00270       byte |= (b2a[(int)(*src)]) & 0x3f;
00271       bits += 6;
00272       src++;
00273       incnt++;
00274       /* If we have at least 8 bits left over, take that character 
00275          off the top */
00276       if (bits >= 8)  {
00277          bits -= 8;
00278          *dst = (byte >> bits) & 0xff;
00279          dst++;
00280          cnt++;
00281       }
00282    }
00283    /* Dont worry about left over bits, they're extra anyway */
00284    return cnt;
00285 }
00286 
00287 /*! \brief encode text to BASE64 coding */
00288 int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
00289 {
00290    int cnt = 0;
00291    int col = 0;
00292    unsigned int byte = 0;
00293    int bits = 0;
00294    int cntin = 0;
00295    /* Reserve space for null byte at end of string */
00296    max--;
00297    while ((cntin < srclen) && (cnt < max)) {
00298       byte <<= 8;
00299       byte |= *(src++);
00300       bits += 8;
00301       cntin++;
00302       if ((bits == 24) && (cnt + 4 <= max)) {
00303          *dst++ = base64[(byte >> 18) & 0x3f];
00304          *dst++ = base64[(byte >> 12) & 0x3f];
00305          *dst++ = base64[(byte >> 6) & 0x3f];
00306          *dst++ = base64[byte & 0x3f];
00307          cnt += 4;
00308          col += 4;
00309          bits = 0;
00310          byte = 0;
00311       }
00312       if (linebreaks && (cnt < max) && (col == 64)) {
00313          *dst++ = '\n';
00314          cnt++;
00315          col = 0;
00316       }
00317    }
00318    if (bits && (cnt + 4 <= max)) {
00319       /* Add one last character for the remaining bits, 
00320          padding the rest with 0 */
00321       byte <<= 24 - bits;
00322       *dst++ = base64[(byte >> 18) & 0x3f];
00323       *dst++ = base64[(byte >> 12) & 0x3f];
00324       if (bits == 16)
00325          *dst++ = base64[(byte >> 6) & 0x3f];
00326       else
00327          *dst++ = '=';
00328       *dst++ = '=';
00329       cnt += 4;
00330    }
00331    if (linebreaks && (cnt < max)) {
00332       *dst++ = '\n';
00333       cnt++;
00334    }
00335    *dst = '\0';
00336    return cnt;
00337 }
00338 
00339 int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
00340 {
00341    return ast_base64encode_full(dst, src, srclen, max, 0);
00342 }
00343 
00344 static void base64_init(void)
00345 {
00346    int x;
00347    memset(b2a, -1, sizeof(b2a));
00348    /* Initialize base-64 Conversion table */
00349    for (x = 0; x < 26; x++) {
00350       /* A-Z */
00351       base64[x] = 'A' + x;
00352       b2a['A' + x] = x;
00353       /* a-z */
00354       base64[x + 26] = 'a' + x;
00355       b2a['a' + x] = x + 26;
00356       /* 0-9 */
00357       if (x < 10) {
00358          base64[x + 52] = '0' + x;
00359          b2a['0' + x] = x + 52;
00360       }
00361    }
00362    base64[62] = '+';
00363    base64[63] = '/';
00364    b2a[(int)'+'] = 62;
00365    b2a[(int)'/'] = 63;
00366 }
00367 
00368 /*! \brief  ast_uri_encode: Turn text string to URI-encoded %XX version
00369 \note    At this point, we're converting from ISO-8859-x (8-bit), not UTF8
00370    as in the SIP protocol spec 
00371    If doreserved == 1 we will convert reserved characters also.
00372    RFC 2396, section 2.4
00373    outbuf needs to have more memory allocated than the instring
00374    to have room for the expansion. Every char that is converted
00375    is replaced by three ASCII characters.
00376 
00377    Note: The doreserved option is needed for replaces header in
00378    SIP transfers.
00379 */
00380 char *ast_uri_encode(const char *string, char *outbuf, int buflen, int doreserved) 
00381 {
00382    char *reserved = ";/?:@&=+$,# "; /* Reserved chars */
00383 
00384    const char *ptr  = string; /* Start with the string */
00385    char *out = NULL;
00386    char *buf = NULL;
00387 
00388    ast_copy_string(outbuf, string, buflen);
00389 
00390    /* If there's no characters to convert, just go through and don't do anything */
00391    while (*ptr) {
00392       if ((*ptr < 32 || (unsigned char) *ptr) > 127 || (doreserved && strchr(reserved, *ptr)) ) {
00393          /* Oops, we need to start working here */
00394          if (!buf) {
00395             buf = outbuf;
00396             out = buf + (ptr - string) ;  /* Set output ptr */
00397          }
00398          out += sprintf(out, "%%%02x", (unsigned char) *ptr);
00399       } else if (buf) {
00400          *out = *ptr;   /* Continue copying the string */
00401          out++;
00402       } 
00403       ptr++;
00404    }
00405    if (buf)
00406       *out = '\0';
00407    return outbuf;
00408 }
00409 
00410 /*! \brief  ast_uri_decode: Decode SIP URI, URN, URL (overwrite the string)  */
00411 void ast_uri_decode(char *s) 
00412 {
00413    char *o;
00414    unsigned int tmp;
00415 
00416    for (o = s; *s; s++, o++) {
00417       if (*s == '%' && strlen(s) > 2 && sscanf(s + 1, "%2x", &tmp) == 1) {
00418          /* have '%', two chars and correct parsing */
00419          *o = tmp;
00420          s += 2;  /* Will be incremented once more when we break out */
00421       } else /* all other cases, just copy */
00422          *o = *s;
00423    }
00424    *o = '\0';
00425 }
00426 
00427 /*! \brief  ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa */
00428 const char *ast_inet_ntoa(struct in_addr ia)
00429 {
00430    char *buf;
00431 
00432    if (!(buf = ast_threadstorage_get(&inet_ntoa_buf, INET_ADDRSTRLEN)))
00433       return "";
00434 
00435    return inet_ntop(AF_INET, &ia, buf, INET_ADDRSTRLEN);
00436 }
00437 
00438 #ifdef HAVE_DEV_URANDOM
00439 static int dev_urandom_fd;
00440 #endif
00441 
00442 #ifndef __linux__
00443 #undef pthread_create /* For ast_pthread_create function only */
00444 #endif /* !__linux__ */
00445 
00446 #if !defined(LOW_MEMORY)
00447 
00448 #ifdef DEBUG_THREADS
00449 
00450 /*! \brief A reasonable maximum number of locks a thread would be holding ... */
00451 #define AST_MAX_LOCKS 64
00452 
00453 /* Allow direct use of pthread_mutex_t and friends */
00454 #undef pthread_mutex_t
00455 #undef pthread_mutex_lock
00456 #undef pthread_mutex_unlock
00457 #undef pthread_mutex_init
00458 #undef pthread_mutex_destroy
00459 
00460 /*! 
00461  * \brief Keep track of which locks a thread holds 
00462  *
00463  * There is an instance of this struct for every active thread
00464  */
00465 struct thr_lock_info {
00466    /*! The thread's ID */
00467    pthread_t thread_id;
00468    /*! The thread name which includes where the thread was started */
00469    const char *thread_name;
00470    /*! This is the actual container of info for what locks this thread holds */
00471    struct {
00472       const char *file;
00473       int line_num;
00474       const char *func;
00475       const char *lock_name;
00476       void *lock_addr;
00477       int times_locked;
00478       enum ast_lock_type type;
00479       /*! This thread is waiting on this lock */
00480       int pending:2;
00481    } locks[AST_MAX_LOCKS];
00482    /*! This is the number of locks currently held by this thread.
00483     *  The index (num_locks - 1) has the info on the last one in the
00484     *  locks member */
00485    unsigned int num_locks;
00486    /*! Protects the contents of the locks member 
00487     * Intentionally not ast_mutex_t */
00488    pthread_mutex_t lock;
00489    AST_LIST_ENTRY(thr_lock_info) entry;
00490 };
00491 
00492 /*! 
00493  * \brief Locked when accessing the lock_infos list 
00494  */
00495 AST_MUTEX_DEFINE_STATIC(lock_infos_lock);
00496 /*!
00497  * \brief A list of each thread's lock info 
00498  */
00499 static AST_LIST_HEAD_NOLOCK_STATIC(lock_infos, thr_lock_info);
00500 
00501 /*!
00502  * \brief Destroy a thread's lock info
00503  *
00504  * This gets called automatically when the thread stops
00505  */
00506 static void lock_info_destroy(void *data)
00507 {
00508    struct thr_lock_info *lock_info = data;
00509    int i;
00510 
00511    pthread_mutex_lock(&lock_infos_lock.mutex);
00512    AST_LIST_REMOVE(&lock_infos, lock_info, entry);
00513    pthread_mutex_unlock(&lock_infos_lock.mutex);
00514 
00515 
00516    for (i = 0; i < lock_info->num_locks; i++) {
00517       if (lock_info->locks[i].pending == -1) {
00518          /* This just means that the last lock this thread went for was by
00519           * using trylock, and it failed.  This is fine. */
00520          break;
00521       }
00522 
00523       ast_log(LOG_ERROR, 
00524          "Thread '%s' still has a lock! - '%s' (%p) from '%s' in %s:%d!\n", 
00525          lock_info->thread_name,
00526          lock_info->locks[i].lock_name,
00527          lock_info->locks[i].lock_addr,
00528          lock_info->locks[i].func,
00529          lock_info->locks[i].file,
00530          lock_info->locks[i].line_num
00531       );
00532    }
00533 
00534    pthread_mutex_destroy(&lock_info->lock);
00535    if (lock_info->thread_name)
00536       free((void *) lock_info->thread_name);
00537    free(lock_info);
00538 }
00539 
00540 /*!
00541  * \brief The thread storage key for per-thread lock info
00542  */
00543 AST_THREADSTORAGE_CUSTOM(thread_lock_info, NULL, lock_info_destroy);
00544 
00545 void ast_store_lock_info(enum ast_lock_type type, const char *filename,
00546    int line_num, const char *func, const char *lock_name, void *lock_addr)
00547 {
00548    struct thr_lock_info *lock_info;
00549    int i;
00550 
00551    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
00552       return;
00553 
00554    pthread_mutex_lock(&lock_info->lock);
00555 
00556    for (i = 0; i < lock_info->num_locks; i++) {
00557       if (lock_info->locks[i].lock_addr == lock_addr) {
00558          lock_info->locks[i].times_locked++;
00559          pthread_mutex_unlock(&lock_info->lock);
00560          return;
00561       }
00562    }
00563 
00564    if (lock_info->num_locks == AST_MAX_LOCKS) {
00565       /* Can't use ast_log here, because it will cause infinite recursion */
00566       fprintf(stderr, "XXX ERROR XXX A thread holds more locks than '%d'."
00567          "  Increase AST_MAX_LOCKS!\n", AST_MAX_LOCKS);
00568       pthread_mutex_unlock(&lock_info->lock);
00569       return;
00570    }
00571 
00572    if (i && lock_info->locks[i - 1].pending == -1) {
00573       /* The last lock on the list was one that this thread tried to lock but
00574        * failed at doing so.  It has now moved on to something else, so remove
00575        * the old lock from the list. */
00576       i--;
00577       lock_info->num_locks--;
00578       memset(&lock_info->locks[i], 0, sizeof(lock_info->locks[0]));
00579    }
00580 
00581    lock_info->locks[i].file = filename;
00582    lock_info->locks[i].line_num = line_num;
00583    lock_info->locks[i].func = func;
00584    lock_info->locks[i].lock_name = lock_name;
00585    lock_info->locks[i].lock_addr = lock_addr;
00586    lock_info->locks[i].times_locked = 1;
00587    lock_info->locks[i].type = type;
00588    lock_info->locks[i].pending = 1;
00589    lock_info->num_locks++;
00590 
00591    pthread_mutex_unlock(&lock_info->lock);
00592 }
00593 
00594 void ast_mark_lock_acquired(void *lock_addr)
00595 {
00596    struct thr_lock_info *lock_info;
00597 
00598    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
00599       return;
00600 
00601    pthread_mutex_lock(&lock_info->lock);
00602    if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
00603       lock_info->locks[lock_info->num_locks - 1].pending = 0;
00604    }
00605    pthread_mutex_unlock(&lock_info->lock);
00606 }
00607 
00608 void ast_mark_lock_failed(void *lock_addr)
00609 {
00610    struct thr_lock_info *lock_info;
00611 
00612    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
00613       return;
00614 
00615    pthread_mutex_lock(&lock_info->lock);
00616    if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
00617       lock_info->locks[lock_info->num_locks - 1].pending = -1;
00618       lock_info->locks[lock_info->num_locks - 1].times_locked--;
00619    }
00620    pthread_mutex_unlock(&lock_info->lock);
00621 }
00622 
00623 int ast_find_lock_info(void *lock_addr, char *filename, size_t filename_size, int *lineno, char *func, size_t func_size, char *mutex_name, size_t mutex_name_size)
00624 {
00625    struct thr_lock_info *lock_info;
00626    int i = 0;
00627 
00628    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
00629       return -1;
00630 
00631    pthread_mutex_lock(&lock_info->lock);
00632 
00633    for (i = lock_info->num_locks - 1; i >= 0; i--) {
00634       if (lock_info->locks[i].lock_addr == lock_addr)
00635          break;
00636    }
00637 
00638    if (i == -1) {
00639       /* Lock not found :( */
00640       pthread_mutex_unlock(&lock_info->lock);
00641       return -1;
00642    }
00643 
00644    ast_copy_string(filename, lock_info->locks[i].file, filename_size);
00645    *lineno = lock_info->locks[i].line_num;
00646    ast_copy_string(func, lock_info->locks[i].func, func_size);
00647    ast_copy_string(mutex_name, lock_info->locks[i].lock_name, mutex_name_size);
00648 
00649    pthread_mutex_unlock(&lock_info->lock);
00650 
00651    return 0;
00652 }
00653 
00654 void ast_remove_lock_info(void *lock_addr)
00655 {
00656    struct thr_lock_info *lock_info;
00657    int i = 0;
00658 
00659    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
00660       return;
00661 
00662    pthread_mutex_lock(&lock_info->lock);
00663 
00664    for (i = lock_info->num_locks - 1; i >= 0; i--) {
00665       if (lock_info->locks[i].lock_addr == lock_addr)
00666          break;
00667    }
00668 
00669    if (i == -1) {
00670       /* Lock not found :( */
00671       pthread_mutex_unlock(&lock_info->lock);
00672       return;
00673    }
00674 
00675    if (lock_info->locks[i].times_locked > 1) {
00676       lock_info->locks[i].times_locked--;
00677       pthread_mutex_unlock(&lock_info->lock);
00678       return;
00679    }
00680 
00681    if (i < lock_info->num_locks - 1) {
00682       /* Not the last one ... *should* be rare! */
00683       memmove(&lock_info->locks[i], &lock_info->locks[i + 1], 
00684          (lock_info->num_locks - (i + 1)) * sizeof(lock_info->locks[0]));
00685    }
00686 
00687    lock_info->num_locks--;
00688 
00689    pthread_mutex_unlock(&lock_info->lock);
00690 }
00691 
00692 static const char *locktype2str(enum ast_lock_type type)
00693 {
00694    switch (type) {
00695    case AST_MUTEX:
00696       return "MUTEX";
00697    case AST_RDLOCK:
00698       return "RDLOCK";
00699    case AST_WRLOCK:
00700       return "WRLOCK";
00701    }
00702 
00703    return "UNKNOWN";
00704 }
00705 
00706 static char *handle_show_locks(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00707 {
00708    struct thr_lock_info *lock_info;
00709    struct ast_str *str;
00710 
00711    if (!(str = ast_str_create(4096)))
00712       return CLI_FAILURE;
00713 
00714    switch (cmd) {
00715    case CLI_INIT:
00716       e->command = "core show locks";
00717       e->usage =
00718          "Usage: core show locks\n"
00719          "       This command is for lock debugging.  It prints out which locks\n"
00720          "are owned by each active thread.\n";
00721       return NULL;
00722 
00723    case CLI_GENERATE:
00724       return NULL;
00725    }
00726 
00727    ast_str_append(&str, 0, "\n" 
00728                   "=======================================================================\n"
00729                   "=== Currently Held Locks ==============================================\n"
00730                   "=======================================================================\n"
00731                   "===\n"
00732                   "=== <file> <line num> <function> <lock name> <lock addr> (times locked)\n"
00733                   "===\n");
00734 
00735    if (!str)
00736       return CLI_FAILURE;
00737 
00738    pthread_mutex_lock(&lock_infos_lock.mutex);
00739    AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
00740       int i;
00741       if (lock_info->num_locks) {
00742          ast_str_append(&str, 0, "=== Thread ID: %d (%s)\n", (int) lock_info->thread_id,
00743             lock_info->thread_name);
00744          pthread_mutex_lock(&lock_info->lock);
00745          for (i = 0; str && i < lock_info->num_locks; i++) {
00746             int j;
00747             ast_mutex_t *lock;
00748 
00749             ast_str_append(&str, 0, "=== ---> %sLock #%d (%s): %s %d %s %s %p (%d)\n", 
00750                lock_info->locks[i].pending > 0 ? "Waiting for " : 
00751                   lock_info->locks[i].pending < 0 ? "Tried and failed to get " : "", i,
00752                lock_info->locks[i].file, 
00753                locktype2str(lock_info->locks[i].type),
00754                lock_info->locks[i].line_num,
00755                lock_info->locks[i].func, lock_info->locks[i].lock_name,
00756                lock_info->locks[i].lock_addr, 
00757                lock_info->locks[i].times_locked);
00758 
00759             if (!lock_info->locks[i].pending || lock_info->locks[i].pending == -1)
00760                continue;
00761 
00762             /* We only have further details for mutexes right now */
00763             if (lock_info->locks[i].type != AST_MUTEX)
00764                continue;
00765 
00766             lock = lock_info->locks[i].lock_addr;
00767 
00768             ast_reentrancy_lock(lock);
00769             for (j = 0; str && j < lock->reentrancy; j++) {
00770                ast_str_append(&str, 0, "=== --- ---> Locked Here: %s line %d (%s)\n",
00771                   lock->file[j], lock->lineno[j], lock->func[j]);
00772             }
00773             ast_reentrancy_unlock(lock);  
00774          }
00775          pthread_mutex_unlock(&lock_info->lock);
00776          if (!str)
00777             break;
00778          ast_str_append(&str, 0, "=== -------------------------------------------------------------------\n"
00779                         "===\n");
00780          if (!str)
00781             break;
00782       }
00783    }
00784    pthread_mutex_unlock(&lock_infos_lock.mutex);
00785 
00786    if (!str)
00787       return CLI_FAILURE;
00788 
00789    ast_str_append(&str, 0, "=======================================================================\n"
00790                   "\n");
00791 
00792    if (!str)
00793       return CLI_FAILURE;
00794 
00795    ast_cli(a->fd, "%s", str->str);
00796 
00797    ast_free(str);
00798 
00799    return CLI_SUCCESS;
00800 }
00801 
00802 static struct ast_cli_entry utils_cli[] = {
00803    AST_CLI_DEFINE(handle_show_locks, "Show which locks are held by which thread"),
00804 };
00805 
00806 #endif /* DEBUG_THREADS */
00807 
00808 /*
00809  * support for 'show threads'. The start routine is wrapped by
00810  * dummy_start(), so that ast_register_thread() and
00811  * ast_unregister_thread() know the thread identifier.
00812  */
00813 struct thr_arg {
00814    void *(*start_routine)(void *);
00815    void *data;
00816    char *name;
00817 };
00818 
00819 /*
00820  * on OS/X, pthread_cleanup_push() and pthread_cleanup_pop()
00821  * are odd macros which start and end a block, so they _must_ be
00822  * used in pairs (the latter with a '1' argument to call the
00823  * handler on exit.
00824  * On BSD we don't need this, but we keep it for compatibility.
00825  */
00826 static void *dummy_start(void *data)
00827 {
00828    void *ret;
00829    struct thr_arg a = *((struct thr_arg *) data);  /* make a local copy */
00830 #ifdef DEBUG_THREADS
00831    struct thr_lock_info *lock_info;
00832    pthread_mutexattr_t mutex_attr;
00833 #endif
00834 
00835    /* note that even though data->name is a pointer to allocated memory,
00836       we are not freeing it here because ast_register_thread is going to
00837       keep a copy of the pointer and then ast_unregister_thread will
00838       free the memory
00839    */
00840    ast_free(data);
00841    ast_register_thread(a.name);
00842    pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
00843 
00844 #ifdef DEBUG_THREADS
00845    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
00846       return NULL;
00847 
00848    lock_info->thread_id = pthread_self();
00849    lock_info->thread_name = strdup(a.name);
00850 
00851    pthread_mutexattr_init(&mutex_attr);
00852    pthread_mutexattr_settype(&mutex_attr, AST_MUTEX_KIND);
00853    pthread_mutex_init(&lock_info->lock, &mutex_attr);
00854    pthread_mutexattr_destroy(&mutex_attr);
00855 
00856    pthread_mutex_lock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
00857    AST_LIST_INSERT_TAIL(&lock_infos, lock_info, entry);
00858    pthread_mutex_unlock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
00859 #endif /* DEBUG_THREADS */
00860 
00861    ret = a.start_routine(a.data);
00862 
00863    pthread_cleanup_pop(1);
00864 
00865    return ret;
00866 }
00867 
00868 #endif /* !LOW_MEMORY */
00869 
00870 int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
00871               void *data, size_t stacksize, const char *file, const char *caller,
00872               int line, const char *start_fn)
00873 {
00874 #if !defined(LOW_MEMORY)
00875    struct thr_arg *a;
00876 #endif
00877 
00878    if (!attr) {
00879       attr = alloca(sizeof(*attr));
00880       pthread_attr_init(attr);
00881    }
00882 
00883 #ifdef __linux__
00884    /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
00885       which is kind of useless. Change this here to
00886       PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
00887       priority will propagate down to new threads by default.
00888       This does mean that callers cannot set a different priority using
00889       PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
00890       the priority afterwards with pthread_setschedparam(). */
00891    if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
00892       ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
00893 #endif
00894 
00895    if (!stacksize)
00896       stacksize = AST_STACKSIZE;
00897 
00898    if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
00899       ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
00900 
00901 #if !defined(LOW_MEMORY)
00902    if ((a = ast_malloc(sizeof(*a)))) {
00903       a->start_routine = start_routine;
00904       a->data = data;
00905       start_routine = dummy_start;
00906       if (asprintf(&a->name, "%-20s started at [%5d] %s %s()",
00907               start_fn, line, file, caller) < 0) {
00908          ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
00909          a->name = NULL;
00910       }
00911       data = a;
00912    }
00913 #endif /* !LOW_MEMORY */
00914 
00915    return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
00916 }
00917 
00918 
00919 int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
00920               void *data, size_t stacksize, const char *file, const char *caller,
00921               int line, const char *start_fn)
00922 {
00923    unsigned char attr_destroy = 0;
00924    int res;
00925 
00926    if (!attr) {
00927       attr = alloca(sizeof(*attr));
00928       pthread_attr_init(attr);
00929       attr_destroy = 1;
00930    }
00931 
00932    if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
00933       ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
00934 
00935    res = ast_pthread_create_stack(thread, attr, start_routine, data, 
00936                                   stacksize, file, caller, line, start_fn);
00937 
00938    if (attr_destroy)
00939       pthread_attr_destroy(attr);
00940 
00941    return res;
00942 }
00943 
00944 int ast_wait_for_input(int fd, int ms)
00945 {
00946    struct pollfd pfd[1];
00947    memset(pfd, 0, sizeof(pfd));
00948    pfd[0].fd = fd;
00949    pfd[0].events = POLLIN|POLLPRI;
00950    return ast_poll(pfd, 1, ms);
00951 }
00952 
00953 static int ast_wait_for_output(int fd, int timeoutms)
00954 {
00955    struct pollfd pfd = {
00956       .fd = fd,
00957       .events = POLLOUT,
00958    };
00959    int res;
00960    struct timeval start = ast_tvnow();
00961    int elapsed = 0;
00962 
00963    /* poll() until the fd is writable without blocking */
00964    while ((res = ast_poll(&pfd, 1, timeoutms - elapsed)) <= 0) {
00965       if (res == 0) {
00966          /* timed out. */
00967          ast_log(LOG_NOTICE, "Timed out trying to write\n");
00968          return -1;
00969       } else if (res == -1) {
00970          /* poll() returned an error, check to see if it was fatal */
00971 
00972          if (errno == EINTR || errno == EAGAIN) {
00973             elapsed = ast_tvdiff_ms(ast_tvnow(), start);
00974             if (elapsed >= timeoutms) {
00975                return -1;
00976             }
00977             /* This was an acceptable error, go back into poll() */
00978             continue;
00979          }
00980 
00981          /* Fatal error, bail. */
00982          ast_log(LOG_ERROR, "poll returned error: %s\n", strerror(errno));
00983 
00984          return -1;
00985       }
00986       elapsed = ast_tvdiff_ms(ast_tvnow(), start);
00987       if (elapsed >= timeoutms) {
00988          return -1;
00989       }
00990    }
00991 
00992    return 0;
00993 }
00994 
00995 /*!
00996  * Try to write string, but wait no more than ms milliseconds before timing out.
00997  *
00998  * \note The code assumes that the file descriptor has NONBLOCK set,
00999  * so there is only one system call made to do a write, unless we actually
01000  * have a need to wait.  This way, we get better performance.
01001  * If the descriptor is blocking, all assumptions on the guaranteed
01002  * detail do not apply anymore.
01003  */
01004 int ast_carefulwrite(int fd, char *s, int len, int timeoutms) 
01005 {
01006    struct timeval start = ast_tvnow();
01007    int res = 0;
01008    int elapsed = 0;
01009 
01010    while (len) {
01011       if (ast_wait_for_output(fd, timeoutms - elapsed)) {
01012          return -1;
01013       }
01014 
01015       res = write(fd, s, len);
01016 
01017       if (res < 0 && errno != EAGAIN && errno != EINTR) {
01018          /* fatal error from write() */
01019          ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
01020          return -1;
01021       }
01022 
01023       if (res < 0) {
01024          /* It was an acceptable error */
01025          res = 0;
01026       }
01027 
01028       /* Update how much data we have left to write */
01029       len -= res;
01030       s += res;
01031       res = 0;
01032 
01033       elapsed = ast_tvdiff_ms(ast_tvnow(), start);
01034       if (elapsed >= timeoutms) {
01035          /* We've taken too long to write 
01036           * This is only an error condition if we haven't finished writing. */
01037          res = len ? -1 : 0;
01038          break;
01039       }
01040    }
01041 
01042    return res;
01043 }
01044 
01045 int ast_careful_fwrite(FILE *f, int fd, const char *src, size_t len, int timeoutms)
01046 {
01047    struct timeval start = ast_tvnow();
01048    int n = 0;
01049    int elapsed = 0;
01050 
01051    while (len) {
01052       if (ast_wait_for_output(fd, timeoutms - elapsed)) {
01053          /* poll returned a fatal error, so bail out immediately. */
01054          return -1;
01055       }
01056 
01057       /* Clear any errors from a previous write */
01058       clearerr(f);
01059 
01060       n = fwrite(src, 1, len, f);
01061 
01062       if (ferror(f) && errno != EINTR && errno != EAGAIN) {
01063          /* fatal error from fwrite() */
01064          if (!feof(f)) {
01065             /* Don't spam the logs if it was just that the connection is closed. */
01066             ast_log(LOG_ERROR, "fwrite() returned error: %s\n", strerror(errno));
01067          }
01068          n = -1;
01069          break;
01070       }
01071 
01072       /* Update for data already written to the socket */
01073       len -= n;
01074       src += n;
01075 
01076       elapsed = ast_tvdiff_ms(ast_tvnow(), start);
01077       if (elapsed >= timeoutms) {
01078          /* We've taken too long to write 
01079           * This is only an error condition if we haven't finished writing. */
01080          n = len ? -1 : 0;
01081          break;
01082       }
01083    }
01084 
01085    while (fflush(f)) {
01086       if (errno == EAGAIN || errno == EINTR) {
01087          continue;
01088       }
01089       if (!feof(f)) {
01090          /* Don't spam the logs if it was just that the connection is closed. */
01091          ast_log(LOG_ERROR, "fflush() returned error: %s\n", strerror(errno));
01092       }
01093       n = -1;
01094       break;
01095    }
01096 
01097    return n < 0 ? -1 : 0;
01098 }
01099 
01100 char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
01101 {
01102    char *e;
01103    char *q;
01104 
01105    s = ast_strip(s);
01106    if ((q = strchr(beg_quotes, *s)) && *q != '\0') {
01107       e = s + strlen(s) - 1;
01108       if (*e == *(end_quotes + (q - beg_quotes))) {
01109          s++;
01110          *e = '\0';
01111       }
01112    }
01113 
01114    return s;
01115 }
01116 
01117 char *ast_unescape_semicolon(char *s)
01118 {
01119    char *e;
01120    char *work = s;
01121 
01122    while ((e = strchr(work, ';'))) {
01123       if ((e > work) && (*(e-1) == '\\')) {
01124          memmove(e - 1, e, strlen(e) + 1);
01125          work = e;
01126       } else {
01127          work = e + 1;
01128       }
01129    }
01130 
01131    return s;
01132 }
01133 
01134 /* !\brief unescape some C sequences in place, return pointer to the original string.
01135  */
01136 char *ast_unescape_c(char *src)
01137 {
01138    char c, *ret, *dst;
01139 
01140    if (src == NULL)
01141       return NULL;
01142    for (ret = dst = src; (c = *src++); *dst++ = c ) {
01143       if (c != '\\')
01144          continue;   /* copy char at the end of the loop */
01145       switch ((c = *src++)) {
01146       case '\0':  /* special, trailing '\' */
01147          c = '\\';
01148          break;
01149       case 'b':   /* backspace */
01150          c = '\b';
01151          break;
01152       case 'f':   /* form feed */
01153          c = '\f';
01154          break;
01155       case 'n':
01156          c = '\n';
01157          break;
01158       case 'r':
01159          c = '\r';
01160          break;
01161       case 't':
01162          c = '\t';
01163          break;
01164       }
01165       /* default, use the char literally */
01166    }
01167    *dst = '\0';
01168    return ret;
01169 }
01170 
01171 int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap)
01172 {
01173    int result;
01174 
01175    if (!buffer || !*buffer || !space || !*space)
01176       return -1;
01177 
01178    result = vsnprintf(*buffer, *space, fmt, ap);
01179 
01180    if (result < 0)
01181       return -1;
01182    else if (result > *space)
01183       result = *space;
01184 
01185    *buffer += result;
01186    *space -= result;
01187    return 0;
01188 }
01189 
01190 int ast_build_string(char **buffer, size_t *space, const char *fmt, ...)
01191 {
01192    va_list ap;
01193    int result;
01194 
01195    va_start(ap, fmt);
01196    result = ast_build_string_va(buffer, space, fmt, ap);
01197    va_end(ap);
01198 
01199    return result;
01200 }
01201 
01202 int ast_true(const char *s)
01203 {
01204    if (ast_strlen_zero(s))
01205       return 0;
01206 
01207    /* Determine if this is a true value */
01208    if (!strcasecmp(s, "yes") ||
01209        !strcasecmp(s, "true") ||
01210        !strcasecmp(s, "y") ||
01211        !strcasecmp(s, "t") ||
01212        !strcasecmp(s, "1") ||
01213        !strcasecmp(s, "on"))
01214       return -1;
01215 
01216    return 0;
01217 }
01218 
01219 int ast_false(const char *s)
01220 {
01221    if (ast_strlen_zero(s))
01222       return 0;
01223 
01224    /* Determine if this is a false value */
01225    if (!strcasecmp(s, "no") ||
01226        !strcasecmp(s, "false") ||
01227        !strcasecmp(s, "n") ||
01228        !strcasecmp(s, "f") ||
01229        !strcasecmp(s, "0") ||
01230        !strcasecmp(s, "off"))
01231       return -1;
01232 
01233    return 0;
01234 }
01235 
01236 #define ONE_MILLION  1000000
01237 /*
01238  * put timeval in a valid range. usec is 0..999999
01239  * negative values are not allowed and truncated.
01240  */
01241 static struct timeval tvfix(struct timeval a)
01242 {
01243    if (a.tv_usec >= ONE_MILLION) {
01244       ast_log(LOG_WARNING, "warning too large timestamp %ld.%ld\n",
01245          a.tv_sec, (long int) a.tv_usec);
01246       a.tv_sec += a.tv_usec / ONE_MILLION;
01247       a.tv_usec %= ONE_MILLION;
01248    } else if (a.tv_usec < 0) {
01249       ast_log(LOG_WARNING, "warning negative timestamp %ld.%ld\n",
01250          a.tv_sec, (long int) a.tv_usec);
01251       a.tv_usec = 0;
01252    }
01253    return a;
01254 }
01255 
01256 struct timeval ast_tvadd(struct timeval a, struct timeval b)
01257 {
01258    /* consistency checks to guarantee usec in 0..999999 */
01259    a = tvfix(a);
01260    b = tvfix(b);
01261    a.tv_sec += b.tv_sec;
01262    a.tv_usec += b.tv_usec;
01263    if (a.tv_usec >= ONE_MILLION) {
01264       a.tv_sec++;
01265       a.tv_usec -= ONE_MILLION;
01266    }
01267    return a;
01268 }
01269 
01270 struct timeval ast_tvsub(struct timeval a, struct timeval b)
01271 {
01272    /* consistency checks to guarantee usec in 0..999999 */
01273    a = tvfix(a);
01274    b = tvfix(b);
01275    a.tv_sec -= b.tv_sec;
01276    a.tv_usec -= b.tv_usec;
01277    if (a.tv_usec < 0) {
01278       a.tv_sec-- ;
01279       a.tv_usec += ONE_MILLION;
01280    }
01281    return a;
01282 }
01283 #undef ONE_MILLION
01284 
01285 /*! \brief glibc puts a lock inside random(3), so that the results are thread-safe.
01286  * BSD libc (and others) do not. */
01287 
01288 #ifndef linux
01289 AST_MUTEX_DEFINE_STATIC(randomlock);
01290 #endif
01291 
01292 long int ast_random(void)
01293 {
01294    long int res;
01295 #ifdef HAVE_DEV_URANDOM
01296    if (dev_urandom_fd >= 0) {
01297       int read_res = read(dev_urandom_fd, &res, sizeof(res));
01298       if (read_res > 0) {
01299          long int rm = RAND_MAX;
01300          res = res < 0 ? ~res : res;
01301          rm++;
01302          return res % rm;
01303       }
01304    }
01305 #endif
01306 #ifdef linux
01307    res = random();
01308 #else
01309    ast_mutex_lock(&randomlock);
01310    res = random();
01311    ast_mutex_unlock(&randomlock);
01312 #endif
01313    return res;
01314 }
01315 
01316 char *ast_process_quotes_and_slashes(char *start, char find, char replace_with)
01317 {
01318    char *dataPut = start;
01319    int inEscape = 0;
01320    int inQuotes = 0;
01321 
01322    for (; *start; start++) {
01323       if (inEscape) {
01324          *dataPut++ = *start;       /* Always goes verbatim */
01325          inEscape = 0;
01326       } else {
01327          if (*start == '\\') {
01328             inEscape = 1;      /* Do not copy \ into the data */
01329          } else if (*start == '\'') {
01330             inQuotes = 1 - inQuotes;   /* Do not copy ' into the data */
01331          } else {
01332             /* Replace , with |, unless in quotes */
01333             *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
01334          }
01335       }
01336    }
01337    if (start != dataPut)
01338       *dataPut = 0;
01339    return dataPut;
01340 }
01341 
01342 void ast_join(char *s, size_t len, char * const w[])
01343 {
01344    int x, ofs = 0;
01345    const char *src;
01346 
01347    /* Join words into a string */
01348    if (!s)
01349       return;
01350    for (x = 0; ofs < len && w[x]; x++) {
01351       if (x > 0)
01352          s[ofs++] = ' ';
01353       for (src = w[x]; *src && ofs < len; src++)
01354          s[ofs++] = *src;
01355    }
01356    if (ofs == len)
01357       ofs--;
01358    s[ofs] = '\0';
01359 }
01360 
01361 /*
01362  * stringfields support routines.
01363  */
01364 
01365 const char __ast_string_field_empty[] = ""; /*!< the empty string */
01366 
01367 /*! \brief add a new block to the pool.
01368  * We can only allocate from the topmost pool, so the
01369  * fields in *mgr reflect the size of that only.
01370  */
01371 static int add_string_pool(struct ast_string_field_mgr *mgr, struct ast_string_field_pool **pool_head,
01372             size_t size, const char *file, int lineno, const char *func)
01373 {
01374    struct ast_string_field_pool *pool;
01375 
01376 #if defined(__AST_DEBUG_MALLOC)
01377    if (!(pool = __ast_calloc(1, sizeof(*pool) + size, file, lineno, func))) {
01378       return -1;
01379    }
01380 #else
01381    if (!(pool = ast_calloc(1, sizeof(*pool) + size))) {
01382       return -1;
01383    }
01384 #endif
01385 
01386    pool->prev = *pool_head;
01387    *pool_head = pool;
01388    mgr->size = size;
01389    mgr->used = 0;
01390    mgr->last_alloc = NULL;
01391 
01392    return 0;
01393 }
01394 
01395 /*
01396  * This is an internal API, code should not use it directly.
01397  * It initializes all fields as empty, then uses 'size' for 3 functions:
01398  * size > 0 means initialize the pool list with a pool of given size.
01399  * This must be called right after allocating the object.
01400  * size = 0 means release all pools except the most recent one.
01401  * This is useful to e.g. reset an object to the initial value.
01402  * size < 0 means release all pools.
01403  * This must be done before destroying the object.
01404  */
01405 int __ast_string_field_init(struct ast_string_field_mgr *mgr, struct ast_string_field_pool **pool_head,
01406              int needed, const char *file, int lineno, const char *func)
01407 {
01408    const char **p = (const char **) pool_head + 1;
01409    struct ast_string_field_pool *cur = NULL;
01410    struct ast_string_field_pool *preserve = NULL;
01411 
01412    /* clear fields - this is always necessary */
01413    while ((struct ast_string_field_mgr *) p != mgr)
01414       *p++ = __ast_string_field_empty;
01415    mgr->last_alloc = NULL;
01416 #if defined(__AST_DEBUG_MALLOC)
01417    mgr->owner_file = file;
01418    mgr->owner_func = func;
01419    mgr->owner_line = lineno;
01420 #endif
01421    if (needed > 0) {    /* allocate the initial pool */
01422       *pool_head = NULL;
01423       return add_string_pool(mgr, pool_head, needed, file, lineno, func);
01424    }
01425    if (needed < 0) {    /* reset all pools */
01426       if (*pool_head == NULL) {
01427          ast_log(LOG_WARNING, "trying to reset empty pool\n");
01428          return -1;
01429       }
01430       cur = *pool_head;
01431    } else {       /* preserve the last pool */
01432       if (*pool_head == NULL) {
01433          ast_log(LOG_WARNING, "trying to reset empty pool\n");
01434          return -1;
01435       }
01436       mgr->used = 0;
01437       preserve = *pool_head;
01438       cur = preserve->prev;
01439    }
01440 
01441    if (preserve) {
01442       preserve->prev = NULL;
01443    }
01444 
01445    while (cur) {
01446       struct ast_string_field_pool *prev = cur->prev;
01447 
01448       if (cur != preserve) {
01449          ast_free(cur);
01450       }
01451       cur = prev;
01452    }
01453 
01454    *pool_head = preserve;
01455 
01456    return 0;
01457 }
01458 
01459 ast_string_field __ast_string_field_alloc_space(struct ast_string_field_mgr *mgr,
01460                   struct ast_string_field_pool **pool_head, size_t needed)
01461 {
01462    char *result = NULL;
01463    size_t space = mgr->size - mgr->used;
01464 
01465    if (__builtin_expect(needed > space, 0)) {
01466       size_t new_size = mgr->size * 2;
01467 
01468       while (new_size < needed)
01469          new_size *= 2;
01470 
01471 #if defined(__AST_DEBUG_MALLOC)
01472       if (add_string_pool(mgr, pool_head, new_size, mgr->owner_file, mgr->owner_line, mgr->owner_func))
01473          return NULL;
01474 #else
01475       if (add_string_pool(mgr, pool_head, new_size, __FILE__, __LINE__, __FUNCTION__))
01476          return NULL;
01477 #endif
01478    }
01479 
01480    result = (*pool_head)->base + mgr->used;
01481    mgr->used += needed;
01482    mgr->last_alloc = result;
01483    return result;
01484 }
01485 
01486 int __ast_string_field_ptr_grow(struct ast_string_field_mgr *mgr, size_t needed,
01487             const ast_string_field *ptr)
01488 {
01489    int grow = needed - (strlen(*ptr) + 1);
01490    size_t space = mgr->size - mgr->used;
01491 
01492    if (grow <= 0) {
01493       return 0;
01494    }
01495 
01496    if (*ptr != mgr->last_alloc) {
01497       return 1;
01498    }
01499 
01500    if (space < grow) {
01501       return 1;
01502    }
01503 
01504    mgr->used += grow;
01505 
01506    return 0;
01507 }
01508 
01509 void __ast_string_field_ptr_build_va(struct ast_string_field_mgr *mgr,
01510                  struct ast_string_field_pool **pool_head,
01511                  ast_string_field *ptr, const char *format, va_list ap1, va_list ap2)
01512 {
01513    size_t needed;
01514    size_t available;
01515    size_t space = mgr->size - mgr->used;
01516    char *target;
01517 
01518    /* if the field already has space allocated, try to reuse it;
01519       otherwise, use the empty space at the end of the current
01520       pool
01521    */
01522    if ((*ptr)[0] != '\0') {
01523       target = (char *) *ptr;
01524       available = strlen(target) + 1;
01525    } else {
01526       target = (*pool_head)->base + mgr->used;
01527       available = space;
01528    }
01529 
01530    needed = vsnprintf(target, available, format, ap1) + 1;
01531 
01532    va_end(ap1);
01533 
01534    if (needed > available) {
01535       /* if the space needed can be satisfied by using the current
01536          pool (which could only occur if we tried to use the field's
01537          allocated space and failed), then use that space; otherwise
01538          allocate a new pool
01539       */
01540       if (needed > space) {
01541          size_t new_size = mgr->size * 2;
01542 
01543          while (new_size < needed)
01544             new_size *= 2;
01545          
01546 #if defined(__AST_DEBUG_MALLOC)
01547          if (add_string_pool(mgr, pool_head, new_size, mgr->owner_file, mgr->owner_line, mgr->owner_func))
01548             return;
01549 #else
01550          if (add_string_pool(mgr, pool_head, new_size, NULL, 0, NULL))
01551             return;
01552 #endif
01553       }
01554 
01555       target = (*pool_head)->base + mgr->used;
01556       vsprintf(target, format, ap2);
01557    }
01558 
01559    if (*ptr != target) {
01560       mgr->last_alloc = *ptr = target;
01561       mgr->used += needed;
01562    }
01563 }
01564 
01565 void __ast_string_field_ptr_build(struct ast_string_field_mgr *mgr,
01566               struct ast_string_field_pool **pool_head,
01567               ast_string_field *ptr, const char *format, ...)
01568 {
01569    va_list ap1, ap2;
01570 
01571    va_start(ap1, format);
01572    va_start(ap2, format);     /* va_copy does not exist on FreeBSD */
01573 
01574    __ast_string_field_ptr_build_va(mgr, pool_head, ptr, format, ap1, ap2);
01575 
01576    va_end(ap1);
01577    va_end(ap2);
01578 }
01579 /* end of stringfields support */
01580 
01581 AST_MUTEX_DEFINE_STATIC(fetchadd_m); /* used for all fetc&add ops */
01582 
01583 int ast_atomic_fetchadd_int_slow(volatile int *p, int v)
01584 {
01585    int ret;
01586    ast_mutex_lock(&fetchadd_m);
01587    ret = *p;
01588    *p += v;
01589    ast_mutex_unlock(&fetchadd_m);
01590    return ret;
01591 }
01592 
01593 /*! \brief
01594  * get values from config variables.
01595  */
01596 int ast_get_timeval(const char *src, struct timeval *dst, struct timeval _default, int *consumed)
01597 {
01598    long double dtv = 0.0;
01599    int scanned;
01600 
01601    if (dst == NULL)
01602       return -1;
01603 
01604    *dst = _default;
01605 
01606    if (ast_strlen_zero(src))
01607       return -1;
01608 
01609    /* only integer at the moment, but one day we could accept more formats */
01610    if (sscanf(src, "%Lf%n", &dtv, &scanned) > 0) {
01611       dst->tv_sec = dtv;
01612       dst->tv_usec = (dtv - dst->tv_sec) * 1000000.0;
01613       if (consumed)
01614          *consumed = scanned;
01615       return 0;
01616    } else
01617       return -1;
01618 }
01619 
01620 /*! \brief
01621  * get values from config variables.
01622  */
01623 int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed)
01624 {
01625    long t;
01626    int scanned;
01627 
01628    if (dst == NULL)
01629       return -1;
01630 
01631    *dst = _default;
01632 
01633    if (ast_strlen_zero(src))
01634       return -1;
01635 
01636    /* only integer at the moment, but one day we could accept more formats */
01637    if (sscanf(src, "%ld%n", &t, &scanned) == 1) {
01638       *dst = t;
01639       if (consumed)
01640          *consumed = scanned;
01641       return 0;
01642    } else
01643       return -1;
01644 }
01645 
01646 /*!
01647  * core handler for dynamic strings.
01648  * This is not meant to be called directly, but rather through the
01649  * various wrapper macros
01650  * ast_str_set(...)
01651  * ast_str_append(...)
01652  * ast_str_set_va(...)
01653  * ast_str_append_va(...)
01654  */
01655 
01656 int __ast_str_helper(struct ast_str **buf, size_t max_len,
01657    int append, const char *fmt, va_list ap)
01658 {
01659    int res, need;
01660    int offset = (append && (*buf)->len) ? (*buf)->used : 0;
01661 
01662    if (max_len < 0)
01663       max_len = (*buf)->len;  /* don't exceed the allocated space */
01664    /*
01665     * Ask vsnprintf how much space we need. Remember that vsnprintf
01666     * does not count the final '\0' so we must add 1.
01667     */
01668    res = vsnprintf((*buf)->str + offset, (*buf)->len - offset, fmt, ap);
01669 
01670    need = res + offset + 1;
01671    /*
01672     * If there is not enough space and we are below the max length,
01673     * reallocate the buffer and return a message telling to retry.
01674     */
01675    if (need > (*buf)->len && (max_len == 0 || (*buf)->len < max_len) ) {
01676       if (max_len && max_len < need)   /* truncate as needed */
01677          need = max_len;
01678       else if (max_len == 0)  /* if unbounded, give more room for next time */
01679          need += 16 + need/4;
01680       if (0)   /* debugging */
01681          ast_verbose("extend from %d to %d\n", (int)(*buf)->len, need);
01682       if (ast_str_make_space(buf, need)) {
01683          ast_verbose("failed to extend from %d to %d\n", (int)(*buf)->len, need);
01684          return AST_DYNSTR_BUILD_FAILED;
01685       }
01686       (*buf)->str[offset] = '\0';   /* Truncate the partial write. */
01687 
01688       /* va_end() and va_start() must be done before calling
01689        * vsnprintf() again. */
01690       return AST_DYNSTR_BUILD_RETRY;
01691    }
01692    /* update space used, keep in mind the truncation */
01693    (*buf)->used = (res + offset > (*buf)->len) ? (*buf)->len : res + offset;
01694 
01695    return res;
01696 }
01697 
01698 void ast_enable_packet_fragmentation(int sock)
01699 {
01700 #if defined(HAVE_IP_MTU_DISCOVER)
01701    int val = IP_PMTUDISC_DONT;
01702    
01703    if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
01704       ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
01705 #endif /* HAVE_IP_MTU_DISCOVER */
01706 }
01707 
01708 int ast_mkdir(const char *path, int mode)
01709 {
01710    char *ptr;
01711    int len = strlen(path), count = 0, x, piececount = 0;
01712    char *tmp = ast_strdupa(path);
01713    char **pieces;
01714    char *fullpath = alloca(len + 1);
01715    int res = 0;
01716 
01717    for (ptr = tmp; *ptr; ptr++) {
01718       if (*ptr == '/')
01719          count++;
01720    }
01721 
01722    /* Count the components to the directory path */
01723    pieces = alloca(count * sizeof(*pieces));
01724    for (ptr = tmp; *ptr; ptr++) {
01725       if (*ptr == '/') {
01726          *ptr = '\0';
01727          pieces[piececount++] = ptr + 1;
01728       }
01729    }
01730 
01731    *fullpath = '\0';
01732    for (x = 0; x < piececount; x++) {
01733       /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
01734       strcat(fullpath, "/");
01735       strcat(fullpath, pieces[x]);
01736       res = mkdir(fullpath, mode);
01737       if (res && errno != EEXIST)
01738          return errno;
01739    }
01740    return 0;
01741 }
01742 
01743 int ast_utils_init(void)
01744 {
01745 #ifdef HAVE_DEV_URANDOM
01746    dev_urandom_fd = open("/dev/urandom", O_RDONLY);
01747 #endif
01748    base64_init();
01749 #ifdef DEBUG_THREADS
01750 #if !defined(LOW_MEMORY)
01751    ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
01752 #endif
01753 #endif
01754    return 0;
01755 }
01756 
01757 #ifndef __AST_DEBUG_MALLOC
01758 int _ast_asprintf(char **ret, const char *file, int lineno, const char *func, const char *fmt, ...)
01759 {
01760    int res;
01761    va_list ap;
01762 
01763    va_start(ap, fmt);
01764    if ((res = vasprintf(ret, fmt, ap)) == -1) {
01765       MALLOC_FAILURE_MSG;
01766    }
01767    va_end(ap);
01768 
01769    return res;
01770 }
01771 #endif

Generated on Thu Jul 9 13:40:41 2009 for Asterisk - the Open Source PBX by  doxygen 1.4.7