Fri Aug 24 02:22:17 2007

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$")
00029 
00030 #include <ctype.h>
00031 #include <string.h>
00032 #include <unistd.h>
00033 #include <stdlib.h>
00034 #include <errno.h>
00035 #include <stdarg.h>
00036 #include <stdio.h>
00037 #include <sys/types.h>
00038 #include <sys/socket.h>
00039 #include <netinet/in.h>
00040 #include <arpa/inet.h>
00041 
00042 #define AST_API_MODULE     /* ensure that inlinable API functions will be built in lock.h if required */
00043 #include "asterisk/lock.h"
00044 #include "asterisk/io.h"
00045 #include "asterisk/logger.h"
00046 #include "asterisk/md5.h"
00047 #include "asterisk/sha1.h"
00048 #include "asterisk/options.h"
00049 #include "asterisk/cli.h"
00050 #include "asterisk/linkedlists.h"
00051 
00052 #define AST_API_MODULE     /* ensure that inlinable API functions will be built in this module if required */
00053 #include "asterisk/strings.h"
00054 
00055 #define AST_API_MODULE     /* ensure that inlinable API functions will be built in this module if required */
00056 #include "asterisk/time.h"
00057 
00058 #define AST_API_MODULE     /* ensure that inlinable API functions will be built in this module if required */
00059 #include "asterisk/stringfields.h"
00060 
00061 #define AST_API_MODULE     /* ensure that inlinable API functions will be built in this module if required */
00062 #include "asterisk/utils.h"
00063 
00064 #define AST_API_MODULE
00065 #include "asterisk/threadstorage.h"
00066 
00067 static char base64[64];
00068 static char b2a[256];
00069 
00070 AST_THREADSTORAGE(inet_ntoa_buf, inet_ntoa_buf_init);
00071 
00072 #if !defined(HAVE_GETHOSTBYNAME_R_5) && !defined(HAVE_GETHOSTBYNAME_R_6)
00073 
00074 #define ERANGE 34 /*!< duh? ERANGE value copied from web... */
00075 #undef gethostbyname
00076 
00077 AST_MUTEX_DEFINE_STATIC(__mutex);
00078 
00079 /*! \brief Reentrant replacement for gethostbyname for BSD-based systems.
00080 \note This
00081 routine is derived from code originally written and placed in the public 
00082 domain by Enzo Michelangeli <em@em.no-ip.com> */
00083 
00084 static int gethostbyname_r (const char *name, struct hostent *ret, char *buf,
00085             size_t buflen, struct hostent **result, 
00086             int *h_errnop) 
00087 {
00088    int hsave;
00089    struct hostent *ph;
00090    ast_mutex_lock(&__mutex); /* begin critical area */
00091    hsave = h_errno;
00092 
00093    ph = gethostbyname(name);
00094    *h_errnop = h_errno; /* copy h_errno to *h_herrnop */
00095    if (ph == NULL) {
00096       *result = NULL;
00097    } else {
00098       char **p, **q;
00099       char *pbuf;
00100       int nbytes=0;
00101       int naddr=0, naliases=0;
00102       /* determine if we have enough space in buf */
00103 
00104       /* count how many addresses */
00105       for (p = ph->h_addr_list; *p != 0; p++) {
00106          nbytes += ph->h_length; /* addresses */
00107          nbytes += sizeof(*p); /* pointers */
00108          naddr++;
00109       }
00110       nbytes += sizeof(*p); /* one more for the terminating NULL */
00111 
00112       /* count how many aliases, and total length of strings */
00113       for (p = ph->h_aliases; *p != 0; p++) {
00114          nbytes += (strlen(*p)+1); /* aliases */
00115          nbytes += sizeof(*p);  /* pointers */
00116          naliases++;
00117       }
00118       nbytes += sizeof(*p); /* one more for the terminating NULL */
00119 
00120       /* here nbytes is the number of bytes required in buffer */
00121       /* as a terminator must be there, the minimum value is ph->h_length */
00122       if (nbytes > buflen) {
00123          *result = NULL;
00124          ast_mutex_unlock(&__mutex); /* end critical area */
00125          return ERANGE; /* not enough space in buf!! */
00126       }
00127 
00128       /* There is enough space. Now we need to do a deep copy! */
00129       /* Allocation in buffer:
00130          from [0] to [(naddr-1) * sizeof(*p)]:
00131          pointers to addresses
00132          at [naddr * sizeof(*p)]:
00133          NULL
00134          from [(naddr+1) * sizeof(*p)] to [(naddr+naliases) * sizeof(*p)] :
00135          pointers to aliases
00136          at [(naddr+naliases+1) * sizeof(*p)]:
00137          NULL
00138          then naddr addresses (fixed length), and naliases aliases (asciiz).
00139       */
00140 
00141       *ret = *ph;   /* copy whole structure (not its address!) */
00142 
00143       /* copy addresses */
00144       q = (char **)buf; /* pointer to pointers area (type: char **) */
00145       ret->h_addr_list = q; /* update pointer to address list */
00146       pbuf = buf + ((naddr + naliases + 2) * sizeof(*p)); /* skip that area */
00147       for (p = ph->h_addr_list; *p != 0; p++) {
00148          memcpy(pbuf, *p, ph->h_length); /* copy address bytes */
00149          *q++ = pbuf; /* the pointer is the one inside buf... */
00150          pbuf += ph->h_length; /* advance pbuf */
00151       }
00152       *q++ = NULL; /* address list terminator */
00153 
00154       /* copy aliases */
00155       ret->h_aliases = q; /* update pointer to aliases list */
00156       for (p = ph->h_aliases; *p != 0; p++) {
00157          strcpy(pbuf, *p); /* copy alias strings */
00158          *q++ = pbuf; /* the pointer is the one inside buf... */
00159          pbuf += strlen(*p); /* advance pbuf */
00160          *pbuf++ = 0; /* string terminator */
00161       }
00162       *q++ = NULL; /* terminator */
00163 
00164       strcpy(pbuf, ph->h_name); /* copy alias strings */
00165       ret->h_name = pbuf;
00166       pbuf += strlen(ph->h_name); /* advance pbuf */
00167       *pbuf++ = 0; /* string terminator */
00168 
00169       *result = ret;  /* and let *result point to structure */
00170 
00171    }
00172    h_errno = hsave;  /* restore h_errno */
00173    ast_mutex_unlock(&__mutex); /* end critical area */
00174 
00175    return (*result == NULL); /* return 0 on success, non-zero on error */
00176 }
00177 
00178 
00179 #endif
00180 
00181 /*! \brief Re-entrant (thread safe) version of gethostbyname that replaces the 
00182    standard gethostbyname (which is not thread safe)
00183 */
00184 struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp)
00185 {
00186    int res;
00187    int herrno;
00188    int dots=0;
00189    const char *s;
00190    struct hostent *result = NULL;
00191    /* Although it is perfectly legitimate to lookup a pure integer, for
00192       the sake of the sanity of people who like to name their peers as
00193       integers, we break with tradition and refuse to look up a
00194       pure integer */
00195    s = host;
00196    res = 0;
00197    while(s && *s) {
00198       if (*s == '.')
00199          dots++;
00200       else if (!isdigit(*s))
00201          break;
00202       s++;
00203    }
00204    if (!s || !*s) {
00205       /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
00206       if (dots != 3)
00207          return NULL;
00208       memset(hp, 0, sizeof(struct ast_hostent));
00209       hp->hp.h_addrtype = AF_INET;
00210       hp->hp.h_addr_list = (void *) hp->buf;
00211       hp->hp.h_addr = hp->buf + sizeof(void *);
00212       if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
00213          return &hp->hp;
00214       return NULL;
00215       
00216    }
00217 #ifdef HAVE_GETHOSTBYNAME_R_5
00218    result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);
00219 
00220    if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
00221       return NULL;
00222 #else
00223    res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
00224 
00225    if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
00226       return NULL;
00227 #endif
00228    return &hp->hp;
00229 }
00230 
00231 
00232 
00233 AST_MUTEX_DEFINE_STATIC(test_lock);
00234 AST_MUTEX_DEFINE_STATIC(test_lock2);
00235 static pthread_t test_thread; 
00236 static int lock_count = 0;
00237 static int test_errors = 0;
00238 
00239 /*! \brief This is a regression test for recursive mutexes.
00240    test_for_thread_safety() will return 0 if recursive mutex locks are
00241    working properly, and non-zero if they are not working properly. */
00242 static void *test_thread_body(void *data) 
00243 { 
00244    ast_mutex_lock(&test_lock);
00245    lock_count += 10;
00246    if (lock_count != 10) 
00247       test_errors++;
00248    ast_mutex_lock(&test_lock);
00249    lock_count += 10;
00250    if (lock_count != 20) 
00251       test_errors++;
00252    ast_mutex_lock(&test_lock2);
00253    ast_mutex_unlock(&test_lock);
00254    lock_count -= 10;
00255    if (lock_count != 10) 
00256       test_errors++;
00257    ast_mutex_unlock(&test_lock);
00258    lock_count -= 10;
00259    ast_mutex_unlock(&test_lock2);
00260    if (lock_count != 0) 
00261       test_errors++;
00262    return NULL;
00263 } 
00264 
00265 int test_for_thread_safety(void)
00266 { 
00267    ast_mutex_lock(&test_lock2);
00268    ast_mutex_lock(&test_lock);
00269    lock_count += 1;
00270    ast_mutex_lock(&test_lock);
00271    lock_count += 1;
00272    ast_pthread_create(&test_thread, NULL, test_thread_body, NULL); 
00273    usleep(100);
00274    if (lock_count != 2) 
00275       test_errors++;
00276    ast_mutex_unlock(&test_lock);
00277    lock_count -= 1;
00278    usleep(100); 
00279    if (lock_count != 1) 
00280       test_errors++;
00281    ast_mutex_unlock(&test_lock);
00282    lock_count -= 1;
00283    if (lock_count != 0) 
00284       test_errors++;
00285    ast_mutex_unlock(&test_lock2);
00286    usleep(100);
00287    if (lock_count != 0) 
00288       test_errors++;
00289    pthread_join(test_thread, NULL);
00290    return(test_errors);          /* return 0 on success. */
00291 }
00292 
00293 /*! \brief Produce 32 char MD5 hash of value. */
00294 void ast_md5_hash(char *output, char *input)
00295 {
00296    struct MD5Context md5;
00297    unsigned char digest[16];
00298    char *ptr;
00299    int x;
00300 
00301    MD5Init(&md5);
00302    MD5Update(&md5, (unsigned char *)input, strlen(input));
00303    MD5Final(digest, &md5);
00304    ptr = output;
00305    for (x = 0; x < 16; x++)
00306       ptr += sprintf(ptr, "%2.2x", digest[x]);
00307 }
00308 
00309 /*! \brief Produce 40 char SHA1 hash of value. */
00310 void ast_sha1_hash(char *output, char *input)
00311 {
00312    struct SHA1Context sha;
00313    char *ptr;
00314    int x;
00315    uint8_t Message_Digest[20];
00316 
00317    SHA1Reset(&sha);
00318    
00319    SHA1Input(&sha, (const unsigned char *) input, strlen(input));
00320 
00321    SHA1Result(&sha, Message_Digest);
00322    ptr = output;
00323    for (x = 0; x < 20; x++)
00324       ptr += sprintf(ptr, "%2.2x", Message_Digest[x]);
00325 }
00326 
00327 /*! \brief decode BASE64 encoded text */
00328 int ast_base64decode(unsigned char *dst, const char *src, int max)
00329 {
00330    int cnt = 0;
00331    unsigned int byte = 0;
00332    unsigned int bits = 0;
00333    int incnt = 0;
00334    while(*src && (cnt < max)) {
00335       /* Shift in 6 bits of input */
00336       byte <<= 6;
00337       byte |= (b2a[(int)(*src)]) & 0x3f;
00338       bits += 6;
00339       src++;
00340       incnt++;
00341       /* If we have at least 8 bits left over, take that character 
00342          off the top */
00343       if (bits >= 8)  {
00344          bits -= 8;
00345          *dst = (byte >> bits) & 0xff;
00346          dst++;
00347          cnt++;
00348       }
00349    }
00350    /* Dont worry about left over bits, they're extra anyway */
00351    return cnt;
00352 }
00353 
00354 /*! \brief encode text to BASE64 coding */
00355 int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
00356 {
00357    int cnt = 0;
00358    int col = 0;
00359    unsigned int byte = 0;
00360    int bits = 0;
00361    int cntin = 0;
00362    /* Reserve space for null byte at end of string */
00363    max--;
00364    while ((cntin < srclen) && (cnt < max)) {
00365       byte <<= 8;
00366       byte |= *(src++);
00367       bits += 8;
00368       cntin++;
00369       if ((bits == 24) && (cnt + 4 <= max)) {
00370          *dst++ = base64[(byte >> 18) & 0x3f];
00371          *dst++ = base64[(byte >> 12) & 0x3f];
00372          *dst++ = base64[(byte >> 6) & 0x3f];
00373          *dst++ = base64[byte & 0x3f];
00374          cnt += 4;
00375          col += 4;
00376          bits = 0;
00377          byte = 0;
00378       }
00379       if (linebreaks && (cnt < max) && (col == 64)) {
00380          *dst++ = '\n';
00381          cnt++;
00382          col = 0;
00383       }
00384    }
00385    if (bits && (cnt + 4 <= max)) {
00386       /* Add one last character for the remaining bits, 
00387          padding the rest with 0 */
00388       byte <<= 24 - bits;
00389       *dst++ = base64[(byte >> 18) & 0x3f];
00390       *dst++ = base64[(byte >> 12) & 0x3f];
00391       if (bits == 16)
00392          *dst++ = base64[(byte >> 6) & 0x3f];
00393       else
00394          *dst++ = '=';
00395       *dst++ = '=';
00396       cnt += 4;
00397    }
00398    if (linebreaks && (cnt < max)) {
00399       *dst++ = '\n';
00400       cnt++;
00401    }
00402    *dst = '\0';
00403    return cnt;
00404 }
00405 
00406 int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
00407 {
00408    return ast_base64encode_full(dst, src, srclen, max, 0);
00409 }
00410 
00411 static void base64_init(void)
00412 {
00413    int x;
00414    memset(b2a, -1, sizeof(b2a));
00415    /* Initialize base-64 Conversion table */
00416    for (x = 0; x < 26; x++) {
00417       /* A-Z */
00418       base64[x] = 'A' + x;
00419       b2a['A' + x] = x;
00420       /* a-z */
00421       base64[x + 26] = 'a' + x;
00422       b2a['a' + x] = x + 26;
00423       /* 0-9 */
00424       if (x < 10) {
00425          base64[x + 52] = '0' + x;
00426          b2a['0' + x] = x + 52;
00427       }
00428    }
00429    base64[62] = '+';
00430    base64[63] = '/';
00431    b2a[(int)'+'] = 62;
00432    b2a[(int)'/'] = 63;
00433 }
00434 
00435 /*! \brief  ast_uri_encode: Turn text string to URI-encoded %XX version
00436 \note    At this point, we're converting from ISO-8859-x (8-bit), not UTF8
00437    as in the SIP protocol spec 
00438    If doreserved == 1 we will convert reserved characters also.
00439    RFC 2396, section 2.4
00440    outbuf needs to have more memory allocated than the instring
00441    to have room for the expansion. Every char that is converted
00442    is replaced by three ASCII characters.
00443 
00444    Note: The doreserved option is needed for replaces header in
00445    SIP transfers.
00446 */
00447 char *ast_uri_encode(const char *string, char *outbuf, int buflen, int doreserved) 
00448 {
00449    char *reserved = ";/?:@&=+$, ";  /* Reserved chars */
00450 
00451    const char *ptr  = string; /* Start with the string */
00452    char *out = NULL;
00453    char *buf = NULL;
00454 
00455    ast_copy_string(outbuf, string, buflen);
00456 
00457    /* If there's no characters to convert, just go through and don't do anything */
00458    while (*ptr) {
00459       if (((unsigned char) *ptr) > 127 || (doreserved && strchr(reserved, *ptr)) ) {
00460          /* Oops, we need to start working here */
00461          if (!buf) {
00462             buf = outbuf;
00463             out = buf + (ptr - string) ;  /* Set output ptr */
00464          }
00465          out += sprintf(out, "%%%02x", (unsigned char) *ptr);
00466       } else if (buf) {
00467          *out = *ptr;   /* Continue copying the string */
00468          out++;
00469       } 
00470       ptr++;
00471    }
00472    if (buf)
00473       *out = '\0';
00474    return outbuf;
00475 }
00476 
00477 /*! \brief  ast_uri_decode: Decode SIP URI, URN, URL (overwrite the string)  */
00478 void ast_uri_decode(char *s) 
00479 {
00480    char *o;
00481    unsigned int tmp;
00482 
00483    for (o = s; *s; s++, o++) {
00484       if (*s == '%' && strlen(s) > 2 && sscanf(s + 1, "%2x", &tmp) == 1) {
00485          /* have '%', two chars and correct parsing */
00486          *o = tmp;
00487          s += 2;  /* Will be incremented once more when we break out */
00488       } else /* all other cases, just copy */
00489          *o = *s;
00490    }
00491    *o = '\0';
00492 }
00493 
00494 /*! \brief  ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa */
00495 const char *ast_inet_ntoa(struct in_addr ia)
00496 {
00497    char *buf;
00498 
00499    if (!(buf = ast_threadstorage_get(&inet_ntoa_buf, INET_ADDRSTRLEN)))
00500       return "";
00501 
00502    return inet_ntop(AF_INET, &ia, buf, INET_ADDRSTRLEN);
00503 }
00504 
00505 #ifndef __linux__
00506 #undef pthread_create /* For ast_pthread_create function only */
00507 #endif /* !__linux__ */
00508 
00509 #if !defined(LOW_MEMORY)
00510 
00511 #ifdef DEBUG_THREADS
00512 
00513 /*! \brief A reasonable maximum number of locks a thread would be holding ... */
00514 #define AST_MAX_LOCKS 16
00515 
00516 /* Allow direct use of pthread_mutex_t and friends */
00517 #undef pthread_mutex_t
00518 #undef pthread_mutex_lock
00519 #undef pthread_mutex_unlock
00520 #undef pthread_mutex_init
00521 #undef pthread_mutex_destroy
00522 
00523 /*! 
00524  * \brief Keep track of which locks a thread holds 
00525  *
00526  * There is an instance of this struct for every active thread
00527  */
00528 struct thr_lock_info {
00529    /*! The thread's ID */
00530    pthread_t thread_id;
00531    /*! The thread name which includes where the thread was started */
00532    const char *thread_name;
00533    /*! This is the actual container of info for what locks this thread holds */
00534    struct {
00535       const char *file;
00536       int line_num;
00537       const char *func;
00538       const char *lock_name;
00539       void *lock_addr;
00540       int times_locked;
00541       /*! This thread is waiting on this lock */
00542       unsigned int pending:1;
00543    } locks[AST_MAX_LOCKS];
00544    /*! This is the number of locks currently held by this thread.
00545     *  The index (num_locks - 1) has the info on the last one in the
00546     *  locks member */
00547    unsigned int num_locks;
00548    /*! Protects the contents of the locks member 
00549     * Intentionally not ast_mutex_t */
00550    pthread_mutex_t lock;
00551    AST_LIST_ENTRY(thr_lock_info) entry;
00552 };
00553 
00554 /*! 
00555  * \brief Locked when accessing the lock_infos list 
00556  */
00557 AST_MUTEX_DEFINE_STATIC(lock_infos_lock);
00558 /*!
00559  * \brief A list of each thread's lock info 
00560  */
00561 static AST_LIST_HEAD_NOLOCK_STATIC(lock_infos, thr_lock_info);
00562 
00563 /*!
00564  * \brief Destroy a thread's lock info
00565  *
00566  * This gets called automatically when the thread stops
00567  */
00568 static void lock_info_destroy(void *data)
00569 {
00570    struct thr_lock_info *lock_info = data;
00571 
00572    pthread_mutex_lock(&lock_infos_lock.mutex);
00573    AST_LIST_REMOVE(&lock_infos, lock_info, entry);
00574    pthread_mutex_unlock(&lock_infos_lock.mutex);
00575 
00576    pthread_mutex_destroy(&lock_info->lock);
00577    free((void *) lock_info->thread_name);
00578    free(lock_info);
00579 }
00580 
00581 /*!
00582  * \brief The thread storage key for per-thread lock info
00583  */
00584 AST_THREADSTORAGE_CUSTOM(thread_lock_info, thread_lock_info_init, lock_info_destroy);
00585 
00586 void ast_store_lock_info(const char *filename, int line_num, 
00587    const char *func, const char *lock_name, void *lock_addr)
00588 {
00589    struct thr_lock_info *lock_info;
00590    int i;
00591 
00592    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
00593       return;
00594 
00595    pthread_mutex_lock(&lock_info->lock);
00596 
00597    for (i = 0; i < lock_info->num_locks; i++) {
00598       if (lock_info->locks[i].lock_addr == lock_addr) {
00599          lock_info->locks[i].times_locked++;
00600          pthread_mutex_unlock(&lock_info->lock);
00601          return;
00602       }
00603    }
00604 
00605    if (lock_info->num_locks == AST_MAX_LOCKS) {
00606       /* Can't use ast_log here, because it will cause infinite recursion */
00607       fprintf(stderr, "XXX ERROR XXX A thread holds more locks than '%d'."
00608          "  Increase AST_MAX_LOCKS!\n", AST_MAX_LOCKS);
00609       pthread_mutex_unlock(&lock_info->lock);
00610       return;
00611    }
00612    
00613    lock_info->locks[i].file = filename;
00614    lock_info->locks[i].line_num = line_num;
00615    lock_info->locks[i].func = func;
00616    lock_info->locks[i].lock_name = lock_name;
00617    lock_info->locks[i].lock_addr = lock_addr;
00618    lock_info->locks[i].times_locked = 1;
00619    lock_info->locks[i].pending = 1;
00620    lock_info->num_locks++;
00621 
00622    pthread_mutex_unlock(&lock_info->lock);
00623 }
00624 
00625 void ast_mark_lock_acquired(void)
00626 {
00627    struct thr_lock_info *lock_info;
00628 
00629    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
00630       return;
00631 
00632    pthread_mutex_lock(&lock_info->lock);
00633    lock_info->locks[lock_info->num_locks - 1].pending = 0;
00634    pthread_mutex_unlock(&lock_info->lock);
00635 }
00636 
00637 void ast_remove_lock_info(void *lock_addr)
00638 {
00639    struct thr_lock_info *lock_info;
00640    int i = 0;
00641 
00642    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
00643       return;
00644 
00645    pthread_mutex_lock(&lock_info->lock);
00646 
00647    for (i = lock_info->num_locks - 1; i >= 0; i--) {
00648       if (lock_info->locks[i].lock_addr == lock_addr)
00649          break;
00650    }
00651 
00652    if (i == -1) {
00653       /* Lock not found :( */
00654       pthread_mutex_unlock(&lock_info->lock);
00655       return;
00656    }
00657 
00658    if (lock_info->locks[i].times_locked > 1) {
00659       lock_info->locks[i].times_locked--;
00660       pthread_mutex_unlock(&lock_info->lock);
00661       return;
00662    }
00663 
00664    if (i < lock_info->num_locks - 1) {
00665       /* Not the last one ... *should* be rare! */
00666       memmove(&lock_info->locks[i], &lock_info->locks[i + 1], 
00667          (lock_info->num_locks - (i + 1)) * sizeof(lock_info->locks[0]));
00668    }
00669 
00670    lock_info->num_locks--;
00671 
00672    pthread_mutex_unlock(&lock_info->lock);
00673 }
00674 
00675 static int handle_show_locks(int fd, int argc, char *argv[])
00676 {
00677    struct thr_lock_info *lock_info;
00678 
00679    ast_cli(fd, "\n" 
00680                "=======================================================================\n"
00681                "=== Currently Held Locks ==============================================\n"
00682                "=======================================================================\n"
00683                "===\n"
00684             "=== <file> <line num> <function> <lock name> <lock addr> (times locked)\n"
00685             "===\n");
00686 
00687    pthread_mutex_lock(&lock_infos_lock.mutex);
00688    AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
00689       int i;
00690       ast_cli(fd, "=== Thread ID: %d (%s)\n", (int) lock_info->thread_id,
00691          lock_info->thread_name);
00692       pthread_mutex_lock(&lock_info->lock);
00693       for (i = 0; i < lock_info->num_locks; i++) {
00694          ast_cli(fd, "=== ---> %sLock #%d: %s %d %s %s %p (%d)\n", 
00695             lock_info->locks[i].pending ? "Waiting for " : "", i,
00696             lock_info->locks[i].file, lock_info->locks[i].line_num,
00697             lock_info->locks[i].func, lock_info->locks[i].lock_name,
00698             lock_info->locks[i].lock_addr, 
00699             lock_info->locks[i].times_locked);
00700       }
00701       pthread_mutex_unlock(&lock_info->lock);
00702       ast_cli(fd, "=== -------------------------------------------------------------------\n"
00703                   "===\n");
00704    }
00705    pthread_mutex_unlock(&lock_infos_lock.mutex);
00706 
00707    ast_cli(fd, "=======================================================================\n"
00708                "\n");
00709 
00710    return 0;
00711 }
00712 
00713 static char show_locks_help[] =
00714 "Usage: core show locks\n"
00715 "       This command is for lock debugging.  It prints out which locks\n"
00716 "are owned by each active thread.\n";
00717 
00718 static struct ast_cli_entry utils_cli[] = {
00719    { { "core", "show", "locks", NULL }, handle_show_locks,
00720      "Show which locks are locked by which thread", show_locks_help },
00721 };
00722 
00723 #endif /* DEBUG_THREADS */
00724 
00725 
00726 
00727 /*
00728  * support for 'show threads'. The start routine is wrapped by
00729  * dummy_start(), so that ast_register_thread() and
00730  * ast_unregister_thread() know the thread identifier.
00731  */
00732 struct thr_arg {
00733    void *(*start_routine)(void *);
00734    void *data;
00735    char *name;
00736 };
00737 
00738 /*
00739  * on OS/X, pthread_cleanup_push() and pthread_cleanup_pop()
00740  * are odd macros which start and end a block, so they _must_ be
00741  * used in pairs (the latter with a '1' argument to call the
00742  * handler on exit.
00743  * On BSD we don't need this, but we keep it for compatibility.
00744  */
00745 static void *dummy_start(void *data)
00746 {
00747    void *ret;
00748    struct thr_arg a = *((struct thr_arg *) data);  /* make a local copy */
00749 #ifdef DEBUG_THREADS
00750    struct thr_lock_info *lock_info;
00751 #endif
00752 
00753    /* note that even though data->name is a pointer to allocated memory,
00754       we are not freeing it here because ast_register_thread is going to
00755       keep a copy of the pointer and then ast_unregister_thread will
00756       free the memory
00757    */
00758    free(data);
00759    ast_register_thread(a.name);
00760    pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
00761 
00762 #ifdef DEBUG_THREADS
00763    if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
00764       return NULL;
00765 
00766    lock_info->thread_id = pthread_self();
00767    lock_info->thread_name = strdup(a.name);
00768    pthread_mutex_init(&lock_info->lock, NULL);
00769 
00770    pthread_mutex_lock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
00771    AST_LIST_INSERT_TAIL(&lock_infos, lock_info, entry);
00772    pthread_mutex_unlock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
00773 #endif /* DEBUG_THREADS */
00774 
00775    ret = a.start_routine(a.data);
00776 
00777    pthread_cleanup_pop(1);
00778 
00779    return ret;
00780 }
00781 
00782 #endif /* !LOW_MEMORY */
00783 
00784 int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
00785               void *data, size_t stacksize, const char *file, const char *caller,
00786               int line, const char *start_fn)
00787 {
00788 #if !defined(LOW_MEMORY)
00789    struct thr_arg *a;
00790 #endif
00791 
00792    if (!attr) {
00793       attr = alloca(sizeof(*attr));
00794       pthread_attr_init(attr);
00795    }
00796 
00797 #ifdef __linux__
00798    /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
00799       which is kind of useless. Change this here to
00800       PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
00801       priority will propagate down to new threads by default.
00802       This does mean that callers cannot set a different priority using
00803       PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
00804       the priority afterwards with pthread_setschedparam(). */
00805    if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
00806       ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
00807 #endif
00808 
00809    if (!stacksize)
00810       stacksize = AST_STACKSIZE;
00811 
00812    if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
00813       ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
00814 
00815 #if !defined(LOW_MEMORY)
00816    if ((a = ast_malloc(sizeof(*a)))) {
00817       a->start_routine = start_routine;
00818       a->data = data;
00819       start_routine = dummy_start;
00820       asprintf(&a->name, "%-20s started at [%5d] %s %s()",
00821           start_fn, line, file, caller);
00822       data = a;
00823    }
00824 #endif /* !LOW_MEMORY */
00825 
00826    return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
00827 }
00828 
00829 int ast_wait_for_input(int fd, int ms)
00830 {
00831    struct pollfd pfd[1];
00832    memset(pfd, 0, sizeof(pfd));
00833    pfd[0].fd = fd;
00834    pfd[0].events = POLLIN|POLLPRI;
00835    return poll(pfd, 1, ms);
00836 }
00837 
00838 /*!
00839  * Try to write string, but wait no more than ms milliseconds before timing out.
00840  *
00841  * \note The code assumes that the file descriptor has NONBLOCK set,
00842  * so there is only one system call made to do a write, unless we actually
00843  * have a need to wait.  This way, we get better performance.
00844  * If the descriptor is blocking, all assumptions on the guaranteed
00845  * detail do not apply anymore.
00846  * Also note that in the current implementation, the delay is per-write,
00847  * so you still have no guarantees, anyways.
00848  * Fortunately the routine is only used in a few places (cli.c, manager.c,
00849  * res_agi.c) so it is reasonably easy to check how it behaves there.
00850  *
00851  * XXX We either need to fix the code, or fix the documentation.
00852  */
00853 int ast_carefulwrite(int fd, char *s, int len, int timeoutms) 
00854 {
00855    /* Try to write string, but wait no more than ms milliseconds
00856       before timing out */
00857    int res = 0;
00858    struct pollfd fds[1];
00859    while (len) {
00860       res = write(fd, s, len);
00861       if ((res < 0) && (errno != EAGAIN)) {
00862          return -1;
00863       }
00864       if (res < 0)
00865          res = 0;
00866       len -= res;
00867       s += res;
00868       res = 0;
00869       if (len) {
00870          fds[0].fd = fd;
00871          fds[0].events = POLLOUT;
00872          /* Wait until writable again */
00873          res = poll(fds, 1, timeoutms);
00874          if (res < 1)
00875             return -1;
00876       }
00877    }
00878    return res;
00879 }
00880 
00881 char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
00882 {
00883    char *e;
00884    char *q;
00885 
00886    s = ast_strip(s);
00887    if ((q = strchr(beg_quotes, *s)) && *q != '\0') {
00888       e = s + strlen(s) - 1;
00889       if (*e == *(end_quotes + (q - beg_quotes))) {
00890          s++;
00891          *e = '\0';
00892       }
00893    }
00894 
00895    return s;
00896 }
00897 
00898 char *ast_unescape_semicolon(char *s)
00899 {
00900    char *e;
00901    char *work = s;
00902 
00903    while ((e = strchr(work, ';'))) {
00904       if ((e > work) && (*(e-1) == '\\')) {
00905          memmove(e - 1, e, strlen(e) + 1);
00906          work = e;
00907       }
00908    }
00909 
00910    return s;
00911 }
00912 
00913 int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap)
00914 {
00915    int result;
00916 
00917    if (!buffer || !*buffer || !space || !*space)
00918       return -1;
00919 
00920    result = vsnprintf(*buffer, *space, fmt, ap);
00921 
00922    if (result < 0)
00923       return -1;
00924    else if (result > *space)
00925       result = *space;
00926 
00927    *buffer += result;
00928    *space -= result;
00929    return 0;
00930 }
00931 
00932 int ast_build_string(char **buffer, size_t *space, const char *fmt, ...)
00933 {
00934    va_list ap;
00935    int result;
00936 
00937    va_start(ap, fmt);
00938    result = ast_build_string_va(buffer, space, fmt, ap);
00939    va_end(ap);
00940 
00941    return result;
00942 }
00943 
00944 int ast_true(const char *s)
00945 {
00946    if (ast_strlen_zero(s))
00947       return 0;
00948 
00949    /* Determine if this is a true value */
00950    if (!strcasecmp(s, "yes") ||
00951        !strcasecmp(s, "true") ||
00952        !strcasecmp(s, "y") ||
00953        !strcasecmp(s, "t") ||
00954        !strcasecmp(s, "1") ||
00955        !strcasecmp(s, "on"))
00956       return -1;
00957 
00958    return 0;
00959 }
00960 
00961 int ast_false(const char *s)
00962 {
00963    if (ast_strlen_zero(s))
00964       return 0;
00965 
00966    /* Determine if this is a false value */
00967    if (!strcasecmp(s, "no") ||
00968        !strcasecmp(s, "false") ||
00969        !strcasecmp(s, "n") ||
00970        !strcasecmp(s, "f") ||
00971        !strcasecmp(s, "0") ||
00972        !strcasecmp(s, "off"))
00973       return -1;
00974 
00975    return 0;
00976 }
00977 
00978 #define ONE_MILLION  1000000
00979 /*
00980  * put timeval in a valid range. usec is 0..999999
00981  * negative values are not allowed and truncated.
00982  */
00983 static struct timeval tvfix(struct timeval a)
00984 {
00985    if (a.tv_usec >= ONE_MILLION) {
00986       ast_log(LOG_WARNING, "warning too large timestamp %ld.%ld\n",
00987          a.tv_sec, (long int) a.tv_usec);
00988       a.tv_sec += a.tv_usec / ONE_MILLION;
00989       a.tv_usec %= ONE_MILLION;
00990    } else if (a.tv_usec < 0) {
00991       ast_log(LOG_WARNING, "warning negative timestamp %ld.%ld\n",
00992          a.tv_sec, (long int) a.tv_usec);
00993       a.tv_usec = 0;
00994    }
00995    return a;
00996 }
00997 
00998 struct timeval ast_tvadd(struct timeval a, struct timeval b)
00999 {
01000    /* consistency checks to guarantee usec in 0..999999 */
01001    a = tvfix(a);
01002    b = tvfix(b);
01003    a.tv_sec += b.tv_sec;
01004    a.tv_usec += b.tv_usec;
01005    if (a.tv_usec >= ONE_MILLION) {
01006       a.tv_sec++;
01007       a.tv_usec -= ONE_MILLION;
01008    }
01009    return a;
01010 }
01011 
01012 struct timeval ast_tvsub(struct timeval a, struct timeval b)
01013 {
01014    /* consistency checks to guarantee usec in 0..999999 */
01015    a = tvfix(a);
01016    b = tvfix(b);
01017    a.tv_sec -= b.tv_sec;
01018    a.tv_usec -= b.tv_usec;
01019    if (a.tv_usec < 0) {
01020       a.tv_sec-- ;
01021       a.tv_usec += ONE_MILLION;
01022    }
01023    return a;
01024 }
01025 #undef ONE_MILLION
01026 
01027 /*! \brief glibc puts a lock inside random(3), so that the results are thread-safe.
01028  * BSD libc (and others) do not. */
01029 #ifndef linux
01030 
01031 AST_MUTEX_DEFINE_STATIC(randomlock);
01032 
01033 long int ast_random(void)
01034 {
01035    long int res;
01036    ast_mutex_lock(&randomlock);
01037    res = random();
01038    ast_mutex_unlock(&randomlock);
01039    return res;
01040 }
01041 #endif
01042 
01043 char *ast_process_quotes_and_slashes(char *start, char find, char replace_with)
01044 {
01045    char *dataPut = start;
01046    int inEscape = 0;
01047    int inQuotes = 0;
01048 
01049    for (; *start; start++) {
01050       if (inEscape) {
01051          *dataPut++ = *start;       /* Always goes verbatim */
01052          inEscape = 0;
01053       } else {
01054          if (*start == '\\') {
01055             inEscape = 1;      /* Do not copy \ into the data */
01056          } else if (*start == '\'') {
01057             inQuotes = 1 - inQuotes;   /* Do not copy ' into the data */
01058          } else {
01059             /* Replace , with |, unless in quotes */
01060             *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
01061          }
01062       }
01063    }
01064    if (start != dataPut)
01065       *dataPut = 0;
01066    return dataPut;
01067 }
01068 
01069 void ast_join(char *s, size_t len, char * const w[])
01070 {
01071    int x, ofs = 0;
01072    const char *src;
01073 
01074    /* Join words into a string */
01075    if (!s)
01076       return;
01077    for (x = 0; ofs < len && w[x]; x++) {
01078       if (x > 0)
01079          s[ofs++] = ' ';
01080       for (src = w[x]; *src && ofs < len; src++)
01081          s[ofs++] = *src;
01082    }
01083    if (ofs == len)
01084       ofs--;
01085    s[ofs] = '\0';
01086 }
01087 
01088 const char __ast_string_field_empty[] = "";
01089 
01090 static int add_string_pool(struct ast_string_field_mgr *mgr, size_t size)
01091 {
01092    struct ast_string_field_pool *pool;
01093 
01094    if (!(pool = ast_calloc(1, sizeof(*pool) + size)))
01095       return -1;
01096    
01097    pool->prev = mgr->pool;
01098    mgr->pool = pool;
01099    mgr->size = size;
01100    mgr->space = size;
01101    mgr->used = 0;
01102 
01103    return 0;
01104 }
01105 
01106 int __ast_string_field_init(struct ast_string_field_mgr *mgr, size_t size,
01107              ast_string_field *fields, int num_fields)
01108 {
01109    int index;
01110 
01111    if (add_string_pool(mgr, size))
01112       return -1;
01113 
01114    for (index = 0; index < num_fields; index++)
01115       fields[index] = __ast_string_field_empty;
01116 
01117    return 0;
01118 }
01119 
01120 ast_string_field __ast_string_field_alloc_space(struct ast_string_field_mgr *mgr, size_t needed,
01121                   ast_string_field *fields, int num_fields)
01122 {
01123    char *result = NULL;
01124 
01125    if (__builtin_expect(needed > mgr->space, 0)) {
01126       size_t new_size = mgr->size * 2;
01127 
01128       while (new_size < needed)
01129          new_size *= 2;
01130 
01131       if (add_string_pool(mgr, new_size))
01132          return NULL;
01133    }
01134 
01135    result = mgr->pool->base + mgr->used;
01136    mgr->used += needed;
01137    mgr->space -= needed;
01138    return result;
01139 }
01140 
01141 void __ast_string_field_index_build_va(struct ast_string_field_mgr *mgr,
01142                 ast_string_field *fields, int num_fields,
01143                 int index, const char *format, va_list ap1, va_list ap2)
01144 {
01145    size_t needed;
01146 
01147    needed = vsnprintf(mgr->pool->base + mgr->used, mgr->space, format, ap1) + 1;
01148 
01149    va_end(ap1);
01150 
01151    if (needed > mgr->space) {
01152       size_t new_size = mgr->size * 2;
01153 
01154       while (new_size < needed)
01155          new_size *= 2;
01156 
01157       if (add_string_pool(mgr, new_size))
01158          return;
01159 
01160       vsprintf(mgr->pool->base + mgr->used, format, ap2);
01161    }
01162 
01163    fields[index] = mgr->pool->base + mgr->used;
01164    mgr->used += needed;
01165    mgr->space -= needed;
01166 }
01167 
01168 void __ast_string_field_index_build(struct ast_string_field_mgr *mgr,
01169                 ast_string_field *fields, int num_fields,
01170                 int index, const char *format, ...)
01171 {
01172    va_list ap1, ap2;
01173 
01174    va_start(ap1, format);
01175    va_start(ap2, format);     /* va_copy does not exist on FreeBSD */
01176 
01177    __ast_string_field_index_build_va(mgr, fields, num_fields, index, format, ap1, ap2);
01178 
01179    va_end(ap1);
01180    va_end(ap2);
01181 }
01182 
01183 AST_MUTEX_DEFINE_STATIC(fetchadd_m); /* used for all fetc&add ops */
01184 
01185 int ast_atomic_fetchadd_int_slow(volatile int *p, int v)
01186 {
01187         int ret;
01188         ast_mutex_lock(&fetchadd_m);
01189         ret = *p;
01190         *p += v;
01191         ast_mutex_unlock(&fetchadd_m);
01192         return ret;
01193 }
01194 
01195 /*! \brief
01196  * get values from config variables.
01197  */
01198 int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed)
01199 {
01200    long t;
01201    int scanned;
01202 
01203    if (dst == NULL)
01204       return -1;
01205 
01206    *dst = _default;
01207 
01208    if (ast_strlen_zero(src))
01209       return -1;
01210 
01211    /* only integer at the moment, but one day we could accept more formats */
01212    if (sscanf(src, "%ld%n", &t, &scanned) == 1) {
01213       *dst = t;
01214       if (consumed)
01215          *consumed = scanned;
01216       return 0;
01217    } else
01218       return -1;
01219 }
01220 
01221 int ast_dynamic_str_thread_build_va(struct ast_dynamic_str **buf, size_t max_len,
01222    struct ast_threadstorage *ts, int append, const char *fmt, va_list ap)
01223 {
01224    int res;
01225    int offset = (append && (*buf)->len) ? strlen((*buf)->str) : 0;
01226 #if defined(DEBUG_THREADLOCALS)
01227    struct ast_dynamic_str *old_buf = *buf;
01228 #endif /* defined(DEBUG_THREADLOCALS) */
01229 
01230    res = vsnprintf((*buf)->str + offset, (*buf)->len - offset, fmt, ap);
01231 
01232    /* Check to see if there was not enough space in the string buffer to prepare
01233     * the string.  Also, if a maximum length is present, make sure the current
01234     * length is less than the maximum before increasing the size. */
01235    if ((res + offset + 1) > (*buf)->len && (max_len ? ((*buf)->len < max_len) : 1)) {
01236       /* Set the new size of the string buffer to be the size needed
01237        * to hold the resulting string (res) plus one byte for the
01238        * terminating '\0'.  If this size is greater than the max, set
01239        * the new length to be the maximum allowed. */
01240       if (max_len)
01241          (*buf)->len = ((res + offset + 1) < max_len) ? (res + offset + 1) : max_len;
01242       else
01243          (*buf)->len = res + offset + 1;
01244 
01245       if (!(*buf = ast_realloc(*buf, (*buf)->len + sizeof(*(*buf)))))
01246          return AST_DYNSTR_BUILD_FAILED;
01247 
01248       if (append)
01249          (*buf)->str[offset] = '\0';
01250 
01251       if (ts) {
01252          pthread_setspecific(ts->key, *buf);
01253 #if defined(DEBUG_THREADLOCALS)
01254          __ast_threadstorage_object_replace(old_buf, *buf, (*buf)->len + sizeof(*(*buf)));
01255 #endif /* defined(DEBUG_THREADLOCALS) */
01256       }
01257 
01258       /* va_end() and va_start() must be done before calling
01259        * vsnprintf() again. */
01260       return AST_DYNSTR_BUILD_RETRY;
01261    }
01262 
01263    return res;
01264 }
01265 
01266 void ast_enable_packet_fragmentation(int sock)
01267 {
01268 #if defined(HAVE_IP_MTU_DISCOVER)
01269    int val = IP_PMTUDISC_DONT;
01270    
01271    if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
01272       ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
01273 #endif /* HAVE_IP_MTU_DISCOVER */
01274 }
01275 
01276 int ast_utils_init(void)
01277 {
01278    base64_init();
01279 #ifdef DEBUG_THREADS
01280    ast_cli_register_multiple(utils_cli, sizeof(utils_cli) / sizeof(utils_cli[0]));
01281 #endif
01282    return 0;
01283 }
01284 
01285 

Generated on Fri Aug 24 02:22:17 2007 for Asterisk - the Open Source PBX by  doxygen 1.5.1