Sat Jul 12 2014 17:18:39

Asterisk developer's documentation


utils.h
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  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  * \brief Utility functions
00021  */
00022 
00023 #ifndef _ASTERISK_UTILS_H
00024 #define _ASTERISK_UTILS_H
00025 
00026 #include "asterisk/network.h"
00027 
00028 #include <time.h> /* we want to override localtime_r */
00029 #include <unistd.h>
00030 #include <string.h>
00031 
00032 #include "asterisk/lock.h"
00033 #include "asterisk/time.h"
00034 #include "asterisk/logger.h"
00035 #include "asterisk/localtime.h"
00036 #include "asterisk/stringfields.h"
00037 
00038 /*!
00039 \note \verbatim
00040    Note:
00041    It is very important to use only unsigned variables to hold
00042    bit flags, as otherwise you can fall prey to the compiler's
00043    sign-extension antics if you try to use the top two bits in
00044    your variable.
00045 
00046    The flag macros below use a set of compiler tricks to verify
00047    that the caller is using an "unsigned int" variable to hold
00048    the flags, and nothing else. If the caller uses any other
00049    type of variable, a warning message similar to this:
00050 
00051    warning: comparison of distinct pointer types lacks cast
00052    will be generated.
00053 
00054    The "dummy" variable below is used to make these comparisons.
00055 
00056    Also note that at -O2 or above, this type-safety checking
00057    does _not_ produce any additional object code at all.
00058  \endverbatim
00059 */
00060 
00061 extern unsigned int __unsigned_int_flags_dummy;
00062 
00063 #define ast_test_flag(p,flag)       ({ \
00064                typeof ((p)->flags) __p = (p)->flags; \
00065                typeof (__unsigned_int_flags_dummy) __x = 0; \
00066                (void) (&__p == &__x); \
00067                ((p)->flags & (flag)); \
00068                })
00069 
00070 #define ast_set_flag(p,flag)     do { \
00071                typeof ((p)->flags) __p = (p)->flags; \
00072                typeof (__unsigned_int_flags_dummy) __x = 0; \
00073                (void) (&__p == &__x); \
00074                ((p)->flags |= (flag)); \
00075                } while(0)
00076 
00077 #define ast_clear_flag(p,flag)      do { \
00078                typeof ((p)->flags) __p = (p)->flags; \
00079                typeof (__unsigned_int_flags_dummy) __x = 0; \
00080                (void) (&__p == &__x); \
00081                ((p)->flags &= ~(flag)); \
00082                } while(0)
00083 
00084 #define ast_copy_flags(dest,src,flagz) do { \
00085                typeof ((dest)->flags) __d = (dest)->flags; \
00086                typeof ((src)->flags) __s = (src)->flags; \
00087                typeof (__unsigned_int_flags_dummy) __x = 0; \
00088                (void) (&__d == &__x); \
00089                (void) (&__s == &__x); \
00090                (dest)->flags &= ~(flagz); \
00091                (dest)->flags |= ((src)->flags & (flagz)); \
00092                } while (0)
00093 
00094 #define ast_set2_flag(p,value,flag) do { \
00095                typeof ((p)->flags) __p = (p)->flags; \
00096                typeof (__unsigned_int_flags_dummy) __x = 0; \
00097                (void) (&__p == &__x); \
00098                if (value) \
00099                   (p)->flags |= (flag); \
00100                else \
00101                   (p)->flags &= ~(flag); \
00102                } while (0)
00103 
00104 #define ast_set_flags_to(p,flag,value) do { \
00105                typeof ((p)->flags) __p = (p)->flags; \
00106                typeof (__unsigned_int_flags_dummy) __x = 0; \
00107                (void) (&__p == &__x); \
00108                (p)->flags &= ~(flag); \
00109                (p)->flags |= (value); \
00110                } while (0)
00111 
00112 
00113 /* The following 64-bit flag code can most likely be erased after app_dial
00114    is reorganized to either reduce the large number of options, or handle
00115    them in some other way. At the time of this writing, app_dial would be
00116    the only user of 64-bit option flags */
00117 
00118 extern uint64_t __unsigned_int_flags_dummy64;
00119 
00120 #define ast_test_flag64(p,flag)     ({ \
00121                typeof ((p)->flags) __p = (p)->flags; \
00122                typeof (__unsigned_int_flags_dummy64) __x = 0; \
00123                (void) (&__p == &__x); \
00124                ((p)->flags & (flag)); \
00125                })
00126 
00127 #define ast_set_flag64(p,flag)      do { \
00128                typeof ((p)->flags) __p = (p)->flags; \
00129                typeof (__unsigned_int_flags_dummy64) __x = 0; \
00130                (void) (&__p == &__x); \
00131                ((p)->flags |= (flag)); \
00132                } while(0)
00133 
00134 #define ast_clear_flag64(p,flag)       do { \
00135                typeof ((p)->flags) __p = (p)->flags; \
00136                typeof (__unsigned_int_flags_dummy64) __x = 0; \
00137                (void) (&__p == &__x); \
00138                ((p)->flags &= ~(flag)); \
00139                } while(0)
00140 
00141 #define ast_copy_flags64(dest,src,flagz)  do { \
00142                typeof ((dest)->flags) __d = (dest)->flags; \
00143                typeof ((src)->flags) __s = (src)->flags; \
00144                typeof (__unsigned_int_flags_dummy64) __x = 0; \
00145                (void) (&__d == &__x); \
00146                (void) (&__s == &__x); \
00147                (dest)->flags &= ~(flagz); \
00148                (dest)->flags |= ((src)->flags & (flagz)); \
00149                } while (0)
00150 
00151 #define ast_set2_flag64(p,value,flag)  do { \
00152                typeof ((p)->flags) __p = (p)->flags; \
00153                typeof (__unsigned_int_flags_dummy64) __x = 0; \
00154                (void) (&__p == &__x); \
00155                if (value) \
00156                   (p)->flags |= (flag); \
00157                else \
00158                   (p)->flags &= ~(flag); \
00159                } while (0)
00160 
00161 #define ast_set_flags_to64(p,flag,value)  do { \
00162                typeof ((p)->flags) __p = (p)->flags; \
00163                typeof (__unsigned_int_flags_dummy64) __x = 0; \
00164                (void) (&__p == &__x); \
00165                (p)->flags &= ~(flag); \
00166                (p)->flags |= (value); \
00167                } while (0)
00168 
00169 
00170 /* Non-type checking variations for non-unsigned int flags.  You
00171    should only use non-unsigned int flags where required by
00172    protocol etc and if you know what you're doing :)  */
00173 #define ast_test_flag_nonstd(p,flag) \
00174                ((p)->flags & (flag))
00175 
00176 #define ast_set_flag_nonstd(p,flag)       do { \
00177                ((p)->flags |= (flag)); \
00178                } while(0)
00179 
00180 #define ast_clear_flag_nonstd(p,flag)     do { \
00181                ((p)->flags &= ~(flag)); \
00182                } while(0)
00183 
00184 #define ast_copy_flags_nonstd(dest,src,flagz)   do { \
00185                (dest)->flags &= ~(flagz); \
00186                (dest)->flags |= ((src)->flags & (flagz)); \
00187                } while (0)
00188 
00189 #define ast_set2_flag_nonstd(p,value,flag)   do { \
00190                if (value) \
00191                   (p)->flags |= (flag); \
00192                else \
00193                   (p)->flags &= ~(flag); \
00194                } while (0)
00195 
00196 #define AST_FLAGS_ALL UINT_MAX
00197 
00198 /*! \brief Structure used to handle boolean flags */
00199 struct ast_flags {
00200    unsigned int flags;
00201 };
00202 
00203 /*! \brief Structure used to handle a large number of boolean flags == used only in app_dial? */
00204 struct ast_flags64 {
00205    uint64_t flags;
00206 };
00207 
00208 struct ast_hostent {
00209    struct hostent hp;
00210    char buf[1024];
00211 };
00212 
00213 /*! \brief Thread-safe gethostbyname function to use in Asterisk */
00214 struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp);
00215 
00216 /*! \brief Produces MD5 hash based on input string */
00217 void ast_md5_hash(char *output, const char *input);
00218 /*! \brief Produces SHA1 hash based on input string */
00219 void ast_sha1_hash(char *output, const char *input);
00220 /*! \brief Produces SHA1 hash based on input string, stored in uint8_t array */
00221 void ast_sha1_hash_uint(uint8_t *digest, const char *input);
00222 
00223 int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks);
00224 
00225 #undef MIN
00226 #define MIN(a, b) ({ typeof(a) __a = (a); typeof(b) __b = (b); ((__a > __b) ? __b : __a);})
00227 #undef MAX
00228 #define MAX(a, b) ({ typeof(a) __a = (a); typeof(b) __b = (b); ((__a < __b) ? __b : __a);})
00229 
00230 #define SWAP(a,b) do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)
00231 
00232 /*!
00233  * \brief Encode data in base64
00234  * \param dst the destination buffer
00235  * \param src the source data to be encoded
00236  * \param srclen the number of bytes present in the source buffer
00237  * \param max the maximum number of bytes to write into the destination
00238  *        buffer, *including* the terminating NULL character.
00239  */
00240 int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max);
00241 
00242 /*!
00243  * \brief Decode data from base64
00244  * \param dst the destination buffer
00245  * \param src the source buffer
00246  * \param max The maximum number of bytes to write into the destination
00247  *            buffer.  Note that this function will not ensure that the
00248  *            destination buffer is NULL terminated.  So, in general,
00249  *            this parameter should be sizeof(dst) - 1.
00250  */
00251 int ast_base64decode(unsigned char *dst, const char *src, int max);
00252 
00253 #define AST_URI_ALPHANUM     (1 << 0)
00254 #define AST_URI_MARK         (1 << 1)
00255 #define AST_URI_UNRESERVED   (AST_URI_ALPHANUM | AST_URI_MARK)
00256 #define AST_URI_LEGACY_SPACE (1 << 2)
00257 
00258 #define AST_URI_SIP_USER_UNRESERVED (1 << 20)
00259 
00260 extern const struct ast_flags ast_uri_http;
00261 extern const struct ast_flags ast_uri_http_legacy;
00262 extern const struct ast_flags ast_uri_sip_user;
00263 
00264 /*!
00265  * \brief Turn text string to URI-encoded %XX version
00266  *
00267  * This function encodes characters according to the rules presented in RFC
00268  * 2396 and/or RFC 3261 section 19.1.2 and section 25.1.
00269  *
00270  * Outbuf needs to have more memory allocated than the instring to have room
00271  * for the expansion. Every byte that is converted is replaced by three ASCII
00272  * characters.
00273  *
00274  * \param string string to be converted
00275  * \param outbuf resulting encoded string
00276  * \param buflen size of output buffer
00277  * \param spec flags describing how the encoding should be performed
00278  * \return a pointer to the uri encoded string
00279  */
00280 char *ast_uri_encode(const char *string, char *outbuf, int buflen, struct ast_flags spec);
00281 
00282 /*!
00283  * \brief Decode URI, URN, URL (overwrite string)
00284  *
00285  * \note The ast_uri_http_legacy decode spec flag will cause this function to
00286  * decode '+' as ' '.
00287  *
00288  * \param s string to be decoded
00289  * \param spec flags describing how the decoding should be performed
00290  */
00291 void ast_uri_decode(char *s, struct ast_flags spec);
00292 
00293 /*! ast_xml_escape
00294    \brief Escape reserved characters for use in XML.
00295 
00296    If \a outbuf is too short, the output string will be truncated.
00297    Regardless, the output will always be null terminated.
00298 
00299    \param string String to be converted
00300    \param outbuf Resulting encoded string
00301    \param buflen Size of output buffer
00302    \return 0 for success
00303    \return -1 if buflen is too short.
00304  */
00305 int ast_xml_escape(const char *string, char *outbuf, size_t buflen);
00306 
00307 /*!
00308  * \brief Escape characters found in a quoted string.
00309  *
00310  * \note This function escapes quoted characters based on the 'qdtext' set of
00311  * allowed characters from RFC 3261 section 25.1.
00312  *
00313  * \param string string to be escaped
00314  * \param outbuf resulting escaped string
00315  * \param buflen size of output buffer
00316  * \return a pointer to the escaped string
00317  */
00318 char *ast_escape_quoted(const char *string, char *outbuf, int buflen);
00319 
00320 static force_inline void ast_slinear_saturated_add(short *input, short *value)
00321 {
00322    int res;
00323 
00324    res = (int) *input + *value;
00325    if (res > 32767)
00326       *input = 32767;
00327    else if (res < -32768)
00328       *input = -32768;
00329    else
00330       *input = (short) res;
00331 }
00332 
00333 static force_inline void ast_slinear_saturated_subtract(short *input, short *value)
00334 {
00335    int res;
00336 
00337    res = (int) *input - *value;
00338    if (res > 32767)
00339       *input = 32767;
00340    else if (res < -32768)
00341       *input = -32768;
00342    else
00343       *input = (short) res;
00344 }
00345 
00346 static force_inline void ast_slinear_saturated_multiply(short *input, short *value)
00347 {
00348    int res;
00349 
00350    res = (int) *input * *value;
00351    if (res > 32767)
00352       *input = 32767;
00353    else if (res < -32768)
00354       *input = -32768;
00355    else
00356       *input = (short) res;
00357 }
00358 
00359 static force_inline void ast_slinear_saturated_divide(short *input, short *value)
00360 {
00361    *input /= *value;
00362 }
00363 
00364 #ifdef localtime_r
00365 #undef localtime_r
00366 #endif
00367 #define localtime_r __dont_use_localtime_r_use_ast_localtime_instead__
00368 
00369 int ast_utils_init(void);
00370 int ast_wait_for_input(int fd, int ms);
00371 int ast_wait_for_output(int fd, int ms);
00372 
00373 /*!
00374  * \brief Try to write string, but wait no more than ms milliseconds
00375  * before timing out.
00376  *
00377  * \note If you are calling ast_carefulwrite, it is assumed that you are calling
00378  * it on a file descriptor that _DOES_ have NONBLOCK set.  This way,
00379  * there is only one system call made to do a write, unless we actually
00380  * have a need to wait.  This way, we get better performance.
00381  */
00382 int ast_carefulwrite(int fd, char *s, int len, int timeoutms);
00383 
00384 /*!
00385  * \brief Write data to a file stream with a timeout
00386  *
00387  * \param f the file stream to write to
00388  * \param fd the file description to poll on to know when the file stream can
00389  *        be written to without blocking.
00390  * \param s the buffer to write from
00391  * \param len the number of bytes to write
00392  * \param timeoutms The maximum amount of time to block in this function trying
00393  *        to write, specified in milliseconds.
00394  *
00395  * \note This function assumes that the associated file stream has been set up
00396  *       as non-blocking.
00397  *
00398  * \retval 0 success
00399  * \retval -1 error
00400  */
00401 int ast_careful_fwrite(FILE *f, int fd, const char *s, size_t len, int timeoutms);
00402 
00403 /*
00404  * Thread management support (should be moved to lock.h or a different header)
00405  */
00406 
00407 #define AST_STACKSIZE (((sizeof(void *) * 8 * 8) - 16) * 1024)
00408 
00409 #if defined(LOW_MEMORY)
00410 #define AST_BACKGROUND_STACKSIZE (((sizeof(void *) * 8 * 2) - 16) * 1024)
00411 #else
00412 #define AST_BACKGROUND_STACKSIZE AST_STACKSIZE
00413 #endif
00414 
00415 void ast_register_thread(char *name);
00416 void ast_unregister_thread(void *id);
00417 
00418 int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
00419               void *data, size_t stacksize, const char *file, const char *caller,
00420               int line, const char *start_fn);
00421 
00422 int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void*(*start_routine)(void *),
00423              void *data, size_t stacksize, const char *file, const char *caller,
00424              int line, const char *start_fn);
00425 
00426 #define ast_pthread_create(a, b, c, d)             \
00427    ast_pthread_create_stack(a, b, c, d,         \
00428       0, __FILE__, __FUNCTION__, __LINE__, #c)
00429 
00430 #define ast_pthread_create_detached(a, b, c, d)       \
00431    ast_pthread_create_detached_stack(a, b, c, d,      \
00432       0, __FILE__, __FUNCTION__, __LINE__, #c)
00433 
00434 #define ast_pthread_create_background(a, b, c, d)     \
00435    ast_pthread_create_stack(a, b, c, d,         \
00436       AST_BACKGROUND_STACKSIZE,        \
00437       __FILE__, __FUNCTION__, __LINE__, #c)
00438 
00439 #define ast_pthread_create_detached_background(a, b, c, d)  \
00440    ast_pthread_create_detached_stack(a, b, c, d,      \
00441       AST_BACKGROUND_STACKSIZE,        \
00442       __FILE__, __FUNCTION__, __LINE__, #c)
00443 
00444 /* End of thread management support */
00445 
00446 /*!
00447  * \brief Replace '^' in a string with ','
00448  * \param s String within which to replace characters
00449  */
00450 void ast_replace_subargument_delimiter(char *s);
00451 
00452 /*!
00453  * \brief Process a string to find and replace characters
00454  * \param start The string to analyze
00455  * \param find The character to find
00456  * \param replace_with The character that will replace the one we are looking for
00457  */
00458 char *ast_process_quotes_and_slashes(char *start, char find, char replace_with);
00459 
00460 long int ast_random(void);
00461 
00462 
00463 #ifndef __AST_DEBUG_MALLOC
00464 #define ast_std_malloc malloc
00465 #define ast_std_calloc calloc
00466 #define ast_std_realloc realloc
00467 #define ast_std_free free
00468 
00469 /*!
00470  * \brief free() wrapper
00471  *
00472  * ast_free_ptr should be used when a function pointer for free() needs to be passed
00473  * as the argument to a function. Otherwise, astmm will cause seg faults.
00474  */
00475 #define ast_free free
00476 #define ast_free_ptr ast_free
00477 
00478 #define MALLOC_FAILURE_MSG \
00479    ast_log(LOG_ERROR, "Memory Allocation Failure in function %s at line %d of %s\n", func, lineno, file);
00480 /*!
00481  * \brief A wrapper for malloc()
00482  *
00483  * ast_malloc() is a wrapper for malloc() that will generate an Asterisk log
00484  * message in the case that the allocation fails.
00485  *
00486  * The argument and return value are the same as malloc()
00487  */
00488 #define ast_malloc(len) \
00489    _ast_malloc((len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
00490 
00491 AST_INLINE_API(
00492 void * attribute_malloc _ast_malloc(size_t len, const char *file, int lineno, const char *func),
00493 {
00494    void *p;
00495 
00496    if (!(p = malloc(len)))
00497       MALLOC_FAILURE_MSG;
00498 
00499    return p;
00500 }
00501 )
00502 
00503 /*!
00504  * \brief A wrapper for calloc()
00505  *
00506  * ast_calloc() is a wrapper for calloc() that will generate an Asterisk log
00507  * message in the case that the allocation fails.
00508  *
00509  * The arguments and return value are the same as calloc()
00510  */
00511 #define ast_calloc(num, len) \
00512    _ast_calloc((num), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
00513 
00514 AST_INLINE_API(
00515 void * attribute_malloc _ast_calloc(size_t num, size_t len, const char *file, int lineno, const char *func),
00516 {
00517    void *p;
00518 
00519    if (!(p = calloc(num, len)))
00520       MALLOC_FAILURE_MSG;
00521 
00522    return p;
00523 }
00524 )
00525 
00526 /*!
00527  * \brief A wrapper for calloc() for use in cache pools
00528  *
00529  * ast_calloc_cache() is a wrapper for calloc() that will generate an Asterisk log
00530  * message in the case that the allocation fails. When memory debugging is in use,
00531  * the memory allocated by this function will be marked as 'cache' so it can be
00532  * distinguished from normal memory allocations.
00533  *
00534  * The arguments and return value are the same as calloc()
00535  */
00536 #define ast_calloc_cache(num, len) \
00537    _ast_calloc((num), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
00538 
00539 /*!
00540  * \brief A wrapper for realloc()
00541  *
00542  * ast_realloc() is a wrapper for realloc() that will generate an Asterisk log
00543  * message in the case that the allocation fails.
00544  *
00545  * The arguments and return value are the same as realloc()
00546  */
00547 #define ast_realloc(p, len) \
00548    _ast_realloc((p), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
00549 
00550 AST_INLINE_API(
00551 void * attribute_malloc _ast_realloc(void *p, size_t len, const char *file, int lineno, const char *func),
00552 {
00553    void *newp;
00554 
00555    if (!(newp = realloc(p, len)))
00556       MALLOC_FAILURE_MSG;
00557 
00558    return newp;
00559 }
00560 )
00561 
00562 /*!
00563  * \brief A wrapper for strdup()
00564  *
00565  * ast_strdup() is a wrapper for strdup() that will generate an Asterisk log
00566  * message in the case that the allocation fails.
00567  *
00568  * ast_strdup(), unlike strdup(), can safely accept a NULL argument. If a NULL
00569  * argument is provided, ast_strdup will return NULL without generating any
00570  * kind of error log message.
00571  *
00572  * The argument and return value are the same as strdup()
00573  */
00574 #define ast_strdup(str) \
00575    _ast_strdup((str), __FILE__, __LINE__, __PRETTY_FUNCTION__)
00576 
00577 AST_INLINE_API(
00578 char * attribute_malloc _ast_strdup(const char *str, const char *file, int lineno, const char *func),
00579 {
00580    char *newstr = NULL;
00581 
00582    if (str) {
00583       if (!(newstr = strdup(str)))
00584          MALLOC_FAILURE_MSG;
00585    }
00586 
00587    return newstr;
00588 }
00589 )
00590 
00591 /*!
00592  * \brief A wrapper for strndup()
00593  *
00594  * ast_strndup() is a wrapper for strndup() that will generate an Asterisk log
00595  * message in the case that the allocation fails.
00596  *
00597  * ast_strndup(), unlike strndup(), can safely accept a NULL argument for the
00598  * string to duplicate. If a NULL argument is provided, ast_strdup will return
00599  * NULL without generating any kind of error log message.
00600  *
00601  * The arguments and return value are the same as strndup()
00602  */
00603 #define ast_strndup(str, len) \
00604    _ast_strndup((str), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
00605 
00606 AST_INLINE_API(
00607 char * attribute_malloc _ast_strndup(const char *str, size_t len, const char *file, int lineno, const char *func),
00608 {
00609    char *newstr = NULL;
00610 
00611    if (str) {
00612       if (!(newstr = strndup(str, len)))
00613          MALLOC_FAILURE_MSG;
00614    }
00615 
00616    return newstr;
00617 }
00618 )
00619 
00620 /*!
00621  * \brief A wrapper for asprintf()
00622  *
00623  * ast_asprintf() is a wrapper for asprintf() that will generate an Asterisk log
00624  * message in the case that the allocation fails.
00625  *
00626  * The arguments and return value are the same as asprintf()
00627  */
00628 #define ast_asprintf(ret, fmt, ...) \
00629    _ast_asprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, fmt, __VA_ARGS__)
00630 
00631 int __attribute__((format(printf, 5, 6)))
00632    _ast_asprintf(char **ret, const char *file, int lineno, const char *func, const char *fmt, ...);
00633 
00634 /*!
00635  * \brief A wrapper for vasprintf()
00636  *
00637  * ast_vasprintf() is a wrapper for vasprintf() that will generate an Asterisk log
00638  * message in the case that the allocation fails.
00639  *
00640  * The arguments and return value are the same as vasprintf()
00641  */
00642 #define ast_vasprintf(ret, fmt, ap) \
00643    _ast_vasprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, (fmt), (ap))
00644 
00645 AST_INLINE_API(
00646 __attribute__((format(printf, 5, 0)))
00647 int _ast_vasprintf(char **ret, const char *file, int lineno, const char *func, const char *fmt, va_list ap),
00648 {
00649    int res;
00650 
00651    if ((res = vasprintf(ret, fmt, ap)) == -1)
00652       MALLOC_FAILURE_MSG;
00653 
00654    return res;
00655 }
00656 )
00657 
00658 #endif /* AST_DEBUG_MALLOC */
00659 
00660 /*!
00661   \brief call __builtin_alloca to ensure we get gcc builtin semantics
00662   \param size The size of the buffer we want allocated
00663 
00664   This macro will attempt to allocate memory from the stack.  If it fails
00665   you won't get a NULL returned, but a SEGFAULT if you're lucky.
00666 */
00667 #define ast_alloca(size) __builtin_alloca(size)
00668 
00669 #if !defined(ast_strdupa) && defined(__GNUC__)
00670 /*!
00671  * \brief duplicate a string in memory from the stack
00672  * \param s The string to duplicate
00673  *
00674  * This macro will duplicate the given string.  It returns a pointer to the stack
00675  * allocatted memory for the new string.
00676  */
00677 #define ast_strdupa(s)                                                    \
00678    (__extension__                                                    \
00679    ({                                                                \
00680       const char *__old = (s);                                  \
00681       size_t __len = strlen(__old) + 1;                         \
00682       char *__new = __builtin_alloca(__len);                    \
00683       memcpy (__new, __old, __len);                             \
00684       __new;                                                    \
00685    }))
00686 #endif
00687 
00688 /*!
00689  * \brief Disable PMTU discovery on a socket
00690  * \param sock The socket to manipulate
00691  * \return Nothing
00692  *
00693  * On Linux, UDP sockets default to sending packets with the Dont Fragment (DF)
00694  * bit set. This is supposedly done to allow the application to do PMTU
00695  * discovery, but Asterisk does not do this.
00696  *
00697  * Because of this, UDP packets sent by Asterisk that are larger than the MTU
00698  * of any hop in the path will be lost. This function can be called on a socket
00699  * to ensure that the DF bit will not be set.
00700  */
00701 void ast_enable_packet_fragmentation(int sock);
00702 
00703 /*!
00704  * \brief Recursively create directory path
00705  * \param path The directory path to create
00706  * \param mode The permissions with which to try to create the directory
00707  * \return 0 on success or an error code otherwise
00708  *
00709  * Creates a directory path, creating parent directories as needed.
00710  */
00711 int ast_mkdir(const char *path, int mode);
00712 
00713 #define ARRAY_LEN(a) (size_t) (sizeof(a) / sizeof(0[a]))
00714 
00715 
00716 /* Definition for Digest authorization */
00717 struct ast_http_digest {
00718    AST_DECLARE_STRING_FIELDS(
00719       AST_STRING_FIELD(username);
00720       AST_STRING_FIELD(nonce);
00721       AST_STRING_FIELD(uri);
00722       AST_STRING_FIELD(realm);
00723       AST_STRING_FIELD(domain);
00724       AST_STRING_FIELD(response);
00725       AST_STRING_FIELD(cnonce);
00726       AST_STRING_FIELD(opaque);
00727       AST_STRING_FIELD(nc);
00728    );
00729    int qop;    /* Flag set to 1, if we send/recv qop="quth" */
00730 };
00731 
00732 /*!
00733  * \brief Parse digest authorization header.
00734  * \return Returns -1 if we have no auth or something wrong with digest.
00735  * \note This function may be used for Digest request and responce header.
00736  * request arg is set to nonzero, if we parse Digest Request.
00737  * pedantic arg can be set to nonzero if we need to do addition Digest check.
00738  */
00739 int ast_parse_digest(const char *digest, struct ast_http_digest *d, int request, int pedantic);
00740 
00741 
00742 #ifdef AST_DEVMODE
00743 void __ast_assert_failed(int condition, const char *condition_str, const char *file, int line, const char *function);
00744 #define ast_assert(a) _ast_assert(a, # a, __FILE__, __LINE__, __PRETTY_FUNCTION__)
00745 static void force_inline _ast_assert(int condition, const char *condition_str, const char *file, int line, const char *function)
00746 {
00747    if (__builtin_expect(!condition, 1)) {
00748       __ast_assert_failed(condition, condition_str, file, line, function);
00749    }
00750 }
00751 #else
00752 #define ast_assert(a)
00753 #endif
00754 
00755 /*!
00756  * \brief Force a crash if DO_CRASH is defined.
00757  *
00758  * \note If DO_CRASH is not defined then the function returns.
00759  *
00760  * \return Nothing
00761  */
00762 void ast_do_crash(void);
00763 
00764 #include "asterisk/strings.h"
00765 
00766 /*!
00767  * \brief Return the number of bytes used in the alignment of type.
00768  * \param type
00769  * \return The number of bytes required for alignment.
00770  *
00771  * This is really just __alignof__(), but tucked away in this header so we
00772  * don't have to look at the nasty underscores in the source.
00773  */
00774 #define ast_alignof(type) __alignof__(type)
00775 
00776 /*!
00777  * \brief Increase offset so it is a multiple of the required alignment of type.
00778  * \param offset The value that should be increased.
00779  * \param type The data type that offset should be aligned to.
00780  * \return The smallest multiple of alignof(type) larger than or equal to offset.
00781  * \see ast_make_room_for()
00782  *
00783  * Many systems prefer integers to be stored on aligned on memory locations.
00784  * This macro will increase an offset so a value of the supplied type can be
00785  * safely be stored on such a memory location.
00786  *
00787  * Examples:
00788  * ast_align_for(0x17, int64_t) ==> 0x18
00789  * ast_align_for(0x18, int64_t) ==> 0x18
00790  * ast_align_for(0x19, int64_t) ==> 0x20
00791  *
00792  * Don't mind the ugliness, the compiler will optimize it.
00793  */
00794 #define ast_align_for(offset, type) (((offset + __alignof__(type) - 1) / __alignof__(type)) * __alignof__(type))
00795 
00796 /*!
00797  * \brief Increase offset by the required alignment of type and make sure it is
00798  *        a multiple of said alignment.
00799  * \param offset The value that should be increased.
00800  * \param type The data type that room should be reserved for.
00801  * \return The smallest multiple of alignof(type) larger than or equal to offset
00802  *         plus alignof(type).
00803  * \see ast_align_for()
00804  *
00805  * A use case for this is when prepending length fields of type int to a buffer.
00806  * If you keep the offset a multiple of the alignment of the integer type,
00807  * a next block of length+buffer will have the length field automatically
00808  * aligned.
00809  *
00810  * Examples:
00811  * ast_make_room_for(0x17, int64_t) ==> 0x20
00812  * ast_make_room_for(0x18, int64_t) ==> 0x20
00813  * ast_make_room_for(0x19, int64_t) ==> 0x28
00814  *
00815  * Don't mind the ugliness, the compiler will optimize it.
00816  */
00817 #define ast_make_room_for(offset, type) (((offset + (2 * __alignof__(type) - 1)) / __alignof__(type)) * __alignof__(type))
00818 
00819 /*!
00820  * \brief An Entity ID is essentially a MAC address, brief and unique
00821  */
00822 struct ast_eid {
00823    unsigned char eid[6];
00824 } __attribute__((__packed__));
00825 
00826 /*!
00827  * \brief Global EID
00828  *
00829  * This is set in asterisk.conf, or determined automatically by taking the mac
00830  * address of an Ethernet interface on the system.
00831  */
00832 extern struct ast_eid ast_eid_default;
00833 
00834 /*!
00835  * \brief Fill in an ast_eid with the default eid of this machine
00836  * \since 1.6.1
00837  */
00838 void ast_set_default_eid(struct ast_eid *eid);
00839 
00840 /*!
00841  * \brief Convert an EID to a string
00842  * \since 1.6.1
00843  */
00844 char *ast_eid_to_str(char *s, int maxlen, struct ast_eid *eid);
00845 
00846 /*!
00847  * \brief Convert a string into an EID
00848  *
00849  * This function expects an EID in the format:
00850  *    00:11:22:33:44:55
00851  *
00852  * \return 0 success, non-zero failure
00853  * \since 1.6.1
00854  */
00855 int ast_str_to_eid(struct ast_eid *eid, const char *s);
00856 
00857 /*!
00858  * \brief Compare two EIDs
00859  *
00860  * \return 0 if the two are the same, non-zero otherwise
00861  * \since 1.6.1
00862  */
00863 int ast_eid_cmp(const struct ast_eid *eid1, const struct ast_eid *eid2);
00864 
00865 /*!
00866  * \brief Get current thread ID
00867  * \param None
00868  * \return the ID if platform is supported, else -1
00869  */
00870 int ast_get_tid(void);
00871 
00872 /*!
00873  * \brief Resolve a binary to a full pathname
00874  * \param binary Name of the executable to resolve
00875  * \param fullpath Buffer to hold the complete pathname
00876  * \param fullpath_size Size of \a fullpath
00877  * \retval NULL \a binary was not found or the environment variable PATH is not set
00878  * \return \a fullpath
00879  */
00880 char *ast_utils_which(const char *binary, char *fullpath, size_t fullpath_size);
00881 
00882 /*!
00883  * \brief Declare a variable that will call a destructor function when it goes out of scope.
00884  *
00885  * Resource Allocation Is Initialization (RAII) variable declaration.
00886  *
00887  * \since 11.0
00888  * \param vartype The type of the variable
00889  * \param varname The name of the variable
00890  * \param initval The initial value of the variable
00891  * \param dtor The destructor function of type' void func(vartype *)'
00892  *
00893  * \code
00894  * void mything_cleanup(struct mything *t)
00895  * {
00896  *     if (t) {
00897  *         ast_free(t->stuff);
00898  *     }
00899  * }
00900  *
00901  * void do_stuff(const char *name)
00902  * {
00903  *     RAII_VAR(struct mything *, thing, mything_alloc(name), mything_cleanup);
00904  *     ...
00905  * }
00906  *
00907  * \note This macro is especially useful for working with ao2 objects. A common idiom
00908  * would be a function that needed to look up an ao2 object and might have several error
00909  * conditions after the allocation that would normally need to unref the ao2 object.
00910  * With RAII_VAR, it is possible to just return and leave the cleanup to the destructor
00911  * function. For example:
00912  * \code
00913  * void do_stuff(const char *name)
00914  * {
00915  *     RAII_VAR(struct mything *, thing, find_mything(name), ao2_cleanup);
00916  *     if (!thing) {
00917  *         return;
00918  *     }
00919  *     if (error) {
00920  *         return;
00921  *     }
00922  *     do_stuff_with_thing(thing);
00923  * }
00924  * \encode
00925  */
00926 #define RAII_VAR(vartype, varname, initval, dtor) \
00927     /* Prototype needed due to http://gcc.gnu.org/bugzilla/show_bug.cgi?id=36774 */ \
00928     auto void _dtor_ ## varname (vartype * v); \
00929     void _dtor_ ## varname (vartype * v) { dtor(*v); } \
00930     vartype varname __attribute__((cleanup(_dtor_ ## varname))) = (initval)
00931 
00932 #endif /* _ASTERISK_UTILS_H */