Thu Feb 9 06:34:01 2012

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: 344846 $")
00029 
00030 #include <ctype.h>
00031 #include <sys/stat.h>
00032 #include <sys/stat.h>
00033 
00034 #ifdef HAVE_DEV_URANDOM
00035 #include <fcntl.h>
00036 #endif
00037 
00038 #include <sys/syscall.h>
00039 #if defined(__APPLE__)
00040 #include <mach/mach.h>
00041 #elif defined(HAVE_SYS_THR_H)
00042 #include <sys/thr.h>
00043 #endif
00044 
00045 #include "asterisk/network.h"
00046 
00047 #define AST_API_MODULE     /* ensure that inlinable API functions will be built in lock.h if required */
00048 #include "asterisk/lock.h"
00049 #include "asterisk/io.h"
00050 #include "asterisk/md5.h"
00051 #include "asterisk/sha1.h"
00052 #include "asterisk/cli.h"
00053 #include "asterisk/linkedlists.h"
00054 
00055 #define AST_API_MODULE     /* ensure that inlinable API functions will be built in this module if required */
00056 #include "asterisk/strings.h"
00057 
00058 #define AST_API_MODULE     /* ensure that inlinable API functions will be built in this module if required */
00059 #include "asterisk/time.h"
00060 
00061 #define AST_API_MODULE     /* ensure that inlinable API functions will be built in this module if required */
00062 #include "asterisk/stringfields.h"
00063 
00064 #define AST_API_MODULE     /* ensure that inlinable API functions will be built in this module if required */
00065 #include "asterisk/utils.h"
00066 
00067 #define AST_API_MODULE
00068 #include "asterisk/threadstorage.h"
00069 
00070 #define AST_API_MODULE
00071 #include "asterisk/config.h"
00072 
00073 static char base64[64];
00074 static char b2a[256];
00075 
00076 AST_THREADSTORAGE(inet_ntoa_buf);
00077 
00078 #if !defined(HAVE_GETHOSTBYNAME_R_5) && !defined(HAVE_GETHOSTBYNAME_R_6)
00079 
00080 #define ERANGE 34 /*!< duh? ERANGE value copied from web... */
00081 #undef gethostbyname
00082 
00083 AST_MUTEX_DEFINE_STATIC(__mutex);
00084 
00085 /*! \brief Reentrant replacement for gethostbyname for BSD-based systems.
00086 \note This
00087 routine is derived from code originally written and placed in the public 
00088 domain by Enzo Michelangeli <em@em.no-ip.com> */
00089 
00090 static int gethostbyname_r (const char *name, struct hostent *ret, char *buf,
00091             size_t buflen, struct hostent **result, 
00092             int *h_errnop) 
00093 {
00094    int hsave;
00095    struct hostent *ph;
00096    ast_mutex_lock(&__mutex); /* begin critical area */
00097    hsave = h_errno;
00098 
00099    ph = gethostbyname(name);
00100    *h_errnop = h_errno; /* copy h_errno to *h_herrnop */
00101    if (ph == NULL) {
00102       *result = NULL;
00103    } else {
00104       char **p, **q;
00105       char *pbuf;
00106       int nbytes = 0;
00107       int naddr = 0, naliases = 0;
00108       /* determine if we have enough space in buf */
00109 
00110       /* count how many addresses */
00111       for (p = ph->h_addr_list; *p != 0; p++) {
00112          nbytes += ph->h_length; /* addresses */
00113          nbytes += sizeof(*p); /* pointers */
00114          naddr++;
00115       }
00116       nbytes += sizeof(*p); /* one more for the terminating NULL */
00117 
00118       /* count how many aliases, and total length of strings */
00119       for (p = ph->h_aliases; *p != 0; p++) {
00120          nbytes += (strlen(*p)+1); /* aliases */
00121          nbytes += sizeof(*p);  /* pointers */
00122          naliases++;
00123       }
00124       nbytes += sizeof(*p); /* one more for the terminating NULL */
00125 
00126       /* here nbytes is the number of bytes required in buffer */
00127       /* as a terminator must be there, the minimum value is ph->h_length */
00128       if (nbytes > buflen) {
00129          *result = NULL;
00130          ast_mutex_unlock(&__mutex); /* end critical area */
00131          return ERANGE; /* not enough space in buf!! */
00132       }
00133 
00134       /* There is enough space. Now we need to do a deep copy! */
00135       /* Allocation in buffer:
00136          from [0] to [(naddr-1) * sizeof(*p)]:
00137          pointers to addresses
00138          at [naddr * sizeof(*p)]:
00139          NULL
00140          from [(naddr+1) * sizeof(*p)] to [(naddr+naliases) * sizeof(*p)] :
00141          pointers to aliases
00142          at [(naddr+naliases+1) * sizeof(*p)]:
00143          NULL
00144          then naddr addresses (fixed length), and naliases aliases (asciiz).
00145       */
00146 
00147       *ret = *ph;   /* copy whole structure (not its address!) */
00148 
00149       /* copy addresses */
00150       q = (char **)buf; /* pointer to pointers area (type: char **) */
00151       ret->h_addr_list = q; /* update pointer to address list */
00152       pbuf = buf + ((naddr + naliases + 2) * sizeof(*p)); /* skip that area */
00153       for (p = ph->h_addr_list; *p != 0; p++) {
00154          memcpy(pbuf, *p, ph->h_length); /* copy address bytes */
00155          *q++ = pbuf; /* the pointer is the one inside buf... */
00156          pbuf += ph->h_length; /* advance pbuf */
00157       }
00158       *q++ = NULL; /* address list terminator */
00159 
00160       /* copy aliases */
00161       ret->h_aliases = q; /* update pointer to aliases list */
00162       for (p = ph->h_aliases; *p != 0; p++) {
00163          strcpy(pbuf, *p); /* copy alias strings */
00164          *q++ = pbuf; /* the pointer is the one inside buf... */
00165          pbuf += strlen(*p); /* advance pbuf */
00166          *pbuf++ = 0; /* string terminator */
00167       }
00168       *q++ = NULL; /* terminator */
00169 
00170       strcpy(pbuf, ph->h_name); /* copy alias strings */
00171       ret->h_name = pbuf;
00172       pbuf += strlen(ph->h_name); /* advance pbuf */
00173       *pbuf++ = 0; /* string terminator */
00174 
00175       *result = ret;  /* and let *result point to structure */
00176 
00177    }
00178    h_errno = hsave;  /* restore h_errno */
00179    ast_mutex_unlock(&__mutex); /* end critical area */
00180 
00181    return (*result == NULL); /* return 0 on success, non-zero on error */
00182 }
00183 
00184 
00185 #endif
00186 
00187 /*! \brief Re-entrant (thread safe) version of gethostbyname that replaces the 
00188    standard gethostbyname (which is not thread safe)
00189 */
00190 struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp)
00191 {
00192    int res;
00193    int herrno;
00194    int dots = 0;
00195    const char *s;
00196    struct hostent *result = NULL;
00197    /* Although it is perfectly legitimate to lookup a pure integer, for
00198       the sake of the sanity of people who like to name their peers as
00199       integers, we break with tradition and refuse to look up a
00200       pure integer */
00201    s = host;
00202    res = 0;
00203    while (s && *s) {
00204       if (*s == '.')
00205          dots++;
00206       else if (!isdigit(*s))
00207          break;
00208       s++;
00209    }
00210    if (!s || !*s) {
00211       /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
00212       if (dots != 3)
00213          return NULL;
00214       memset(hp, 0, sizeof(struct ast_hostent));
00215       hp->hp.h_addrtype = AF_INET;
00216       hp->hp.h_addr_list = (void *) hp->buf;
00217       hp->hp.h_addr = hp->buf + sizeof(void *);
00218       /* For AF_INET, this will always be 4 */
00219       hp->hp.h_length = 4;
00220       if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
00221          return &hp->hp;
00222       return NULL;
00223       
00224    }
00225 #ifdef HAVE_GETHOSTBYNAME_R_5
00226    result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);
00227 
00228    if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
00229       return NULL;
00230 #else
00231    res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
00232 
00233    if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
00234       return NULL;
00235 #endif
00236    return &hp->hp;
00237 }
00238 
00239 /*! \brief Produce 32 char MD5 hash of value. */
00240 void ast_md5_hash(char *output, const char *input)
00241 {
00242    struct MD5Context md5;
00243    unsigned char digest[16];
00244    char *ptr;
00245    int x;
00246 
00247    MD5Init(&md5);
00248    MD5Update(&md5, (const unsigned char *) input, strlen(input));
00249    MD5Final(digest, &md5);
00250    ptr = output;
00251    for (x = 0; x < 16; x++)
00252       ptr += sprintf(ptr, "%2.2x", digest[x]);
00253 }
00254 
00255 /*! \brief Produce 40 char SHA1 hash of value. */
00256 void ast_sha1_hash(char *output, const char *input)
00257 {
00258    struct SHA1Context sha;
00259    char *ptr;
00260    int x;
00261    uint8_t Message_Digest[20];
00262 
00263    SHA1Reset(&sha);
00264    
00265    SHA1Input(&sha, (const unsigned char *) input, strlen(input));
00266 
00267    SHA1Result(&sha, Message_Digest);
00268    ptr = output;
00269    for (x = 0; x < 20; x++)
00270       ptr += sprintf(ptr, "%2.2x", Message_Digest[x]);
00271 }
00272 
00273 /*! \brief decode BASE64 encoded text */
00274 int ast_base64decode(unsigned char *dst, const char *src, int max)
00275 {
00276    int cnt = 0;
00277    unsigned int byte = 0;
00278    unsigned int bits = 0;
00279    int incnt = 0;
00280    while(*src && *src != '=' && (cnt < max)) {
00281       /* Shift in 6 bits of input */
00282       byte <<= 6;
00283       byte |= (b2a[(int)(*src)]) & 0x3f;
00284       bits += 6;
00285       src++;
00286       incnt++;
00287       /* If we have at least 8 bits left over, take that character 
00288          off the top */
00289       if (bits >= 8)  {
00290          bits -= 8;
00291          *dst = (byte >> bits) & 0xff;
00292          dst++;
00293          cnt++;
00294       }
00295    }
00296    /* Don't worry about left over bits, they're extra anyway */
00297    return cnt;
00298 }
00299 
00300 /*! \brief encode text to BASE64 coding */
00301 int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
00302 {
00303    int cnt = 0;
00304    int col = 0;
00305    unsigned int byte = 0;
00306    int bits = 0;
00307    int cntin = 0;
00308    /* Reserve space for null byte at end of string */
00309    max--;
00310    while ((cntin < srclen) && (cnt < max)) {
00311       byte <<= 8;
00312       byte |= *(src++);
00313       bits += 8;
00314       cntin++;
00315       if ((bits == 24) && (cnt + 4 <= max)) {
00316          *dst++ = base64[(byte >> 18) & 0x3f];
00317          *dst++ = base64[(byte >> 12) & 0x3f];
00318          *dst++ = base64[(byte >> 6) & 0x3f];
00319          *dst++ = base64[byte & 0x3f];
00320          cnt += 4;
00321          col += 4;
00322          bits = 0;
00323          byte = 0;
00324       }
00325       if (linebreaks && (cnt < max) && (col == 64)) {
00326          *dst++ = '\n';
00327          cnt++;
00328          col = 0;
00329       }
00330    }
00331    if (bits && (cnt + 4 <= max)) {
00332       /* Add one last character for the remaining bits, 
00333          padding the rest with 0 */
00334       byte <<= 24 - bits;
00335       *dst++ = base64[(byte >> 18) & 0x3f];
00336       *dst++ = base64[(byte >> 12) & 0x3f];
00337       if (bits == 16)
00338          *dst++ = base64[(byte >> 6) & 0x3f];
00339       else
00340          *dst++ = '=';
00341       *dst++ = '=';
00342       cnt += 4;
00343    }
00344    if (linebreaks && (cnt < max)) {
00345       *dst++ = '\n';
00346       cnt++;
00347    }
00348    *dst = '\0';
00349    return cnt;
00350 }
00351 
00352 int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
00353 {
00354    return ast_base64encode_full(dst, src, srclen, max, 0);
00355 }
00356 
00357 static void base64_init(void)
00358 {
00359    int x;
00360    memset(b2a, -1, sizeof(b2a));
00361    /* Initialize base-64 Conversion table */
00362    for (x = 0; x < 26; x++) {
00363       /* A-Z */
00364       base64[x] = 'A' + x;
00365       b2a['A' + x] = x;
00366       /* a-z */
00367       base64[x + 26] = 'a' + x;
00368       b2a['a' + x] = x + 26;
00369       /* 0-9 */
00370       if (x < 10) {
00371          base64[x + 52] = '0' + x;
00372          b2a['0' + x] = x + 52;
00373       }
00374    }
00375    base64[62] = '+';
00376    base64[63] = '/';
00377    b2a[(int)'+'] = 62;
00378    b2a[(int)'/'] = 63;
00379 }
00380 
00381 const struct ast_flags ast_uri_http = {AST_URI_UNRESERVED};
00382 const struct ast_flags ast_uri_http_legacy = {AST_URI_LEGACY_SPACE | AST_URI_UNRESERVED};
00383 const struct ast_flags ast_uri_sip_user = {AST_URI_UNRESERVED | AST_URI_SIP_USER_UNRESERVED};
00384 
00385 char *ast_uri_encode(const char *string, char *outbuf, int buflen, struct ast_flags spec)
00386 {
00387    const char *ptr  = string; /* Start with the string */
00388    char *out = outbuf;
00389    const char *mark = "-_.!~*'()"; /* no encode set, RFC 2396 section 2.3, RFC 3261 sec 25 */
00390    const char *user_unreserved = "&=+$,;?/"; /* user-unreserved set, RFC 3261 sec 25 */
00391 
00392    while (*ptr && out - outbuf < buflen - 1) {
00393       if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *ptr == ' ') {
00394          /* for legacy encoding, encode spaces as '+' */
00395          *out = '+';
00396          out++;
00397       } else if (!(ast_test_flag(&spec, AST_URI_MARK)
00398             && strchr(mark, *ptr))
00399          && !(ast_test_flag(&spec, AST_URI_ALPHANUM)
00400             && ((*ptr >= '0' && *ptr <= '9')
00401             || (*ptr >= 'A' && *ptr <= 'Z')
00402             || (*ptr >= 'a' && *ptr <= 'z')))
00403          && !(ast_test_flag(&spec, AST_URI_SIP_USER_UNRESERVED)
00404             && strchr(user_unreserved, *ptr))) {
00405 
00406          if (out - outbuf >= buflen - 3) {
00407             break;
00408          }
00409          out += sprintf(out, "%%%02X", (unsigned char) *ptr);
00410       } else {
00411          *out = *ptr;   /* Continue copying the string */
00412          out++;
00413       }
00414       ptr++;
00415    }
00416 
00417    if (buflen) {
00418       *out = '\0';
00419    }
00420 
00421    return outbuf;
00422 }
00423 
00424 void ast_uri_decode(char *s, struct ast_flags spec)
00425 {
00426    char *o;
00427    unsigned int tmp;
00428 
00429    for (o = s; *s; s++, o++) {
00430       if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *s == '+') {
00431          /* legacy mode, decode '+' as space */
00432          *o = ' ';
00433       } else if (*s == '%' && s[1] != '\0' && s[2] != '\0' && sscanf(s + 1, "%2x", &tmp) == 1) {
00434          /* have '%', two chars and correct parsing */
00435          *o = tmp;
00436          s += 2;  /* Will be incremented once more when we break out */
00437       } else /* all other cases, just copy */
00438          *o = *s;
00439    }
00440    *o = '\0';
00441 }
00442 
00443 char *ast_escape_quoted(const char *string, char *outbuf, int buflen)
00444 {
00445    const char *ptr  = string;
00446    char *out = outbuf;
00447    char *allow = "\t\v !"; /* allow LWS (minus \r and \n) and "!" */
00448 
00449    while (*ptr && out - outbuf < buflen - 1) {
00450       if (!(strchr(allow, *ptr))
00451          && !(*ptr >= '#' && *ptr <= '[') /* %x23 - %x5b */
00452          && !(*ptr >= ']' && *ptr <= '~') /* %x5d - %x7e */
00453          && !((unsigned char) *ptr > 0x7f)) {             /* UTF8-nonascii */
00454 
00455          if (out - outbuf >= buflen - 2) {
00456             break;
00457          }
00458          out += sprintf(out, "\\%c", (unsigned char) *ptr);
00459       } else {
00460          *out = *ptr;
00461          out++;
00462       }
00463       ptr++;
00464    }
00465 
00466    if (buflen) {
00467       *out = '\0';
00468    }
00469 
00470    return outbuf;
00471 }
00472 /*! \brief  ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa */
00473 const char *ast_inet_ntoa(struct in_addr ia)
00474 {
00475    char *buf;
00476 
00477    if (!(buf = ast_threadstorage_get(&inet_ntoa_buf, INET_ADDRSTRLEN)))
00478       return "";
00479 
00480    return inet_ntop(AF_INET, &ia, buf, INET_ADDRSTRLEN);
00481 }
00482 
00483 #ifdef HAVE_DEV_URANDOM
00484 static int dev_urandom_fd;
00485 #endif
00486 
00487 #ifndef __linux__
00488 #undef pthread_create /* For ast_pthread_create function only */
00489 #endif /* !__linux__ */
00490 
00491 #if !defined(LOW_MEMORY)
00492 
00493 #ifdef DEBUG_THREADS
00494 
00495 /*! \brief A reasonable maximum number of locks a thread would be holding ... */
00496 #define AST_MAX_LOCKS 64
00497 
00498 /* Allow direct use of pthread_mutex_t and friends */
00499 #undef pthread_mutex_t
00500 #undef pthread_mutex_lock
00501 #undef pthread_mutex_unlock
00502 #undef pthread_mutex_init
00503 #undef pthread_mutex_destroy
00504 
00505 /*! 
00506  * \brief Keep track of which locks a thread holds 
00507  *
00508  * There is an instance of this struct for every active thread
00509  */
00510 struct thr_lock_info {
00511    /*! The thread's ID */
00512    pthread_t thread_id;
00513    /*! The thread name which includes where the thread was started */
00514    const char *thread_name;
00515    /*! This is the actual container of info for what locks this thread holds */
00516    struct {
00517       const char *file;
00518       int line_num;
00519       const char *func;
00520       const char *lock_name;
00521       void *lock_addr;
00522       int times_locked;
00523       enum ast_lock_type type;
00524       /*! This thread is waiting on this lock */
00525       int pending:2;
00526 #ifdef HAVE_BKTR
00527       struct ast_bt *backtrace;
00528 #endif
00529    } locks[AST_MAX_LOCKS];
00530    /*! This is the number of locks currently held by this thread.
00531     *  The index (num_locks - 1) has the info on the last one in the
00532     *  locks member */
00533    unsigned int num_locks;
00534    /*! Protects the contents of the locks member 
00535     * Intentionally not ast_mutex_t */
00536    pthread_mutex_t lock;
00537    AST_LIST_ENTRY(thr_lock_info) entry;
00538 };
00539 
00540 /*! 
00541  * \brief Locked when accessing the lock_infos list 
00542  */
00543 AST_MUTEX_DEFINE_STATIC(lock_infos_lock);
00544 /*!
00545  * \brief A list of each thread's lock info 
00546  */
00547 static AST_LIST_HEAD_NOLOCK_STATIC(lock_infos, thr_lock_info);
00548 
00549 /*!
00550  * \brief Destroy a thread's lock info
00551  *
00552  * This gets called automatically when the thread stops
00553  */
00554 static void lock_info_destroy(void *data)
00555 {
00556    struct thr_lock_info *lock_info = data;
00557    int i;
00558 
00559    pthread_mutex_lock(&lock_infos_lock.mutex);
00560    AST_LIST_REMOVE(&lock_infos, lock_info, entry);
00561    pthread_mutex_unlock(&lock_infos_lock.mutex);
00562 
00563 
00564    for (i = 0; i < lock_info->num_locks; i++) {
00565       if (lock_info->locks[i].pending == -1) {
00566          /* This just means that the last lock this thread went for was by
00567           * using trylock, and it failed.  This is fine. */
00568          break;
00569       }
00570 
00571       ast_log(LOG_ERROR, 
00572          "Thread '%s' still has a lock! - '%s' (%p) from '%s' in %s:%d!\n", 
00573          lock_info->thread_name,
00574          lock_info->locks[i].lock_name,
00575          lock_info->locks[i].lock_addr,
00576          lock_info->locks[i].func,
00577          lock_info->locks[i].file,
00578          lock_info->locks[i].line_num
00579       );
00580    }
00581 
00582    pthread_mutex_destroy(&lock_info->lock);
00583    if (lock_info->thread_name)
00584       free((void *) lock_info->thread_name);
00585    free(lock_info);
00586 }
00587 
00588 /*!
00589  * \brief The thread storage key for per-thread lock info
00590  */
00591 AST_THREADSTORAGE_CUSTOM(thread_lock_info, NULL, lock_info_destroy);
00592 #ifdef HAVE_BKTR
00593 void ast_store_lock_info(enum ast_lock_type type, const char *filename,
00594    int line_num, const char *func, const char *lock_name, void *lock_addr, struct ast_bt *bt)
00595 #else
00596 void ast_store_lock_info(enum ast_lock_type type, const char *filename,
00597    int line_num, const char *func, const char *lock_name, void *lock_addr)
00598 #endif
00599 {
00600    struct thr_lock_info *lock_info;
00601    int i;
00602 
00603    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
00604       return;
00605 
00606    pthread_mutex_lock(&lock_info->lock);
00607 
00608    for (i = 0; i < lock_info->num_locks; i++) {
00609       if (lock_info->locks[i].lock_addr == lock_addr) {
00610          lock_info->locks[i].times_locked++;
00611 #ifdef HAVE_BKTR
00612          lock_info->locks[i].backtrace = bt;
00613 #endif
00614          pthread_mutex_unlock(&lock_info->lock);
00615          return;
00616       }
00617    }
00618 
00619    if (lock_info->num_locks == AST_MAX_LOCKS) {
00620       /* Can't use ast_log here, because it will cause infinite recursion */
00621       fprintf(stderr, "XXX ERROR XXX A thread holds more locks than '%d'."
00622          "  Increase AST_MAX_LOCKS!\n", AST_MAX_LOCKS);
00623       pthread_mutex_unlock(&lock_info->lock);
00624       return;
00625    }
00626 
00627    if (i && lock_info->locks[i - 1].pending == -1) {
00628       /* The last lock on the list was one that this thread tried to lock but
00629        * failed at doing so.  It has now moved on to something else, so remove
00630        * the old lock from the list. */
00631       i--;
00632       lock_info->num_locks--;
00633       memset(&lock_info->locks[i], 0, sizeof(lock_info->locks[0]));
00634    }
00635 
00636    lock_info->locks[i].file = filename;
00637    lock_info->locks[i].line_num = line_num;
00638    lock_info->locks[i].func = func;
00639    lock_info->locks[i].lock_name = lock_name;
00640    lock_info->locks[i].lock_addr = lock_addr;
00641    lock_info->locks[i].times_locked = 1;
00642    lock_info->locks[i].type = type;
00643    lock_info->locks[i].pending = 1;
00644 #ifdef HAVE_BKTR
00645    lock_info->locks[i].backtrace = bt;
00646 #endif
00647    lock_info->num_locks++;
00648 
00649    pthread_mutex_unlock(&lock_info->lock);
00650 }
00651 
00652 void ast_mark_lock_acquired(void *lock_addr)
00653 {
00654    struct thr_lock_info *lock_info;
00655 
00656    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
00657       return;
00658 
00659    pthread_mutex_lock(&lock_info->lock);
00660    if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
00661       lock_info->locks[lock_info->num_locks - 1].pending = 0;
00662    }
00663    pthread_mutex_unlock(&lock_info->lock);
00664 }
00665 
00666 void ast_mark_lock_failed(void *lock_addr)
00667 {
00668    struct thr_lock_info *lock_info;
00669 
00670    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
00671       return;
00672 
00673    pthread_mutex_lock(&lock_info->lock);
00674    if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
00675       lock_info->locks[lock_info->num_locks - 1].pending = -1;
00676       lock_info->locks[lock_info->num_locks - 1].times_locked--;
00677    }
00678    pthread_mutex_unlock(&lock_info->lock);
00679 }
00680 
00681 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)
00682 {
00683    struct thr_lock_info *lock_info;
00684    int i = 0;
00685 
00686    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
00687       return -1;
00688 
00689    pthread_mutex_lock(&lock_info->lock);
00690 
00691    for (i = lock_info->num_locks - 1; i >= 0; i--) {
00692       if (lock_info->locks[i].lock_addr == lock_addr)
00693          break;
00694    }
00695 
00696    if (i == -1) {
00697       /* Lock not found :( */
00698       pthread_mutex_unlock(&lock_info->lock);
00699       return -1;
00700    }
00701 
00702    ast_copy_string(filename, lock_info->locks[i].file, filename_size);
00703    *lineno = lock_info->locks[i].line_num;
00704    ast_copy_string(func, lock_info->locks[i].func, func_size);
00705    ast_copy_string(mutex_name, lock_info->locks[i].lock_name, mutex_name_size);
00706 
00707    pthread_mutex_unlock(&lock_info->lock);
00708 
00709    return 0;
00710 }
00711 
00712 #ifdef HAVE_BKTR
00713 void ast_remove_lock_info(void *lock_addr, struct ast_bt *bt)
00714 #else
00715 void ast_remove_lock_info(void *lock_addr)
00716 #endif
00717 {
00718    struct thr_lock_info *lock_info;
00719    int i = 0;
00720 
00721    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
00722       return;
00723 
00724    pthread_mutex_lock(&lock_info->lock);
00725 
00726    for (i = lock_info->num_locks - 1; i >= 0; i--) {
00727       if (lock_info->locks[i].lock_addr == lock_addr)
00728          break;
00729    }
00730 
00731    if (i == -1) {
00732       /* Lock not found :( */
00733       pthread_mutex_unlock(&lock_info->lock);
00734       return;
00735    }
00736 
00737    if (lock_info->locks[i].times_locked > 1) {
00738       lock_info->locks[i].times_locked--;
00739 #ifdef HAVE_BKTR
00740       lock_info->locks[i].backtrace = bt;
00741 #endif
00742       pthread_mutex_unlock(&lock_info->lock);
00743       return;
00744    }
00745 
00746    if (i < lock_info->num_locks - 1) {
00747       /* Not the last one ... *should* be rare! */
00748       memmove(&lock_info->locks[i], &lock_info->locks[i + 1], 
00749          (lock_info->num_locks - (i + 1)) * sizeof(lock_info->locks[0]));
00750    }
00751 
00752    lock_info->num_locks--;
00753 
00754    pthread_mutex_unlock(&lock_info->lock);
00755 }
00756 
00757 static const char *locktype2str(enum ast_lock_type type)
00758 {
00759    switch (type) {
00760    case AST_MUTEX:
00761       return "MUTEX";
00762    case AST_RDLOCK:
00763       return "RDLOCK";
00764    case AST_WRLOCK:
00765       return "WRLOCK";
00766    }
00767 
00768    return "UNKNOWN";
00769 }
00770 
00771 #ifdef HAVE_BKTR
00772 static void append_backtrace_information(struct ast_str **str, struct ast_bt *bt)
00773 {
00774    char **symbols;
00775 
00776    if (!bt) {
00777       ast_str_append(str, 0, "\tNo backtrace to print\n");
00778       return;
00779    }
00780 
00781    if ((symbols = ast_bt_get_symbols(bt->addresses, bt->num_frames))) {
00782       int frame_iterator;
00783       
00784       for (frame_iterator = 0; frame_iterator < bt->num_frames; ++frame_iterator) {
00785          ast_str_append(str, 0, "\t%s\n", symbols[frame_iterator]);
00786       }
00787 
00788       free(symbols);
00789    } else {
00790       ast_str_append(str, 0, "\tCouldn't retrieve backtrace symbols\n");
00791    }
00792 }
00793 #endif
00794 
00795 static void append_lock_information(struct ast_str **str, struct thr_lock_info *lock_info, int i)
00796 {
00797    int j;
00798    ast_mutex_t *lock;
00799    struct ast_lock_track *lt;
00800    
00801    ast_str_append(str, 0, "=== ---> %sLock #%d (%s): %s %d %s %s %p (%d)\n", 
00802                lock_info->locks[i].pending > 0 ? "Waiting for " : 
00803                lock_info->locks[i].pending < 0 ? "Tried and failed to get " : "", i,
00804                lock_info->locks[i].file, 
00805                locktype2str(lock_info->locks[i].type),
00806                lock_info->locks[i].line_num,
00807                lock_info->locks[i].func, lock_info->locks[i].lock_name,
00808                lock_info->locks[i].lock_addr, 
00809                lock_info->locks[i].times_locked);
00810 #ifdef HAVE_BKTR
00811    append_backtrace_information(str, lock_info->locks[i].backtrace);
00812 #endif
00813    
00814    if (!lock_info->locks[i].pending || lock_info->locks[i].pending == -1)
00815       return;
00816    
00817    /* We only have further details for mutexes right now */
00818    if (lock_info->locks[i].type != AST_MUTEX)
00819       return;
00820    
00821    lock = lock_info->locks[i].lock_addr;
00822    lt = lock->track;
00823    ast_reentrancy_lock(lt);
00824    for (j = 0; *str && j < lt->reentrancy; j++) {
00825       ast_str_append(str, 0, "=== --- ---> Locked Here: %s line %d (%s)\n",
00826                   lt->file[j], lt->lineno[j], lt->func[j]);
00827    }
00828    ast_reentrancy_unlock(lt); 
00829 }
00830 
00831 
00832 /*! This function can help you find highly temporal locks; locks that happen for a 
00833     short time, but at unexpected times, usually at times that create a deadlock,
00834    Why is this thing locked right then? Who is locking it? Who am I fighting
00835     with for this lock? 
00836 
00837    To answer such questions, just call this routine before you would normally try
00838    to aquire a lock. It doesn't do anything if the lock is not acquired. If the
00839    lock is taken, it will publish a line or two to the console via ast_log().
00840 
00841    Sometimes, the lock message is pretty uninformative. For instance, you might
00842    find that the lock is being aquired deep within the astobj2 code; this tells
00843    you little about higher level routines that call the astobj2 routines.
00844    But, using gdb, you can set a break at the ast_log below, and for that
00845    breakpoint, you can set the commands:
00846      where
00847      cont
00848    which will give a stack trace and continue. -- that aught to do the job!
00849 
00850 */
00851 void log_show_lock(void *this_lock_addr)
00852 {
00853    struct thr_lock_info *lock_info;
00854    struct ast_str *str;
00855 
00856    if (!(str = ast_str_create(4096))) {
00857       ast_log(LOG_NOTICE,"Could not create str\n");
00858       return;
00859    }
00860    
00861 
00862    pthread_mutex_lock(&lock_infos_lock.mutex);
00863    AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
00864       int i;
00865       pthread_mutex_lock(&lock_info->lock);
00866       for (i = 0; str && i < lock_info->num_locks; i++) {
00867          /* ONLY show info about this particular lock, if
00868             it's acquired... */
00869          if (lock_info->locks[i].lock_addr == this_lock_addr) {
00870             append_lock_information(&str, lock_info, i);
00871             ast_log(LOG_NOTICE, "%s", ast_str_buffer(str));
00872             break;
00873          }
00874       }
00875       pthread_mutex_unlock(&lock_info->lock);
00876    }
00877    pthread_mutex_unlock(&lock_infos_lock.mutex);
00878    ast_free(str);
00879 }
00880 
00881 
00882 static char *handle_show_locks(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00883 {
00884    struct thr_lock_info *lock_info;
00885    struct ast_str *str;
00886 
00887    if (!(str = ast_str_create(4096)))
00888       return CLI_FAILURE;
00889 
00890    switch (cmd) {
00891    case CLI_INIT:
00892       e->command = "core show locks";
00893       e->usage =
00894          "Usage: core show locks\n"
00895          "       This command is for lock debugging.  It prints out which locks\n"
00896          "are owned by each active thread.\n";
00897       return NULL;
00898 
00899    case CLI_GENERATE:
00900       return NULL;
00901    }
00902 
00903    ast_str_append(&str, 0, "\n" 
00904                   "=======================================================================\n"
00905                   "=== Currently Held Locks ==============================================\n"
00906                   "=======================================================================\n"
00907                   "===\n"
00908                   "=== <pending> <lock#> (<file>): <lock type> <line num> <function> <lock name> <lock addr> (times locked)\n"
00909                   "===\n");
00910 
00911    if (!str)
00912       return CLI_FAILURE;
00913 
00914    pthread_mutex_lock(&lock_infos_lock.mutex);
00915    AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
00916       int i;
00917       if (lock_info->num_locks) {
00918          ast_str_append(&str, 0, "=== Thread ID: 0x%lx (%s)\n", (long) lock_info->thread_id,
00919             lock_info->thread_name);
00920          pthread_mutex_lock(&lock_info->lock);
00921          for (i = 0; str && i < lock_info->num_locks; i++) {
00922             append_lock_information(&str, lock_info, i);
00923          }
00924          pthread_mutex_unlock(&lock_info->lock);
00925          if (!str)
00926             break;
00927          ast_str_append(&str, 0, "=== -------------------------------------------------------------------\n"
00928                         "===\n");
00929          if (!str)
00930             break;
00931       }
00932    }
00933    pthread_mutex_unlock(&lock_infos_lock.mutex);
00934 
00935    if (!str)
00936       return CLI_FAILURE;
00937 
00938    ast_str_append(&str, 0, "=======================================================================\n"
00939                   "\n");
00940 
00941    if (!str)
00942       return CLI_FAILURE;
00943 
00944    ast_cli(a->fd, "%s", ast_str_buffer(str));
00945 
00946    ast_free(str);
00947 
00948    return CLI_SUCCESS;
00949 }
00950 
00951 static struct ast_cli_entry utils_cli[] = {
00952    AST_CLI_DEFINE(handle_show_locks, "Show which locks are held by which thread"),
00953 };
00954 
00955 #endif /* DEBUG_THREADS */
00956 
00957 /*
00958  * support for 'show threads'. The start routine is wrapped by
00959  * dummy_start(), so that ast_register_thread() and
00960  * ast_unregister_thread() know the thread identifier.
00961  */
00962 struct thr_arg {
00963    void *(*start_routine)(void *);
00964    void *data;
00965    char *name;
00966 };
00967 
00968 /*
00969  * on OS/X, pthread_cleanup_push() and pthread_cleanup_pop()
00970  * are odd macros which start and end a block, so they _must_ be
00971  * used in pairs (the latter with a '1' argument to call the
00972  * handler on exit.
00973  * On BSD we don't need this, but we keep it for compatibility.
00974  */
00975 static void *dummy_start(void *data)
00976 {
00977    void *ret;
00978    struct thr_arg a = *((struct thr_arg *) data);  /* make a local copy */
00979 #ifdef DEBUG_THREADS
00980    struct thr_lock_info *lock_info;
00981    pthread_mutexattr_t mutex_attr;
00982 #endif
00983 
00984    /* note that even though data->name is a pointer to allocated memory,
00985       we are not freeing it here because ast_register_thread is going to
00986       keep a copy of the pointer and then ast_unregister_thread will
00987       free the memory
00988    */
00989    ast_free(data);
00990    ast_register_thread(a.name);
00991    pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
00992 
00993 #ifdef DEBUG_THREADS
00994    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
00995       return NULL;
00996 
00997    lock_info->thread_id = pthread_self();
00998    lock_info->thread_name = strdup(a.name);
00999 
01000    pthread_mutexattr_init(&mutex_attr);
01001    pthread_mutexattr_settype(&mutex_attr, AST_MUTEX_KIND);
01002    pthread_mutex_init(&lock_info->lock, &mutex_attr);
01003    pthread_mutexattr_destroy(&mutex_attr);
01004 
01005    pthread_mutex_lock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
01006    AST_LIST_INSERT_TAIL(&lock_infos, lock_info, entry);
01007    pthread_mutex_unlock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
01008 #endif /* DEBUG_THREADS */
01009 
01010    ret = a.start_routine(a.data);
01011 
01012    pthread_cleanup_pop(1);
01013 
01014    return ret;
01015 }
01016 
01017 #endif /* !LOW_MEMORY */
01018 
01019 int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
01020               void *data, size_t stacksize, const char *file, const char *caller,
01021               int line, const char *start_fn)
01022 {
01023 #if !defined(LOW_MEMORY)
01024    struct thr_arg *a;
01025 #endif
01026 
01027    if (!attr) {
01028       attr = alloca(sizeof(*attr));
01029       pthread_attr_init(attr);
01030    }
01031 
01032 #ifdef __linux__
01033    /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
01034       which is kind of useless. Change this here to
01035       PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
01036       priority will propagate down to new threads by default.
01037       This does mean that callers cannot set a different priority using
01038       PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
01039       the priority afterwards with pthread_setschedparam(). */
01040    if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
01041       ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
01042 #endif
01043 
01044    if (!stacksize)
01045       stacksize = AST_STACKSIZE;
01046 
01047    if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
01048       ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
01049 
01050 #if !defined(LOW_MEMORY)
01051    if ((a = ast_malloc(sizeof(*a)))) {
01052       a->start_routine = start_routine;
01053       a->data = data;
01054       start_routine = dummy_start;
01055       if (asprintf(&a->name, "%-20s started at [%5d] %s %s()",
01056               start_fn, line, file, caller) < 0) {
01057          ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
01058          a->name = NULL;
01059       }
01060       data = a;
01061    }
01062 #endif /* !LOW_MEMORY */
01063 
01064    return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
01065 }
01066 
01067 
01068 int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
01069               void *data, size_t stacksize, const char *file, const char *caller,
01070               int line, const char *start_fn)
01071 {
01072    unsigned char attr_destroy = 0;
01073    int res;
01074 
01075    if (!attr) {
01076       attr = alloca(sizeof(*attr));
01077       pthread_attr_init(attr);
01078       attr_destroy = 1;
01079    }
01080 
01081    if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
01082       ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
01083 
01084    res = ast_pthread_create_stack(thread, attr, start_routine, data, 
01085                                   stacksize, file, caller, line, start_fn);
01086 
01087    if (attr_destroy)
01088       pthread_attr_destroy(attr);
01089 
01090    return res;
01091 }
01092 
01093 int ast_wait_for_input(int fd, int ms)
01094 {
01095    struct pollfd pfd[1];
01096    memset(pfd, 0, sizeof(pfd));
01097    pfd[0].fd = fd;
01098    pfd[0].events = POLLIN|POLLPRI;
01099    return ast_poll(pfd, 1, ms);
01100 }
01101 
01102 static int ast_wait_for_output(int fd, int timeoutms)
01103 {
01104    struct pollfd pfd = {
01105       .fd = fd,
01106       .events = POLLOUT,
01107    };
01108    int res;
01109    struct timeval start = ast_tvnow();
01110    int elapsed = 0;
01111 
01112    /* poll() until the fd is writable without blocking */
01113    while ((res = ast_poll(&pfd, 1, timeoutms - elapsed)) <= 0) {
01114       if (res == 0) {
01115          /* timed out. */
01116 #ifndef STANDALONE
01117          ast_debug(1, "Timed out trying to write\n");
01118 #endif
01119          return -1;
01120       } else if (res == -1) {
01121          /* poll() returned an error, check to see if it was fatal */
01122 
01123          if (errno == EINTR || errno == EAGAIN) {
01124             elapsed = ast_tvdiff_ms(ast_tvnow(), start);
01125             if (elapsed >= timeoutms) {
01126                return -1;
01127             }
01128             /* This was an acceptable error, go back into poll() */
01129             continue;
01130          }
01131 
01132          /* Fatal error, bail. */
01133          ast_log(LOG_ERROR, "poll returned error: %s\n", strerror(errno));
01134 
01135          return -1;
01136       }
01137       elapsed = ast_tvdiff_ms(ast_tvnow(), start);
01138       if (elapsed >= timeoutms) {
01139          return -1;
01140       }
01141    }
01142 
01143    return 0;
01144 }
01145 
01146 /*!
01147  * Try to write string, but wait no more than ms milliseconds before timing out.
01148  *
01149  * \note The code assumes that the file descriptor has NONBLOCK set,
01150  * so there is only one system call made to do a write, unless we actually
01151  * have a need to wait.  This way, we get better performance.
01152  * If the descriptor is blocking, all assumptions on the guaranteed
01153  * detail do not apply anymore.
01154  */
01155 int ast_carefulwrite(int fd, char *s, int len, int timeoutms) 
01156 {
01157    struct timeval start = ast_tvnow();
01158    int res = 0;
01159    int elapsed = 0;
01160 
01161    while (len) {
01162       if (ast_wait_for_output(fd, timeoutms - elapsed)) {
01163          return -1;
01164       }
01165 
01166       res = write(fd, s, len);
01167 
01168       if (res < 0 && errno != EAGAIN && errno != EINTR) {
01169          /* fatal error from write() */
01170          ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
01171          return -1;
01172       }
01173 
01174       if (res < 0) {
01175          /* It was an acceptable error */
01176          res = 0;
01177       }
01178 
01179       /* Update how much data we have left to write */
01180       len -= res;
01181       s += res;
01182       res = 0;
01183 
01184       elapsed = ast_tvdiff_ms(ast_tvnow(), start);
01185       if (elapsed >= timeoutms) {
01186          /* We've taken too long to write 
01187           * This is only an error condition if we haven't finished writing. */
01188          res = len ? -1 : 0;
01189          break;
01190       }
01191    }
01192 
01193    return res;
01194 }
01195 
01196 int ast_careful_fwrite(FILE *f, int fd, const char *src, size_t len, int timeoutms)
01197 {
01198    struct timeval start = ast_tvnow();
01199    int n = 0;
01200    int elapsed = 0;
01201 
01202    while (len) {
01203       if (ast_wait_for_output(fd, timeoutms - elapsed)) {
01204          /* poll returned a fatal error, so bail out immediately. */
01205          return -1;
01206       }
01207 
01208       /* Clear any errors from a previous write */
01209       clearerr(f);
01210 
01211       n = fwrite(src, 1, len, f);
01212 
01213       if (ferror(f) && errno != EINTR && errno != EAGAIN) {
01214          /* fatal error from fwrite() */
01215          if (!feof(f)) {
01216             /* Don't spam the logs if it was just that the connection is closed. */
01217             ast_log(LOG_ERROR, "fwrite() returned error: %s\n", strerror(errno));
01218          }
01219          n = -1;
01220          break;
01221       }
01222 
01223       /* Update for data already written to the socket */
01224       len -= n;
01225       src += n;
01226 
01227       elapsed = ast_tvdiff_ms(ast_tvnow(), start);
01228       if (elapsed >= timeoutms) {
01229          /* We've taken too long to write 
01230           * This is only an error condition if we haven't finished writing. */
01231          n = len ? -1 : 0;
01232          break;
01233       }
01234    }
01235 
01236    while (fflush(f)) {
01237       if (errno == EAGAIN || errno == EINTR) {
01238          continue;
01239       }
01240       if (!feof(f)) {
01241          /* Don't spam the logs if it was just that the connection is closed. */
01242          ast_log(LOG_ERROR, "fflush() returned error: %s\n", strerror(errno));
01243       }
01244       n = -1;
01245       break;
01246    }
01247 
01248    return n < 0 ? -1 : 0;
01249 }
01250 
01251 char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
01252 {
01253    char *e;
01254    char *q;
01255 
01256    s = ast_strip(s);
01257    if ((q = strchr(beg_quotes, *s)) && *q != '\0') {
01258       e = s + strlen(s) - 1;
01259       if (*e == *(end_quotes + (q - beg_quotes))) {
01260          s++;
01261          *e = '\0';
01262       }
01263    }
01264 
01265    return s;
01266 }
01267 
01268 char *ast_unescape_semicolon(char *s)
01269 {
01270    char *e;
01271    char *work = s;
01272 
01273    while ((e = strchr(work, ';'))) {
01274       if ((e > work) && (*(e-1) == '\\')) {
01275          memmove(e - 1, e, strlen(e) + 1);
01276          work = e;
01277       } else {
01278          work = e + 1;
01279       }
01280    }
01281 
01282    return s;
01283 }
01284 
01285 /* !\brief unescape some C sequences in place, return pointer to the original string.
01286  */
01287 char *ast_unescape_c(char *src)
01288 {
01289    char c, *ret, *dst;
01290 
01291    if (src == NULL)
01292       return NULL;
01293    for (ret = dst = src; (c = *src++); *dst++ = c ) {
01294       if (c != '\\')
01295          continue;   /* copy char at the end of the loop */
01296       switch ((c = *src++)) {
01297       case '\0':  /* special, trailing '\' */
01298          c = '\\';
01299          break;
01300       case 'b':   /* backspace */
01301          c = '\b';
01302          break;
01303       case 'f':   /* form feed */
01304          c = '\f';
01305          break;
01306       case 'n':
01307          c = '\n';
01308          break;
01309       case 'r':
01310          c = '\r';
01311          break;
01312       case 't':
01313          c = '\t';
01314          break;
01315       }
01316       /* default, use the char literally */
01317    }
01318    *dst = '\0';
01319    return ret;
01320 }
01321 
01322 int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap)
01323 {
01324    int result;
01325 
01326    if (!buffer || !*buffer || !space || !*space)
01327       return -1;
01328 
01329    result = vsnprintf(*buffer, *space, fmt, ap);
01330 
01331    if (result < 0)
01332       return -1;
01333    else if (result > *space)
01334       result = *space;
01335 
01336    *buffer += result;
01337    *space -= result;
01338    return 0;
01339 }
01340 
01341 int ast_build_string(char **buffer, size_t *space, const char *fmt, ...)
01342 {
01343    va_list ap;
01344    int result;
01345 
01346    va_start(ap, fmt);
01347    result = ast_build_string_va(buffer, space, fmt, ap);
01348    va_end(ap);
01349 
01350    return result;
01351 }
01352 
01353 int ast_true(const char *s)
01354 {
01355    if (ast_strlen_zero(s))
01356       return 0;
01357 
01358    /* Determine if this is a true value */
01359    if (!strcasecmp(s, "yes") ||
01360        !strcasecmp(s, "true") ||
01361        !strcasecmp(s, "y") ||
01362        !strcasecmp(s, "t") ||
01363        !strcasecmp(s, "1") ||
01364        !strcasecmp(s, "on"))
01365       return -1;
01366 
01367    return 0;
01368 }
01369 
01370 int ast_false(const char *s)
01371 {
01372    if (ast_strlen_zero(s))
01373       return 0;
01374 
01375    /* Determine if this is a false value */
01376    if (!strcasecmp(s, "no") ||
01377        !strcasecmp(s, "false") ||
01378        !strcasecmp(s, "n") ||
01379        !strcasecmp(s, "f") ||
01380        !strcasecmp(s, "0") ||
01381        !strcasecmp(s, "off"))
01382       return -1;
01383 
01384    return 0;
01385 }
01386 
01387 #define ONE_MILLION  1000000
01388 /*
01389  * put timeval in a valid range. usec is 0..999999
01390  * negative values are not allowed and truncated.
01391  */
01392 static struct timeval tvfix(struct timeval a)
01393 {
01394    if (a.tv_usec >= ONE_MILLION) {
01395       ast_log(LOG_WARNING, "warning too large timestamp %ld.%ld\n",
01396          (long)a.tv_sec, (long int) a.tv_usec);
01397       a.tv_sec += a.tv_usec / ONE_MILLION;
01398       a.tv_usec %= ONE_MILLION;
01399    } else if (a.tv_usec < 0) {
01400       ast_log(LOG_WARNING, "warning negative timestamp %ld.%ld\n",
01401          (long)a.tv_sec, (long int) a.tv_usec);
01402       a.tv_usec = 0;
01403    }
01404    return a;
01405 }
01406 
01407 struct timeval ast_tvadd(struct timeval a, struct timeval b)
01408 {
01409    /* consistency checks to guarantee usec in 0..999999 */
01410    a = tvfix(a);
01411    b = tvfix(b);
01412    a.tv_sec += b.tv_sec;
01413    a.tv_usec += b.tv_usec;
01414    if (a.tv_usec >= ONE_MILLION) {
01415       a.tv_sec++;
01416       a.tv_usec -= ONE_MILLION;
01417    }
01418    return a;
01419 }
01420 
01421 struct timeval ast_tvsub(struct timeval a, struct timeval b)
01422 {
01423    /* consistency checks to guarantee usec in 0..999999 */
01424    a = tvfix(a);
01425    b = tvfix(b);
01426    a.tv_sec -= b.tv_sec;
01427    a.tv_usec -= b.tv_usec;
01428    if (a.tv_usec < 0) {
01429       a.tv_sec-- ;
01430       a.tv_usec += ONE_MILLION;
01431    }
01432    return a;
01433 }
01434 #undef ONE_MILLION
01435 
01436 /*! \brief glibc puts a lock inside random(3), so that the results are thread-safe.
01437  * BSD libc (and others) do not. */
01438 
01439 #ifndef linux
01440 AST_MUTEX_DEFINE_STATIC(randomlock);
01441 #endif
01442 
01443 long int ast_random(void)
01444 {
01445    long int res;
01446 #ifdef HAVE_DEV_URANDOM
01447    if (dev_urandom_fd >= 0) {
01448       int read_res = read(dev_urandom_fd, &res, sizeof(res));
01449       if (read_res > 0) {
01450          long int rm = RAND_MAX;
01451          res = res < 0 ? ~res : res;
01452          rm++;
01453          return res % rm;
01454       }
01455    }
01456 #endif
01457 #ifdef linux
01458    res = random();
01459 #else
01460    ast_mutex_lock(&randomlock);
01461    res = random();
01462    ast_mutex_unlock(&randomlock);
01463 #endif
01464    return res;
01465 }
01466 
01467 char *ast_process_quotes_and_slashes(char *start, char find, char replace_with)
01468 {
01469    char *dataPut = start;
01470    int inEscape = 0;
01471    int inQuotes = 0;
01472 
01473    for (; *start; start++) {
01474       if (inEscape) {
01475          *dataPut++ = *start;       /* Always goes verbatim */
01476          inEscape = 0;
01477       } else {
01478          if (*start == '\\') {
01479             inEscape = 1;      /* Do not copy \ into the data */
01480          } else if (*start == '\'') {
01481             inQuotes = 1 - inQuotes;   /* Do not copy ' into the data */
01482          } else {
01483             /* Replace , with |, unless in quotes */
01484             *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
01485          }
01486       }
01487    }
01488    if (start != dataPut)
01489       *dataPut = 0;
01490    return dataPut;
01491 }
01492 
01493 void ast_join(char *s, size_t len, const char * const w[])
01494 {
01495    int x, ofs = 0;
01496    const char *src;
01497 
01498    /* Join words into a string */
01499    if (!s)
01500       return;
01501    for (x = 0; ofs < len && w[x]; x++) {
01502       if (x > 0)
01503          s[ofs++] = ' ';
01504       for (src = w[x]; *src && ofs < len; src++)
01505          s[ofs++] = *src;
01506    }
01507    if (ofs == len)
01508       ofs--;
01509    s[ofs] = '\0';
01510 }
01511 
01512 /*
01513  * stringfields support routines.
01514  */
01515 
01516 /* this is a little complex... string fields are stored with their
01517    allocated size in the bytes preceding the string; even the
01518    constant 'empty' string has to be this way, so the code that
01519    checks to see if there is enough room for a new string doesn't
01520    have to have any special case checks
01521 */
01522 
01523 static const struct {
01524    ast_string_field_allocation allocation;
01525    char string[1];
01526 } __ast_string_field_empty_buffer;
01527 
01528 ast_string_field __ast_string_field_empty = __ast_string_field_empty_buffer.string;
01529 
01530 #define ALLOCATOR_OVERHEAD 48
01531 
01532 static size_t optimal_alloc_size(size_t size)
01533 {
01534    unsigned int count;
01535 
01536    size += ALLOCATOR_OVERHEAD;
01537 
01538    for (count = 1; size; size >>= 1, count++);
01539 
01540    return (1 << count) - ALLOCATOR_OVERHEAD;
01541 }
01542 
01543 /*! \brief add a new block to the pool.
01544  * We can only allocate from the topmost pool, so the
01545  * fields in *mgr reflect the size of that only.
01546  */
01547 static int add_string_pool(struct ast_string_field_mgr *mgr, struct ast_string_field_pool **pool_head,
01548             size_t size, const char *file, int lineno, const char *func)
01549 {
01550    struct ast_string_field_pool *pool;
01551    size_t alloc_size = optimal_alloc_size(sizeof(*pool) + size);
01552 
01553 #if defined(__AST_DEBUG_MALLOC)
01554    if (!(pool = __ast_calloc(1, alloc_size, file, lineno, func))) {
01555       return -1;
01556    }
01557 #else
01558    if (!(pool = ast_calloc(1, alloc_size))) {
01559       return -1;
01560    }
01561 #endif
01562 
01563    pool->prev = *pool_head;
01564    pool->size = alloc_size - sizeof(*pool);
01565    *pool_head = pool;
01566    mgr->last_alloc = NULL;
01567 
01568    return 0;
01569 }
01570 
01571 /*
01572  * This is an internal API, code should not use it directly.
01573  * It initializes all fields as empty, then uses 'size' for 3 functions:
01574  * size > 0 means initialize the pool list with a pool of given size.
01575  * This must be called right after allocating the object.
01576  * size = 0 means release all pools except the most recent one.
01577  *      If the first pool was allocated via embedding in another
01578  *      object, that pool will be preserved instead.
01579  * This is useful to e.g. reset an object to the initial value.
01580  * size < 0 means release all pools.
01581  * This must be done before destroying the object.
01582  */
01583 int __ast_string_field_init(struct ast_string_field_mgr *mgr, struct ast_string_field_pool **pool_head,
01584              int needed, const char *file, int lineno, const char *func)
01585 {
01586    const char **p = (const char **) pool_head + 1;
01587    struct ast_string_field_pool *cur = NULL;
01588    struct ast_string_field_pool *preserve = NULL;
01589 
01590    /* clear fields - this is always necessary */
01591    while ((struct ast_string_field_mgr *) p != mgr) {
01592       *p++ = __ast_string_field_empty;
01593    }
01594 
01595    mgr->last_alloc = NULL;
01596 #if defined(__AST_DEBUG_MALLOC)
01597    mgr->owner_file = file;
01598    mgr->owner_func = func;
01599    mgr->owner_line = lineno;
01600 #endif
01601    if (needed > 0) {    /* allocate the initial pool */
01602       *pool_head = NULL;
01603       mgr->embedded_pool = NULL;
01604       return add_string_pool(mgr, pool_head, needed, file, lineno, func);
01605    }
01606 
01607    /* if there is an embedded pool, we can't actually release *all*
01608     * pools, we must keep the embedded one. if the caller is about
01609     * to free the structure that contains the stringfield manager
01610     * and embedded pool anyway, it will be freed as part of that
01611     * operation.
01612     */
01613    if ((needed < 0) && mgr->embedded_pool) {
01614       needed = 0;
01615    }
01616 
01617    if (needed < 0) {    /* reset all pools */
01618       cur = *pool_head;
01619    } else if (mgr->embedded_pool) { /* preserve the embedded pool */
01620       preserve = mgr->embedded_pool;
01621       cur = *pool_head;
01622    } else {       /* preserve the last pool */
01623       if (*pool_head == NULL) {
01624          ast_log(LOG_WARNING, "trying to reset empty pool\n");
01625          return -1;
01626       }
01627       preserve = *pool_head;
01628       cur = preserve->prev;
01629    }
01630 
01631    if (preserve) {
01632       preserve->prev = NULL;
01633       preserve->used = preserve->active = 0;
01634    }
01635 
01636    while (cur) {
01637       struct ast_string_field_pool *prev = cur->prev;
01638 
01639       if (cur != preserve) {
01640          ast_free(cur);
01641       }
01642       cur = prev;
01643    }
01644 
01645    *pool_head = preserve;
01646 
01647    return 0;
01648 }
01649 
01650 ast_string_field __ast_string_field_alloc_space(struct ast_string_field_mgr *mgr,
01651                   struct ast_string_field_pool **pool_head, size_t needed)
01652 {
01653    char *result = NULL;
01654    size_t space = (*pool_head)->size - (*pool_head)->used;
01655    size_t to_alloc;
01656 
01657    /* Make room for ast_string_field_allocation and make it a multiple of that. */
01658    to_alloc = ast_make_room_for(needed, ast_string_field_allocation);
01659    ast_assert(to_alloc % ast_alignof(ast_string_field_allocation) == 0);
01660 
01661    if (__builtin_expect(to_alloc > space, 0)) {
01662       size_t new_size = (*pool_head)->size;
01663 
01664       while (new_size < to_alloc) {
01665          new_size *= 2;
01666       }
01667 
01668 #if defined(__AST_DEBUG_MALLOC)
01669       if (add_string_pool(mgr, pool_head, new_size, mgr->owner_file, mgr->owner_line, mgr->owner_func))
01670          return NULL;
01671 #else
01672       if (add_string_pool(mgr, pool_head, new_size, __FILE__, __LINE__, __FUNCTION__))
01673          return NULL;
01674 #endif
01675    }
01676 
01677    /* pool->base is always aligned (gcc aligned attribute). We ensure that
01678     * to_alloc is also a multiple of ast_alignof(ast_string_field_allocation)
01679     * causing result to always be aligned as well; which in turn fixes that
01680     * AST_STRING_FIELD_ALLOCATION(result) is aligned. */
01681    result = (*pool_head)->base + (*pool_head)->used;
01682    (*pool_head)->used += to_alloc;
01683    (*pool_head)->active += needed;
01684    result += ast_alignof(ast_string_field_allocation);
01685    AST_STRING_FIELD_ALLOCATION(result) = needed;
01686    mgr->last_alloc = result;
01687 
01688    return result;
01689 }
01690 
01691 int __ast_string_field_ptr_grow(struct ast_string_field_mgr *mgr,
01692             struct ast_string_field_pool **pool_head, size_t needed,
01693             const ast_string_field *ptr)
01694 {
01695    ssize_t grow = needed - AST_STRING_FIELD_ALLOCATION(*ptr);
01696    size_t space = (*pool_head)->size - (*pool_head)->used;
01697 
01698    if (*ptr != mgr->last_alloc) {
01699       return 1;
01700    }
01701 
01702    if (space < grow) {
01703       return 1;
01704    }
01705 
01706    (*pool_head)->used += grow;
01707    (*pool_head)->active += grow;
01708    AST_STRING_FIELD_ALLOCATION(*ptr) += grow;
01709 
01710    return 0;
01711 }
01712 
01713 void __ast_string_field_release_active(struct ast_string_field_pool *pool_head,
01714                    const ast_string_field ptr)
01715 {
01716    struct ast_string_field_pool *pool, *prev;
01717 
01718    if (ptr == __ast_string_field_empty) {
01719       return;
01720    }
01721 
01722    for (pool = pool_head, prev = NULL; pool; prev = pool, pool = pool->prev) {
01723       if ((ptr >= pool->base) && (ptr <= (pool->base + pool->size))) {
01724          pool->active -= AST_STRING_FIELD_ALLOCATION(ptr);
01725          if ((pool->active == 0) && prev) {
01726             prev->prev = pool->prev;
01727             ast_free(pool);
01728          }
01729          break;
01730       }
01731    }
01732 }
01733 
01734 void __ast_string_field_ptr_build_va(struct ast_string_field_mgr *mgr,
01735                  struct ast_string_field_pool **pool_head,
01736                  ast_string_field *ptr, const char *format, va_list ap)
01737 {
01738    size_t needed;
01739    size_t available;
01740    size_t space = (*pool_head)->size - (*pool_head)->used;
01741    ssize_t grow;
01742    char *target;
01743    va_list ap2;
01744 
01745    /* if the field already has space allocated, try to reuse it;
01746       otherwise, try to use the empty space at the end of the current
01747       pool
01748    */
01749    if (*ptr != __ast_string_field_empty) {
01750       target = (char *) *ptr;
01751       available = AST_STRING_FIELD_ALLOCATION(*ptr);
01752       if (*ptr == mgr->last_alloc) {
01753          available += space;
01754       }
01755    } else {
01756       /* pool->used is always a multiple of ast_alignof(ast_string_field_allocation)
01757        * so we don't need to re-align anything here.
01758        */
01759       target = (*pool_head)->base + (*pool_head)->used + ast_alignof(ast_string_field_allocation);
01760       available = space - ast_alignof(ast_string_field_allocation);
01761    }
01762 
01763    va_copy(ap2, ap);
01764    needed = vsnprintf(target, available, format, ap2) + 1;
01765    va_end(ap2);
01766 
01767    if (needed > available) {
01768       /* the allocation could not be satisfied using the field's current allocation
01769          (if it has one), or the space available in the pool (if it does not). allocate
01770          space for it, adding a new string pool if necessary.
01771       */
01772       if (!(target = (char *) __ast_string_field_alloc_space(mgr, pool_head, needed))) {
01773          return;
01774       }
01775       vsprintf(target, format, ap);
01776       va_end(ap);
01777       __ast_string_field_release_active(*pool_head, *ptr);
01778       *ptr = target;
01779    } else if (*ptr != target) {
01780       /* the allocation was satisfied using available space in the pool, but not
01781          using the space already allocated to the field
01782       */
01783       __ast_string_field_release_active(*pool_head, *ptr);
01784       mgr->last_alloc = *ptr = target;
01785       AST_STRING_FIELD_ALLOCATION(target) = needed;
01786       (*pool_head)->used += ast_make_room_for(needed, ast_string_field_allocation);
01787       (*pool_head)->active += needed;
01788    } else if ((grow = (needed - AST_STRING_FIELD_ALLOCATION(*ptr))) > 0) {
01789       /* the allocation was satisfied by using available space in the pool *and*
01790          the field was the last allocated field from the pool, so it grew
01791       */
01792       AST_STRING_FIELD_ALLOCATION(*ptr) += grow;
01793       (*pool_head)->used += ast_align_for(grow, ast_string_field_allocation);
01794       (*pool_head)->active += grow;
01795    }
01796 }
01797 
01798 void __ast_string_field_ptr_build(struct ast_string_field_mgr *mgr,
01799               struct ast_string_field_pool **pool_head,
01800               ast_string_field *ptr, const char *format, ...)
01801 {
01802    va_list ap;
01803 
01804    va_start(ap, format);
01805    __ast_string_field_ptr_build_va(mgr, pool_head, ptr, format, ap);
01806    va_end(ap);
01807 }
01808 
01809 void *__ast_calloc_with_stringfields(unsigned int num_structs, size_t struct_size, size_t field_mgr_offset,
01810                  size_t field_mgr_pool_offset, size_t pool_size, const char *file,
01811                  int lineno, const char *func)
01812 {
01813    struct ast_string_field_mgr *mgr;
01814    struct ast_string_field_pool *pool;
01815    struct ast_string_field_pool **pool_head;
01816    size_t pool_size_needed = sizeof(*pool) + pool_size;
01817    size_t size_to_alloc = optimal_alloc_size(struct_size + pool_size_needed);
01818    void *allocation;
01819    unsigned int x;
01820 
01821 #if defined(__AST_DEBUG_MALLOC)  
01822    if (!(allocation = __ast_calloc(num_structs, size_to_alloc, file, lineno, func))) {
01823       return NULL;
01824    }
01825 #else
01826    if (!(allocation = ast_calloc(num_structs, size_to_alloc))) {
01827       return NULL;
01828    }
01829 #endif
01830 
01831    for (x = 0; x < num_structs; x++) {
01832       void *base = allocation + (size_to_alloc * x);
01833       const char **p;
01834 
01835       mgr = base + field_mgr_offset;
01836       pool_head = base + field_mgr_pool_offset;
01837       pool = base + struct_size;
01838 
01839       p = (const char **) pool_head + 1;
01840       while ((struct ast_string_field_mgr *) p != mgr) {
01841          *p++ = __ast_string_field_empty;
01842       }
01843 
01844       mgr->embedded_pool = pool;
01845       *pool_head = pool;
01846       pool->size = size_to_alloc - struct_size - sizeof(*pool);
01847 #if defined(__AST_DEBUG_MALLOC)
01848       mgr->owner_file = file;
01849       mgr->owner_func = func;
01850       mgr->owner_line = lineno;
01851 #endif
01852    }
01853 
01854    return allocation;
01855 }
01856 
01857 /* end of stringfields support */
01858 
01859 AST_MUTEX_DEFINE_STATIC(fetchadd_m); /* used for all fetc&add ops */
01860 
01861 int ast_atomic_fetchadd_int_slow(volatile int *p, int v)
01862 {
01863    int ret;
01864    ast_mutex_lock(&fetchadd_m);
01865    ret = *p;
01866    *p += v;
01867    ast_mutex_unlock(&fetchadd_m);
01868    return ret;
01869 }
01870 
01871 /*! \brief
01872  * get values from config variables.
01873  */
01874 int ast_get_timeval(const char *src, struct timeval *dst, struct timeval _default, int *consumed)
01875 {
01876    long double dtv = 0.0;
01877    int scanned;
01878 
01879    if (dst == NULL)
01880       return -1;
01881 
01882    *dst = _default;
01883 
01884    if (ast_strlen_zero(src))
01885       return -1;
01886 
01887    /* only integer at the moment, but one day we could accept more formats */
01888    if (sscanf(src, "%30Lf%n", &dtv, &scanned) > 0) {
01889       dst->tv_sec = dtv;
01890       dst->tv_usec = (dtv - dst->tv_sec) * 1000000.0;
01891       if (consumed)
01892          *consumed = scanned;
01893       return 0;
01894    } else
01895       return -1;
01896 }
01897 
01898 /*! \brief
01899  * get values from config variables.
01900  */
01901 int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed)
01902 {
01903    long t;
01904    int scanned;
01905 
01906    if (dst == NULL)
01907       return -1;
01908 
01909    *dst = _default;
01910 
01911    if (ast_strlen_zero(src))
01912       return -1;
01913 
01914    /* only integer at the moment, but one day we could accept more formats */
01915    if (sscanf(src, "%30ld%n", &t, &scanned) == 1) {
01916       *dst = t;
01917       if (consumed)
01918          *consumed = scanned;
01919       return 0;
01920    } else
01921       return -1;
01922 }
01923 
01924 void ast_enable_packet_fragmentation(int sock)
01925 {
01926 #if defined(HAVE_IP_MTU_DISCOVER)
01927    int val = IP_PMTUDISC_DONT;
01928    
01929    if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
01930       ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
01931 #endif /* HAVE_IP_MTU_DISCOVER */
01932 }
01933 
01934 int ast_mkdir(const char *path, int mode)
01935 {
01936    char *ptr;
01937    int len = strlen(path), count = 0, x, piececount = 0;
01938    char *tmp = ast_strdupa(path);
01939    char **pieces;
01940    char *fullpath = alloca(len + 1);
01941    int res = 0;
01942 
01943    for (ptr = tmp; *ptr; ptr++) {
01944       if (*ptr == '/')
01945          count++;
01946    }
01947 
01948    /* Count the components to the directory path */
01949    pieces = alloca(count * sizeof(*pieces));
01950    for (ptr = tmp; *ptr; ptr++) {
01951       if (*ptr == '/') {
01952          *ptr = '\0';
01953          pieces[piececount++] = ptr + 1;
01954       }
01955    }
01956 
01957    *fullpath = '\0';
01958    for (x = 0; x < piececount; x++) {
01959       /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
01960       strcat(fullpath, "/");
01961       strcat(fullpath, pieces[x]);
01962       res = mkdir(fullpath, mode);
01963       if (res && errno != EEXIST)
01964          return errno;
01965    }
01966    return 0;
01967 }
01968 
01969 int ast_utils_init(void)
01970 {
01971 #ifdef HAVE_DEV_URANDOM
01972    dev_urandom_fd = open("/dev/urandom", O_RDONLY);
01973 #endif
01974    base64_init();
01975 #ifdef DEBUG_THREADS
01976 #if !defined(LOW_MEMORY)
01977    ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
01978 #endif
01979 #endif
01980    return 0;
01981 }
01982 
01983 
01984 /*!
01985  *\brief Parse digest authorization header.
01986  *\return Returns -1 if we have no auth or something wrong with digest.
01987  *\note  This function may be used for Digest request and responce header.
01988  * request arg is set to nonzero, if we parse Digest Request.
01989  * pedantic arg can be set to nonzero if we need to do addition Digest check.
01990  */
01991 int ast_parse_digest(const char *digest, struct ast_http_digest *d, int request, int pedantic) {
01992    int i;
01993    char *c, key[512], val[512];
01994    struct ast_str *str = ast_str_create(16);
01995 
01996    if (ast_strlen_zero(digest) || !d || !str) {
01997       ast_free(str);
01998       return -1;
01999    }
02000 
02001    ast_str_set(&str, 0, "%s", digest);
02002 
02003    c = ast_skip_blanks(ast_str_buffer(str));
02004 
02005    if (strncasecmp(c, "Digest ", strlen("Digest "))) {
02006       ast_log(LOG_WARNING, "Missing Digest.\n");
02007       ast_free(str);
02008       return -1;
02009    }
02010    c += strlen("Digest ");
02011 
02012    /* lookup for keys/value pair */
02013    while (*c && *(c = ast_skip_blanks(c))) {
02014       /* find key */
02015       i = 0;
02016       while (*c && *c != '=' && *c != ',' && !isspace(*c)) {
02017          key[i++] = *c++;
02018       }
02019       key[i] = '\0';
02020       c = ast_skip_blanks(c);
02021       if (*c == '=') {
02022          c = ast_skip_blanks(++c);
02023          i = 0;
02024          if (*c == '\"') {
02025             /* in quotes. Skip first and look for last */
02026             c++;
02027             while (*c && *c != '\"') {
02028                if (*c == '\\' && c[1] != '\0') { /* unescape chars */
02029                   c++;
02030                }
02031                val[i++] = *c++;
02032             }
02033          } else {
02034             /* token */
02035             while (*c && *c != ',' && !isspace(*c)) {
02036                val[i++] = *c++;
02037             }
02038          }
02039          val[i] = '\0';
02040       }
02041 
02042       while (*c && *c != ',') {
02043          c++;
02044       }
02045       if (*c) {
02046          c++;
02047       }
02048 
02049       if (!strcasecmp(key, "username")) {
02050          ast_string_field_set(d, username, val);
02051       } else if (!strcasecmp(key, "realm")) {
02052          ast_string_field_set(d, realm, val);
02053       } else if (!strcasecmp(key, "nonce")) {
02054          ast_string_field_set(d, nonce, val);
02055       } else if (!strcasecmp(key, "uri")) {
02056          ast_string_field_set(d, uri, val);
02057       } else if (!strcasecmp(key, "domain")) {
02058          ast_string_field_set(d, domain, val);
02059       } else if (!strcasecmp(key, "response")) {
02060          ast_string_field_set(d, response, val);
02061       } else if (!strcasecmp(key, "algorithm")) {
02062          if (strcasecmp(val, "MD5")) {
02063             ast_log(LOG_WARNING, "Digest algorithm: \"%s\" not supported.\n", val);
02064             return -1;
02065          }
02066       } else if (!strcasecmp(key, "cnonce")) {
02067          ast_string_field_set(d, cnonce, val);
02068       } else if (!strcasecmp(key, "opaque")) {
02069          ast_string_field_set(d, opaque, val);
02070       } else if (!strcasecmp(key, "qop") && !strcasecmp(val, "auth")) {
02071          d->qop = 1;
02072       } else if (!strcasecmp(key, "nc")) {
02073          unsigned long u;
02074          if (sscanf(val, "%30lx", &u) != 1) {
02075             ast_log(LOG_WARNING, "Incorrect Digest nc value: \"%s\".\n", val);
02076             return -1;
02077          }
02078          ast_string_field_set(d, nc, val);
02079       }
02080    }
02081    ast_free(str);
02082 
02083    /* Digest checkout */
02084    if (ast_strlen_zero(d->realm) || ast_strlen_zero(d->nonce)) {
02085       /* "realm" and "nonce" MUST be always exist */
02086       return -1;
02087    }
02088 
02089    if (!request) {
02090       /* Additional check for Digest response */
02091       if (ast_strlen_zero(d->username) || ast_strlen_zero(d->uri) || ast_strlen_zero(d->response)) {
02092          return -1;
02093       }
02094 
02095       if (pedantic && d->qop && (ast_strlen_zero(d->cnonce) || ast_strlen_zero(d->nc))) {
02096          return -1;
02097       }
02098    }
02099 
02100    return 0;
02101 }
02102 
02103 #ifndef __AST_DEBUG_MALLOC
02104 int _ast_asprintf(char **ret, const char *file, int lineno, const char *func, const char *fmt, ...)
02105 {
02106    int res;
02107    va_list ap;
02108 
02109    va_start(ap, fmt);
02110    if ((res = vasprintf(ret, fmt, ap)) == -1) {
02111       MALLOC_FAILURE_MSG;
02112    }
02113    va_end(ap);
02114 
02115    return res;
02116 }
02117 #endif
02118 
02119 int ast_get_tid(void)
02120 {
02121    int ret = -1;
02122 #if defined (__linux) && defined(SYS_gettid)
02123    ret = syscall(SYS_gettid); /* available since Linux 1.4.11 */
02124 #elif defined(__sun)
02125    ret = pthread_self();
02126 #elif defined(__APPLE__)
02127    ret = mach_thread_self();
02128    mach_port_deallocate(mach_task_self(), ret);
02129 #elif defined(__FreeBSD__) && defined(HAVE_SYS_THR_H)
02130    long lwpid;
02131    thr_self(&lwpid); /* available since sys/thr.h creation 2003 */
02132    ret = lwpid;
02133 #endif
02134    return ret;
02135 }
02136 
02137 char *ast_utils_which(const char *binary, char *fullpath, size_t fullpath_size)
02138 {
02139    const char *envPATH = getenv("PATH");
02140    char *tpath, *path;
02141    struct stat unused;
02142    if (!envPATH) {
02143       return NULL;
02144    }
02145    tpath = ast_strdupa(envPATH);
02146    while ((path = strsep(&tpath, ":"))) {
02147       snprintf(fullpath, fullpath_size, "%s/%s", path, binary);
02148       if (!stat(fullpath, &unused)) {
02149          return fullpath;
02150       }
02151    }
02152    return NULL;
02153 }
02154 

Generated on Thu Feb 9 06:34:01 2012 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.6