Mon Apr 28 2014 10:05:48

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 */
00200 struct ast_flags {
00201    unsigned int flags;
00202 };
00203 
00204 /*! \brief Structure used to handle a large number of boolean flags == used only in app_dial?
00205 */
00206 struct ast_flags64 {
00207    uint64_t flags;
00208 };
00209 
00210 struct ast_hostent {
00211    struct hostent hp;
00212    char buf[1024];
00213 };
00214 
00215 /*! \brief Thread-safe gethostbyname function to use in Asterisk */
00216 struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp);
00217 
00218 /*!  \brief Produces MD5 hash based on input string */
00219 void ast_md5_hash(char *output, const char *input);
00220 /*! \brief Produces SHA1 hash based on input string */
00221 void ast_sha1_hash(char *output, 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 /*!
00231  * \brief Encode data in base64
00232  * \param dst the destination buffer
00233  * \param src the source data to be encoded
00234  * \param srclen the number of bytes present in the source buffer
00235  * \param max the maximum number of bytes to write into the destination
00236  *        buffer, *including* the terminating NULL character.
00237  */
00238 int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max);
00239 
00240 /*!
00241  * \brief Decode data from base64
00242  * \param dst the destination buffer
00243  * \param src the source buffer
00244  * \param max The maximum number of bytes to write into the destination
00245  *            buffer.  Note that this function will not ensure that the
00246  *            destination buffer is NULL terminated.  So, in general,
00247  *            this parameter should be sizeof(dst) - 1.
00248  */
00249 int ast_base64decode(unsigned char *dst, const char *src, int max);
00250 
00251 /*! \brief Turn text string to URI-encoded %XX version
00252  *
00253  * \note
00254  *  At this point, this function is encoding agnostic; it does not
00255  *  check whether it is fed legal UTF-8. We escape control
00256  *  characters (\x00-\x1F\x7F), '%', and all characters above 0x7F.
00257  *  If do_special_char == 1 we will convert all characters except alnum
00258  *  and the mark set.
00259  *  Outbuf needs to have more memory allocated than the instring
00260  *  to have room for the expansion. Every char that is converted
00261  *  is replaced by three ASCII characters.
00262  *
00263  *  \param string String to be converted
00264  *  \param outbuf Resulting encoded string
00265  *  \param buflen Size of output buffer
00266  *  \param do_special_char Convert all non alphanum characters execept
00267  *         those in the mark set as defined by rfc 3261 section 25.1
00268  */
00269 char *ast_uri_encode(const char *string, char *outbuf, int buflen, int do_special_char);
00270 
00271 /*!   \brief Decode URI, URN, URL (overwrite string)
00272    \param s String to be decoded
00273  */
00274 void ast_uri_decode(char *s);
00275 
00276 /*! ast_xml_escape
00277    \brief Escape reserved characters for use in XML.
00278 
00279    If \a outbuf is too short, the output string will be truncated.
00280    Regardless, the output will always be null terminated.
00281 
00282    \param string String to be converted
00283    \param outbuf Resulting encoded string
00284    \param buflen Size of output buffer
00285    \return 0 for success
00286    \return -1 if buflen is too short.
00287  */
00288 int ast_xml_escape(const char *string, char *outbuf, size_t buflen);
00289 
00290 /*!
00291  * \brief Escape characters found in a quoted string.
00292  *
00293  * \note This function escapes quoted characters based on the 'qdtext' set of
00294  * allowed characters from RFC 3261 section 25.1.
00295  *
00296  * \param string string to be escaped
00297  * \param outbuf resulting escaped string
00298  * \param buflen size of output buffer
00299  * \return a pointer to the escaped string
00300  */
00301 char *ast_escape_quoted(const char *string, char *outbuf, int buflen);
00302 
00303 static force_inline void ast_slinear_saturated_add(short *input, short *value)
00304 {
00305    int res;
00306 
00307    res = (int) *input + *value;
00308    if (res > 32767)
00309       *input = 32767;
00310    else if (res < -32768)
00311       *input = -32768;
00312    else
00313       *input = (short) res;
00314 }
00315 
00316 static force_inline void ast_slinear_saturated_subtract(short *input, short *value)
00317 {
00318    int res;
00319 
00320    res = (int) *input - *value;
00321    if (res > 32767)
00322       *input = 32767;
00323    else if (res < -32768)
00324       *input = -32768;
00325    else
00326       *input = (short) res;
00327 }
00328    
00329 static force_inline void ast_slinear_saturated_multiply(short *input, short *value)
00330 {
00331    int res;
00332 
00333    res = (int) *input * *value;
00334    if (res > 32767)
00335       *input = 32767;
00336    else if (res < -32768)
00337       *input = -32768;
00338    else
00339       *input = (short) res;
00340 }
00341 
00342 static force_inline void ast_slinear_saturated_divide(short *input, short *value)
00343 {
00344    *input /= *value;
00345 }
00346 
00347 #ifdef localtime_r
00348 #undef localtime_r
00349 #endif
00350 #define localtime_r __dont_use_localtime_r_use_ast_localtime_instead__
00351 
00352 int ast_utils_init(void);
00353 int ast_wait_for_input(int fd, int ms);
00354 
00355 /*!
00356    \brief Try to write string, but wait no more than ms milliseconds
00357    before timing out.
00358 
00359    \note If you are calling ast_carefulwrite, it is assumed that you are calling
00360    it on a file descriptor that _DOES_ have NONBLOCK set.  This way,
00361    there is only one system call made to do a write, unless we actually
00362    have a need to wait.  This way, we get better performance.
00363 */
00364 int ast_carefulwrite(int fd, char *s, int len, int timeoutms);
00365 
00366 /*!
00367  * \brief Write data to a file stream with a timeout
00368  *
00369  * \param f the file stream to write to
00370  * \param fd the file description to poll on to know when the file stream can
00371  *        be written to without blocking.
00372  * \param s the buffer to write from
00373  * \param len the number of bytes to write
00374  * \param timeoutms The maximum amount of time to block in this function trying
00375  *        to write, specified in milliseconds.
00376  *
00377  * \note This function assumes that the associated file stream has been set up
00378  *       as non-blocking.
00379  *
00380  * \retval 0 success
00381  * \retval -1 error
00382  */
00383 int ast_careful_fwrite(FILE *f, int fd, const char *s, size_t len, int timeoutms);
00384 
00385 /*
00386  * Thread management support (should be moved to lock.h or a different header)
00387  */
00388 
00389 #define AST_STACKSIZE (((sizeof(void *) * 8 * 8) - 16) * 1024)
00390 
00391 #if defined(LOW_MEMORY)
00392 #define AST_BACKGROUND_STACKSIZE (((sizeof(void *) * 8 * 2) - 16) * 1024)
00393 #else
00394 #define AST_BACKGROUND_STACKSIZE AST_STACKSIZE
00395 #endif
00396 
00397 void ast_register_thread(char *name);
00398 void ast_unregister_thread(void *id);
00399 
00400 int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
00401               void *data, size_t stacksize, const char *file, const char *caller,
00402               int line, const char *start_fn);
00403 
00404 int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void*(*start_routine)(void *),
00405              void *data, size_t stacksize, const char *file, const char *caller,
00406              int line, const char *start_fn);
00407 
00408 #define ast_pthread_create(a, b, c, d)             \
00409    ast_pthread_create_stack(a, b, c, d,         \
00410       0, __FILE__, __FUNCTION__, __LINE__, #c)
00411 
00412 #define ast_pthread_create_detached(a, b, c, d)       \
00413    ast_pthread_create_detached_stack(a, b, c, d,      \
00414       0, __FILE__, __FUNCTION__, __LINE__, #c)
00415 
00416 #define ast_pthread_create_background(a, b, c, d)     \
00417    ast_pthread_create_stack(a, b, c, d,         \
00418       AST_BACKGROUND_STACKSIZE,        \
00419       __FILE__, __FUNCTION__, __LINE__, #c)
00420 
00421 #define ast_pthread_create_detached_background(a, b, c, d)  \
00422    ast_pthread_create_detached_stack(a, b, c, d,      \
00423       AST_BACKGROUND_STACKSIZE,        \
00424       __FILE__, __FUNCTION__, __LINE__, #c)
00425 
00426 /* End of thread management support */
00427 
00428 /*!
00429    \brief Process a string to find and replace characters
00430    \param start The string to analyze
00431    \param find The character to find
00432    \param replace_with The character that will replace the one we are looking for
00433 */
00434 char *ast_process_quotes_and_slashes(char *start, char find, char replace_with);
00435 
00436 long int ast_random(void);
00437 
00438 
00439 #ifndef __AST_DEBUG_MALLOC
00440 #define ast_std_malloc malloc
00441 #define ast_std_calloc calloc
00442 #define ast_std_realloc realloc
00443 #define ast_std_free free
00444 
00445 /*! 
00446  * \brief free() wrapper
00447  *
00448  * ast_free_ptr should be used when a function pointer for free() needs to be passed
00449  * as the argument to a function. Otherwise, astmm will cause seg faults.
00450  */
00451 #define ast_free free
00452 #define ast_free_ptr ast_free
00453 
00454 #define MALLOC_FAILURE_MSG \
00455    ast_log(LOG_ERROR, "Memory Allocation Failure in function %s at line %d of %s\n", func, lineno, file);
00456 /*!
00457  * \brief A wrapper for malloc()
00458  *
00459  * ast_malloc() is a wrapper for malloc() that will generate an Asterisk log
00460  * message in the case that the allocation fails.
00461  *
00462  * The argument and return value are the same as malloc()
00463  */
00464 #define ast_malloc(len) \
00465    _ast_malloc((len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
00466 
00467 AST_INLINE_API(
00468 void * attribute_malloc _ast_malloc(size_t len, const char *file, int lineno, const char *func),
00469 {
00470    void *p;
00471 
00472    if (!(p = malloc(len)))
00473       MALLOC_FAILURE_MSG;
00474 
00475    return p;
00476 }
00477 )
00478 
00479 /*!
00480  * \brief A wrapper for calloc()
00481  *
00482  * ast_calloc() is a wrapper for calloc() that will generate an Asterisk log
00483  * message in the case that the allocation fails.
00484  *
00485  * The arguments and return value are the same as calloc()
00486  */
00487 #define ast_calloc(num, len) \
00488    _ast_calloc((num), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
00489 
00490 AST_INLINE_API(
00491 void * attribute_malloc _ast_calloc(size_t num, size_t len, const char *file, int lineno, const char *func),
00492 {
00493    void *p;
00494 
00495    if (!(p = calloc(num, len)))
00496       MALLOC_FAILURE_MSG;
00497 
00498    return p;
00499 }
00500 )
00501 
00502 /*!
00503  * \brief A wrapper for calloc() for use in cache pools
00504  *
00505  * ast_calloc_cache() is a wrapper for calloc() that will generate an Asterisk log
00506  * message in the case that the allocation fails. When memory debugging is in use,
00507  * the memory allocated by this function will be marked as 'cache' so it can be
00508  * distinguished from normal memory allocations.
00509  *
00510  * The arguments and return value are the same as calloc()
00511  */
00512 #define ast_calloc_cache(num, len) \
00513    _ast_calloc((num), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
00514 
00515 /*!
00516  * \brief A wrapper for realloc()
00517  *
00518  * ast_realloc() is a wrapper for realloc() that will generate an Asterisk log
00519  * message in the case that the allocation fails.
00520  *
00521  * The arguments and return value are the same as realloc()
00522  */
00523 #define ast_realloc(p, len) \
00524    _ast_realloc((p), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
00525 
00526 AST_INLINE_API(
00527 void * attribute_malloc _ast_realloc(void *p, size_t len, const char *file, int lineno, const char *func),
00528 {
00529    void *newp;
00530 
00531    if (!(newp = realloc(p, len)))
00532       MALLOC_FAILURE_MSG;
00533 
00534    return newp;
00535 }
00536 )
00537 
00538 /*!
00539  * \brief A wrapper for strdup()
00540  *
00541  * ast_strdup() is a wrapper for strdup() that will generate an Asterisk log
00542  * message in the case that the allocation fails.
00543  *
00544  * ast_strdup(), unlike strdup(), can safely accept a NULL argument. If a NULL
00545  * argument is provided, ast_strdup will return NULL without generating any
00546  * kind of error log message.
00547  *
00548  * The argument and return value are the same as strdup()
00549  */
00550 #define ast_strdup(str) \
00551    _ast_strdup((str), __FILE__, __LINE__, __PRETTY_FUNCTION__)
00552 
00553 AST_INLINE_API(
00554 char * attribute_malloc _ast_strdup(const char *str, const char *file, int lineno, const char *func),
00555 {
00556    char *newstr = NULL;
00557 
00558    if (str) {
00559       if (!(newstr = strdup(str)))
00560          MALLOC_FAILURE_MSG;
00561    }
00562 
00563    return newstr;
00564 }
00565 )
00566 
00567 /*!
00568  * \brief A wrapper for strndup()
00569  *
00570  * ast_strndup() is a wrapper for strndup() that will generate an Asterisk log
00571  * message in the case that the allocation fails.
00572  *
00573  * ast_strndup(), unlike strndup(), can safely accept a NULL argument for the
00574  * string to duplicate. If a NULL argument is provided, ast_strdup will return  
00575  * NULL without generating any kind of error log message.
00576  *
00577  * The arguments and return value are the same as strndup()
00578  */
00579 #define ast_strndup(str, len) \
00580    _ast_strndup((str), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
00581 
00582 AST_INLINE_API(
00583 char * attribute_malloc _ast_strndup(const char *str, size_t len, const char *file, int lineno, const char *func),
00584 {
00585    char *newstr = NULL;
00586 
00587    if (str) {
00588       if (!(newstr = strndup(str, len)))
00589          MALLOC_FAILURE_MSG;
00590    }
00591 
00592    return newstr;
00593 }
00594 )
00595 
00596 /*!
00597  * \brief A wrapper for asprintf()
00598  *
00599  * ast_asprintf() is a wrapper for asprintf() that will generate an Asterisk log
00600  * message in the case that the allocation fails.
00601  *
00602  * The arguments and return value are the same as asprintf()
00603  */
00604 #define ast_asprintf(ret, fmt, ...) \
00605    _ast_asprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, fmt, __VA_ARGS__)
00606 
00607 int __attribute__((format(printf, 5, 6)))
00608    _ast_asprintf(char **ret, const char *file, int lineno, const char *func, const char *fmt, ...);
00609 
00610 /*!
00611  * \brief A wrapper for vasprintf()
00612  *
00613  * ast_vasprintf() is a wrapper for vasprintf() that will generate an Asterisk log
00614  * message in the case that the allocation fails.
00615  *
00616  * The arguments and return value are the same as vasprintf()
00617  */
00618 #define ast_vasprintf(ret, fmt, ap) \
00619    _ast_vasprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, (fmt), (ap))
00620 
00621 AST_INLINE_API(
00622 __attribute__((format(printf, 5, 0)))
00623 int _ast_vasprintf(char **ret, const char *file, int lineno, const char *func, const char *fmt, va_list ap),
00624 {
00625    int res;
00626 
00627    if ((res = vasprintf(ret, fmt, ap)) == -1)
00628       MALLOC_FAILURE_MSG;
00629 
00630    return res;
00631 }
00632 )
00633 
00634 #endif /* AST_DEBUG_MALLOC */
00635 
00636 /*!
00637   \brief call __builtin_alloca to ensure we get gcc builtin semantics
00638   \param size The size of the buffer we want allocated
00639 
00640   This macro will attempt to allocate memory from the stack.  If it fails
00641   you won't get a NULL returned, but a SEGFAULT if you're lucky.
00642 */
00643 #define ast_alloca(size) __builtin_alloca(size)
00644 
00645 #if !defined(ast_strdupa) && defined(__GNUC__)
00646 /*!
00647   \brief duplicate a string in memory from the stack
00648   \param s The string to duplicate
00649 
00650   This macro will duplicate the given string.  It returns a pointer to stack
00651   allocated memory for the new string.
00652 */
00653 #define ast_strdupa(s)                                                    \
00654    (__extension__                                                    \
00655    ({                                                                \
00656       const char *__old = (s);                                  \
00657       size_t __len = strlen(__old) + 1;                         \
00658       char *__new = __builtin_alloca(__len);                    \
00659       memcpy (__new, __old, __len);                             \
00660       __new;                                                    \
00661    }))
00662 #endif
00663 
00664 /*!
00665   \brief Disable PMTU discovery on a socket
00666   \param sock The socket to manipulate
00667   \return Nothing
00668 
00669   On Linux, UDP sockets default to sending packets with the Dont Fragment (DF)
00670   bit set. This is supposedly done to allow the application to do PMTU
00671   discovery, but Asterisk does not do this.
00672 
00673   Because of this, UDP packets sent by Asterisk that are larger than the MTU
00674   of any hop in the path will be lost. This function can be called on a socket
00675   to ensure that the DF bit will not be set.
00676  */
00677 void ast_enable_packet_fragmentation(int sock);
00678 
00679 /*!
00680   \brief Recursively create directory path
00681   \param path The directory path to create
00682   \param mode The permissions with which to try to create the directory
00683   \return 0 on success or an error code otherwise
00684 
00685   Creates a directory path, creating parent directories as needed.
00686  */
00687 int ast_mkdir(const char *path, int mode);
00688 
00689 #define ARRAY_LEN(a) (size_t) (sizeof(a) / sizeof(0[a]))
00690 
00691 
00692 /* Definition for Digest authorization */
00693 struct ast_http_digest {
00694    AST_DECLARE_STRING_FIELDS(
00695       AST_STRING_FIELD(username);
00696       AST_STRING_FIELD(nonce);
00697       AST_STRING_FIELD(uri);
00698       AST_STRING_FIELD(realm);
00699       AST_STRING_FIELD(domain);
00700       AST_STRING_FIELD(response);
00701       AST_STRING_FIELD(cnonce);
00702       AST_STRING_FIELD(opaque);
00703       AST_STRING_FIELD(nc);
00704    );
00705    int qop;    /* Flag set to 1, if we send/recv qop="quth" */
00706 };
00707 
00708 /*!
00709  *\brief Parse digest authorization header.
00710  *\return Returns -1 if we have no auth or something wrong with digest.
00711  *\note This function may be used for Digest request and responce header.
00712  * request arg is set to nonzero, if we parse Digest Request.
00713  * pedantic arg can be set to nonzero if we need to do addition Digest check.
00714  */
00715 int ast_parse_digest(const char *digest, struct ast_http_digest *d, int request, int pedantic);
00716 
00717 
00718 #ifdef AST_DEVMODE
00719 void __ast_assert_failed(int condition, const char *condition_str, const char *file, int line, const char *function);
00720 #define ast_assert(a) _ast_assert(a, # a, __FILE__, __LINE__, __PRETTY_FUNCTION__)
00721 static void force_inline _ast_assert(int condition, const char *condition_str, const char *file, int line, const char *function)
00722 {
00723    if (__builtin_expect(!condition, 1)) {
00724       __ast_assert_failed(condition, condition_str, file, line, function);
00725    }
00726 }
00727 #else
00728 #define ast_assert(a)
00729 #endif
00730 
00731 /*!
00732  * \brief Force a crash if DO_CRASH is defined.
00733  *
00734  * \note If DO_CRASH is not defined then the function returns.
00735  *
00736  * \return Nothing
00737  */
00738 void ast_do_crash(void);
00739 
00740 #include "asterisk/strings.h"
00741 
00742 /*!
00743  * \brief Return the number of bytes used in the alignment of type.
00744  * \param type
00745  * \return The number of bytes required for alignment.
00746  *
00747  * This is really just __alignof__(), but tucked away in this header so we
00748  * don't have to look at the nasty underscores in the source.
00749  */
00750 #define ast_alignof(type) __alignof__(type)
00751 
00752 /*!
00753  * \brief Increase offset so it is a multiple of the required alignment of type.
00754  * \param offset The value that should be increased.
00755  * \param type The data type that offset should be aligned to.
00756  * \return The smallest multiple of alignof(type) larger than or equal to offset.
00757  * \see ast_make_room_for()
00758  *
00759  * Many systems prefer integers to be stored on aligned on memory locations.
00760  * This macro will increase an offset so a value of the supplied type can be
00761  * safely be stored on such a memory location.
00762  *
00763  * Examples:
00764  * ast_align_for(0x17, int64_t) ==> 0x18
00765  * ast_align_for(0x18, int64_t) ==> 0x18
00766  * ast_align_for(0x19, int64_t) ==> 0x20
00767  *
00768  * Don't mind the ugliness, the compiler will optimize it.
00769  */
00770 #define ast_align_for(offset, type) (((offset + __alignof__(type) - 1) / __alignof__(type)) * __alignof__(type))
00771 
00772 /*!
00773  * \brief Increase offset by the required alignment of type and make sure it is
00774  *        a multiple of said alignment.
00775  * \param offset The value that should be increased.
00776  * \param type The data type that room should be reserved for.
00777  * \return The smallest multiple of alignof(type) larger than or equal to offset
00778  *         plus alignof(type).
00779  * \see ast_align_for()
00780  *
00781  * A use case for this is when prepending length fields of type int to a buffer.
00782  * If you keep the offset a multiple of the alignment of the integer type,
00783  * a next block of length+buffer will have the length field automatically
00784  * aligned.
00785  *
00786  * Examples:
00787  * ast_make_room_for(0x17, int64_t) ==> 0x20
00788  * ast_make_room_for(0x18, int64_t) ==> 0x20
00789  * ast_make_room_for(0x19, int64_t) ==> 0x28
00790  *
00791  * Don't mind the ugliness, the compiler will optimize it.
00792  */
00793 #define ast_make_room_for(offset, type) (((offset + (2 * __alignof__(type) - 1)) / __alignof__(type)) * __alignof__(type))
00794 
00795 /*!
00796  * \brief An Entity ID is essentially a MAC address, brief and unique 
00797  */
00798 struct ast_eid {
00799    unsigned char eid[6];
00800 } __attribute__((__packed__));
00801 
00802 /*!
00803  * \brief Global EID
00804  *
00805  * This is set in asterisk.conf, or determined automatically by taking the mac
00806  * address of an Ethernet interface on the system.
00807  */
00808 extern struct ast_eid ast_eid_default;
00809 
00810 /*!
00811  * \brief Fill in an ast_eid with the default eid of this machine
00812  * \since 1.6.1
00813  */
00814 void ast_set_default_eid(struct ast_eid *eid);
00815 
00816 /*!
00817  * /brief Convert an EID to a string
00818  * \since 1.6.1
00819  */
00820 char *ast_eid_to_str(char *s, int maxlen, struct ast_eid *eid);
00821 
00822 /*!
00823  * \brief Convert a string into an EID
00824  *
00825  * This function expects an EID in the format:
00826  *    00:11:22:33:44:55
00827  *
00828  * \return 0 success, non-zero failure
00829  * \since 1.6.1
00830  */
00831 int ast_str_to_eid(struct ast_eid *eid, const char *s);
00832 
00833 /*!
00834  * \brief Compare two EIDs
00835  *
00836  * \return 0 if the two are the same, non-zero otherwise
00837  * \since 1.6.1
00838  */
00839 int ast_eid_cmp(const struct ast_eid *eid1, const struct ast_eid *eid2);
00840 
00841 /*!\brief Resolve a binary to a full pathname
00842  * \param binary Name of the executable to resolve
00843  * \param fullpath Buffer to hold the complete pathname
00844  * \param fullpath_size Size of \a fullpath
00845  * \retval NULL \a binary was not found or the environment variable PATH is not set
00846  * \return \a fullpath
00847  */
00848 char *ast_utils_which(const char *binary, char *fullpath, size_t fullpath_size);
00849 
00850 /*!
00851  * \brief Declare a variable that will call a destructor function when it goes out of scope.
00852  *
00853  * Resource Allocation Is Initialization (RAII) variable declaration.
00854  *
00855  * \since 1.8.24.0
00856  * \param vartype The type of the variable
00857  * \param varname The name of the variable
00858  * \param initval The initial value of the variable
00859  * \param dtor The destructor function of type' void func(vartype *)'
00860  *
00861  * \code
00862  * void mything_cleanup(struct mything *t)
00863  * {
00864  *     if (t) {
00865  *         ast_free(t->stuff);
00866  *     }
00867  * }
00868  *
00869  * void do_stuff(const char *name)
00870  * {
00871  *     RAII_VAR(struct mything *, thing, mything_alloc(name), mything_cleanup);
00872  *     ...
00873  * }
00874  * \endcode
00875  *
00876  * \note This macro is especially useful for working with ao2 objects. A common idiom
00877  * would be a function that needed to look up an ao2 object and might have several error
00878  * conditions after the allocation that would normally need to unref the ao2 object.
00879  * With RAII_VAR, it is possible to just return and leave the cleanup to the destructor
00880  * function. For example:
00881  *
00882  * \code
00883  * void do_stuff(const char *name)
00884  * {
00885  *     RAII_VAR(struct mything *, thing, find_mything(name), ao2_cleanup);
00886  *     if (!thing) {
00887  *         return;
00888  *     }
00889  *     if (error) {
00890  *         return;
00891  *     }
00892  *     do_stuff_with_thing(thing);
00893  * }
00894  * \endcode
00895  */
00896 #define RAII_VAR(vartype, varname, initval, dtor) \
00897     /* Prototype needed due to http://gcc.gnu.org/bugzilla/show_bug.cgi?id=36774 */ \
00898     auto void _dtor_ ## varname (vartype * v); \
00899     void _dtor_ ## varname (vartype * v) { dtor(*v); } \
00900     vartype varname __attribute__((cleanup(_dtor_ ## varname))) = (initval)
00901 
00902 #endif /* _ASTERISK_UTILS_H */