2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
20 * \brief Utility functions
23 #ifndef _ASTERISK_UTILS_H
24 #define _ASTERISK_UTILS_H
26 #include "asterisk/compat.h"
31 #include <netinet/in.h>
32 #include <arpa/inet.h> /* we want to override inet_ntoa */
35 #include <time.h> /* we want to override localtime_r */
38 #include "asterisk/lock.h"
39 #include "asterisk/time.h"
40 #include "asterisk/strings.h"
41 #include "asterisk/logger.h"
42 #include "asterisk/compiler.h"
43 #include "asterisk/localtime.h"
48 It is very important to use only unsigned variables to hold
49 bit flags, as otherwise you can fall prey to the compiler's
50 sign-extension antics if you try to use the top two bits in
53 The flag macros below use a set of compiler tricks to verify
54 that the caller is using an "unsigned int" variable to hold
55 the flags, and nothing else. If the caller uses any other
56 type of variable, a warning message similar to this:
58 warning: comparison of distinct pointer types lacks cast
61 The "dummy" variable below is used to make these comparisons.
63 Also note that at -O2 or above, this type-safety checking
64 does _not_ produce any additional object code at all.
68 extern unsigned int __unsigned_int_flags_dummy
;
70 #define ast_test_flag(p,flag) ({ \
71 typeof ((p)->flags) __p = (p)->flags; \
72 typeof (__unsigned_int_flags_dummy) __x = 0; \
73 (void) (&__p == &__x); \
74 ((p)->flags & (flag)); \
77 #define ast_set_flag(p,flag) do { \
78 typeof ((p)->flags) __p = (p)->flags; \
79 typeof (__unsigned_int_flags_dummy) __x = 0; \
80 (void) (&__p == &__x); \
81 ((p)->flags |= (flag)); \
84 #define ast_clear_flag(p,flag) do { \
85 typeof ((p)->flags) __p = (p)->flags; \
86 typeof (__unsigned_int_flags_dummy) __x = 0; \
87 (void) (&__p == &__x); \
88 ((p)->flags &= ~(flag)); \
91 #define ast_copy_flags(dest,src,flagz) do { \
92 typeof ((dest)->flags) __d = (dest)->flags; \
93 typeof ((src)->flags) __s = (src)->flags; \
94 typeof (__unsigned_int_flags_dummy) __x = 0; \
95 (void) (&__d == &__x); \
96 (void) (&__s == &__x); \
97 (dest)->flags &= ~(flagz); \
98 (dest)->flags |= ((src)->flags & (flagz)); \
101 #define ast_set2_flag(p,value,flag) do { \
102 typeof ((p)->flags) __p = (p)->flags; \
103 typeof (__unsigned_int_flags_dummy) __x = 0; \
104 (void) (&__p == &__x); \
106 (p)->flags |= (flag); \
108 (p)->flags &= ~(flag); \
111 #define ast_set_flags_to(p,flag,value) do { \
112 typeof ((p)->flags) __p = (p)->flags; \
113 typeof (__unsigned_int_flags_dummy) __x = 0; \
114 (void) (&__p == &__x); \
115 (p)->flags &= ~(flag); \
116 (p)->flags |= (value); \
119 /* Non-type checking variations for non-unsigned int flags. You
120 should only use non-unsigned int flags where required by
121 protocol etc and if you know what you're doing :) */
122 #define ast_test_flag_nonstd(p,flag) \
123 ((p)->flags & (flag))
125 #define ast_set_flag_nonstd(p,flag) do { \
126 ((p)->flags |= (flag)); \
129 #define ast_clear_flag_nonstd(p,flag) do { \
130 ((p)->flags &= ~(flag)); \
133 #define ast_copy_flags_nonstd(dest,src,flagz) do { \
134 (dest)->flags &= ~(flagz); \
135 (dest)->flags |= ((src)->flags & (flagz)); \
138 #define ast_set2_flag_nonstd(p,value,flag) do { \
140 (p)->flags |= (flag); \
142 (p)->flags &= ~(flag); \
145 #define AST_FLAGS_ALL UINT_MAX
156 struct hostent
*ast_gethostbyname(const char *host
, struct ast_hostent
*hp
);
159 \brief Produces MD5 hash based on input string */
160 void ast_md5_hash(char *output
, char *input
);
162 \brief Produces SHA1 hash based on input string */
163 void ast_sha1_hash(char *output
, char *input
);
165 int ast_base64encode_full(char *dst
, const unsigned char *src
, int srclen
, int max
, int linebreaks
);
166 int ast_base64encode(char *dst
, const unsigned char *src
, int srclen
, int max
);
167 int ast_base64decode(unsigned char *dst
, const char *src
, int max
);
170 \brief Turn text string to URI-encoded %XX version
171 At this point, we're converting from ISO-8859-x (8-bit), not UTF8
172 as in the SIP protocol spec
173 If doreserved == 1 we will convert reserved characters also.
174 RFC 2396, section 2.4
175 outbuf needs to have more memory allocated than the instring
176 to have room for the expansion. Every char that is converted
177 is replaced by three ASCII characters.
178 \param string String to be converted
179 \param outbuf Resulting encoded string
180 \param buflen Size of output buffer
181 \param doreserved Convert reserved characters
184 char *ast_uri_encode(const char *string
, char *outbuf
, int buflen
, int doreserved
);
186 /*! \brief Decode URI, URN, URL (overwrite string)
187 \param s String to be decoded
189 void ast_uri_decode(char *s
);
191 static force_inline
void ast_slinear_saturated_add(short *input
, short *value
)
195 res
= (int) *input
+ *value
;
198 else if (res
< -32767)
201 *input
= (short) res
;
204 static force_inline
void ast_slinear_saturated_multiply(short *input
, short *value
)
208 res
= (int) *input
* *value
;
211 else if (res
< -32767)
214 *input
= (short) res
;
217 static force_inline
void ast_slinear_saturated_divide(short *input
, short *value
)
222 int test_for_thread_safety(void);
225 * \brief thread-safe replacement for inet_ntoa().
227 * \note It is very important to note that even though this is a thread-safe
228 * replacement for inet_ntoa(), it is *not* reentrant. In a single
229 * thread, the result from a previous call to this function is no longer
230 * valid once it is called again. If the result from multiple calls to
231 * this function need to be kept or used at once, then the result must be
232 * copied to a local buffer before calling this function again.
234 const char *ast_inet_ntoa(struct in_addr ia
);
239 #define inet_ntoa __dont__use__inet_ntoa__use__ast_inet_ntoa__instead__
244 #define localtime_r __dont_use_localtime_r_use_ast_localtime_instead__
246 int ast_utils_init(void);
247 int ast_wait_for_input(int fd
, int ms
);
250 \brief Try to write string, but wait no more than ms milliseconds
253 \note If you are calling ast_carefulwrite, it is assumed that you are calling
254 it on a file descriptor that _DOES_ have NONBLOCK set. This way,
255 there is only one system call made to do a write, unless we actually
256 have a need to wait. This way, we get better performance.
258 int ast_carefulwrite(int fd
, char *s
, int len
, int timeoutms
);
260 /*! Compares the source address and port of two sockaddr_in */
261 static force_inline
int inaddrcmp(const struct sockaddr_in
*sin1
, const struct sockaddr_in
*sin2
)
263 return ((sin1
->sin_addr
.s_addr
!= sin2
->sin_addr
.s_addr
)
264 || (sin1
->sin_port
!= sin2
->sin_port
));
267 #define AST_STACKSIZE 240 * 1024
269 #if defined(LOW_MEMORY)
270 #define AST_BACKGROUND_STACKSIZE 48 * 1024
272 #define AST_BACKGROUND_STACKSIZE 240 * 1024
275 void ast_register_thread(char *name
);
276 void ast_unregister_thread(void *id
);
278 int ast_pthread_create_stack(pthread_t
*thread
, pthread_attr_t
*attr
, void *(*start_routine
)(void *),
279 void *data
, size_t stacksize
, const char *file
, const char *caller
,
280 int line
, const char *start_fn
);
282 #define ast_pthread_create(a, b, c, d) ast_pthread_create_stack(a, b, c, d, \
284 __FILE__, __FUNCTION__, \
287 #define ast_pthread_create_background(a, b, c, d) ast_pthread_create_stack(a, b, c, d, \
288 AST_BACKGROUND_STACKSIZE, \
289 __FILE__, __FUNCTION__, \
293 \brief Process a string to find and replace characters
294 \param start The string to analyze
295 \param find The character to find
296 \param replace_with The character that will replace the one we are looking for
298 char *ast_process_quotes_and_slashes(char *start
, char find
, char replace_with
);
301 #define ast_random random
303 long int ast_random(void);
307 * \brief free() wrapper
309 * ast_free should be used when a function pointer for free() needs to be passed
310 * as the argument to a function. Otherwise, astmm will cause seg faults.
312 #ifdef __AST_DEBUG_MALLOC
313 static void ast_free(void *ptr
) attribute_unused
;
314 static void ast_free(void *ptr
)
319 #define ast_free free
322 #ifndef __AST_DEBUG_MALLOC
324 #define MALLOC_FAILURE_MSG \
325 ast_log(LOG_ERROR, "Memory Allocation Failure in function %s at line %d of %s\n", func, lineno, file);
327 * \brief A wrapper for malloc()
329 * ast_malloc() is a wrapper for malloc() that will generate an Asterisk log
330 * message in the case that the allocation fails.
332 * The argument and return value are the same as malloc()
334 #define ast_malloc(len) \
335 _ast_malloc((len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
338 void * attribute_malloc
_ast_malloc(size_t len
, const char *file
, int lineno
, const char *func
),
342 if (!(p
= malloc(len
)))
350 * \brief A wrapper for calloc()
352 * ast_calloc() is a wrapper for calloc() that will generate an Asterisk log
353 * message in the case that the allocation fails.
355 * The arguments and return value are the same as calloc()
357 #define ast_calloc(num, len) \
358 _ast_calloc((num), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
361 void * attribute_malloc
_ast_calloc(size_t num
, size_t len
, const char *file
, int lineno
, const char *func
),
365 if (!(p
= calloc(num
, len
)))
373 * \brief A wrapper for calloc() for use in cache pools
375 * ast_calloc_cache() is a wrapper for calloc() that will generate an Asterisk log
376 * message in the case that the allocation fails. When memory debugging is in use,
377 * the memory allocated by this function will be marked as 'cache' so it can be
378 * distinguished from normal memory allocations.
380 * The arguments and return value are the same as calloc()
382 #define ast_calloc_cache(num, len) \
383 _ast_calloc((num), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
386 * \brief A wrapper for realloc()
388 * ast_realloc() is a wrapper for realloc() that will generate an Asterisk log
389 * message in the case that the allocation fails.
391 * The arguments and return value are the same as realloc()
393 #define ast_realloc(p, len) \
394 _ast_realloc((p), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
397 void * attribute_malloc
_ast_realloc(void *p
, size_t len
, const char *file
, int lineno
, const char *func
),
401 if (!(newp
= realloc(p
, len
)))
409 * \brief A wrapper for strdup()
411 * ast_strdup() is a wrapper for strdup() that will generate an Asterisk log
412 * message in the case that the allocation fails.
414 * ast_strdup(), unlike strdup(), can safely accept a NULL argument. If a NULL
415 * argument is provided, ast_strdup will return NULL without generating any
416 * kind of error log message.
418 * The argument and return value are the same as strdup()
420 #define ast_strdup(str) \
421 _ast_strdup((str), __FILE__, __LINE__, __PRETTY_FUNCTION__)
424 char * attribute_malloc
_ast_strdup(const char *str
, const char *file
, int lineno
, const char *func
),
429 if (!(newstr
= strdup(str
)))
438 * \brief A wrapper for strndup()
440 * ast_strndup() is a wrapper for strndup() that will generate an Asterisk log
441 * message in the case that the allocation fails.
443 * ast_strndup(), unlike strndup(), can safely accept a NULL argument for the
444 * string to duplicate. If a NULL argument is provided, ast_strdup will return
445 * NULL without generating any kind of error log message.
447 * The arguments and return value are the same as strndup()
449 #define ast_strndup(str, len) \
450 _ast_strndup((str), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
453 char * attribute_malloc
_ast_strndup(const char *str
, size_t len
, const char *file
, int lineno
, const char *func
),
458 if (!(newstr
= strndup(str
, len
)))
467 * \brief A wrapper for asprintf()
469 * ast_asprintf() is a wrapper for asprintf() that will generate an Asterisk log
470 * message in the case that the allocation fails.
472 * The arguments and return value are the same as asprintf()
474 #define ast_asprintf(ret, fmt, ...) \
475 _ast_asprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, fmt, __VA_ARGS__)
477 int _ast_asprintf(char **ret
, const char *file
, int lineno
, const char *func
, const char *fmt
, ...) __attribute__ ((format (printf
, 5, 6)));
480 * \brief A wrapper for vasprintf()
482 * ast_vasprintf() is a wrapper for vasprintf() that will generate an Asterisk log
483 * message in the case that the allocation fails.
485 * The arguments and return value are the same as vasprintf()
487 #define ast_vasprintf(ret, fmt, ap) \
488 _ast_vasprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, (fmt), (ap))
491 int _ast_vasprintf(char **ret
, const char *file
, int lineno
, const char *func
, const char *fmt
, va_list ap
),
495 if ((res
= vasprintf(ret
, fmt
, ap
)) == -1)
504 /* If astmm is in use, let it handle these. Otherwise, it will report that
505 all allocations are coming from this header file */
507 #define ast_malloc(a) malloc(a)
508 #define ast_calloc(a,b) calloc(a,b)
509 #define ast_realloc(a,b) realloc(a,b)
510 #define ast_strdup(a) strdup(a)
511 #define ast_strndup(a,b) strndup(a,b)
512 #define ast_asprintf(a,b,...) asprintf(a,b,__VA_ARGS__)
513 #define ast_vasprintf(a,b,c) vasprintf(a,b,c)
515 #endif /* AST_DEBUG_MALLOC */
517 #if !defined(ast_strdupa) && defined(__GNUC__)
519 \brief duplicate a string in memory from the stack
520 \param s The string to duplicate
522 This macro will duplicate the given string. It returns a pointer to the stack
523 allocatted memory for the new string.
525 #define ast_strdupa(s) \
528 const char *__old = (s); \
529 size_t __len = strlen(__old) + 1; \
530 char *__new = __builtin_alloca(__len); \
531 memcpy (__new, __old, __len); \
537 \brief Disable PMTU discovery on a socket
538 \param sock The socket to manipulate
541 On Linux, UDP sockets default to sending packets with the Dont Fragment (DF)
542 bit set. This is supposedly done to allow the application to do PMTU
543 discovery, but Asterisk does not do this.
545 Because of this, UDP packets sent by Asterisk that are larger than the MTU
546 of any hop in the path will be lost. This function can be called on a socket
547 to ensure that the DF bit will not be set.
549 void ast_enable_packet_fragmentation(int sock
);
551 #define ARRAY_LEN(a) (sizeof(a) / sizeof(a[0]))
554 #define ast_assert(a) _ast_assert(a, # a, __FILE__, __LINE__, __PRETTY_FUNCTION__)
555 static void force_inline
_ast_assert(int condition
, const char *condition_str
,
556 const char *file
, int line
, const char *function
)
558 if (__builtin_expect(!condition
, 1)) {
559 /* Attempt to put it into the logger, but hope that at least someone saw the
560 * message on stderr ... */
561 ast_log(LOG_ERROR
, "FRACK!, Failed assertion %s (%d) at line %d in %s of %s\n",
562 condition_str
, condition
, line
, function
, file
);
563 fprintf(stderr
, "FRACK!, Failed assertion %s (%d) at line %d in %s of %s\n",
564 condition_str
, condition
, line
, function
, file
);
565 /* Give the logger a chance to get the message out, just in case we abort(), or
566 * Asterisk crashes due to whatever problem just happened after we exit ast_assert(). */
570 /* Just in case abort() doesn't work or something else super silly,
571 * and for Qwell's amusement. */
577 #define ast_assert(a)
580 #endif /* _ASTERISK_UTILS_H */