change the required dependency for codec_dahdi to only be satisfied by DAHDI and...
[asterisk-bristuff.git] / include / asterisk / utils.h
blob4e4d9d5ee0e2d665d6d47919cad156ea90a5b3f4
1 /*
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.
19 /*! \file
20 * \brief Utility functions
23 #ifndef _ASTERISK_UTILS_H
24 #define _ASTERISK_UTILS_H
26 #include "asterisk/compat.h"
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <stdarg.h>
31 #include <netinet/in.h>
32 #include <arpa/inet.h> /* we want to override inet_ntoa */
33 #include <netdb.h>
34 #include <limits.h>
35 #include <time.h> /* we want to override localtime_r */
36 #include <unistd.h>
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"
45 /*! \note
46 \verbatim
47 Note:
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
51 your variable.
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
59 will be generated.
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.
65 \endverbatim
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)); \
82 } while(0)
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)); \
89 } while(0)
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)); \
99 } while (0)
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); \
105 if (value) \
106 (p)->flags |= (flag); \
107 else \
108 (p)->flags &= ~(flag); \
109 } while (0)
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); \
117 } while (0)
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)); \
127 } while(0)
129 #define ast_clear_flag_nonstd(p,flag) do { \
130 ((p)->flags &= ~(flag)); \
131 } while(0)
133 #define ast_copy_flags_nonstd(dest,src,flagz) do { \
134 (dest)->flags &= ~(flagz); \
135 (dest)->flags |= ((src)->flags & (flagz)); \
136 } while (0)
138 #define ast_set2_flag_nonstd(p,value,flag) do { \
139 if (value) \
140 (p)->flags |= (flag); \
141 else \
142 (p)->flags &= ~(flag); \
143 } while (0)
145 #define AST_FLAGS_ALL UINT_MAX
147 struct ast_flags {
148 unsigned int flags;
151 struct ast_hostent {
152 struct hostent hp;
153 char buf[1024];
156 struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp);
158 /* ast_md5_hash
159 \brief Produces MD5 hash based on input string */
160 void ast_md5_hash(char *output, char *input);
161 /* ast_sha1_hash
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);
169 /*! ast_uri_encode
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)
193 int res;
195 res = (int) *input + *value;
196 if (res > 32767)
197 *input = 32767;
198 else if (res < -32767)
199 *input = -32767;
200 else
201 *input = (short) res;
204 static force_inline void ast_slinear_saturated_multiply(short *input, short *value)
206 int res;
208 res = (int) *input * *value;
209 if (res > 32767)
210 *input = 32767;
211 else if (res < -32767)
212 *input = -32767;
213 else
214 *input = (short) res;
217 static force_inline void ast_slinear_saturated_divide(short *input, short *value)
219 *input /= *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);
236 #ifdef inet_ntoa
237 #undef inet_ntoa
238 #endif
239 #define inet_ntoa __dont__use__inet_ntoa__use__ast_inet_ntoa__instead__
241 #ifdef localtime_r
242 #undef localtime_r
243 #endif
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);
249 /*! ast_carefulwrite
250 \brief Try to write string, but wait no more than ms milliseconds
251 before timing out.
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
271 #else
272 #define AST_BACKGROUND_STACKSIZE 240 * 1024
273 #endif
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, \
283 0, \
284 __FILE__, __FUNCTION__, \
285 __LINE__, #c)
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__, \
290 __LINE__, #c)
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);
300 #ifdef linux
301 #define ast_random random
302 #else
303 long int ast_random(void);
304 #endif
306 /*!
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)
316 free(ptr);
318 #else
319 #define ast_free free
320 #endif
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__)
337 AST_INLINE_API(
338 void * attribute_malloc _ast_malloc(size_t len, const char *file, int lineno, const char *func),
340 void *p;
342 if (!(p = malloc(len)))
343 MALLOC_FAILURE_MSG;
345 return p;
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__)
360 AST_INLINE_API(
361 void * attribute_malloc _ast_calloc(size_t num, size_t len, const char *file, int lineno, const char *func),
363 void *p;
365 if (!(p = calloc(num, len)))
366 MALLOC_FAILURE_MSG;
368 return p;
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__)
396 AST_INLINE_API(
397 void * attribute_malloc _ast_realloc(void *p, size_t len, const char *file, int lineno, const char *func),
399 void *newp;
401 if (!(newp = realloc(p, len)))
402 MALLOC_FAILURE_MSG;
404 return newp;
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__)
423 AST_INLINE_API(
424 char * attribute_malloc _ast_strdup(const char *str, const char *file, int lineno, const char *func),
426 char *newstr = NULL;
428 if (str) {
429 if (!(newstr = strdup(str)))
430 MALLOC_FAILURE_MSG;
433 return newstr;
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__)
452 AST_INLINE_API(
453 char * attribute_malloc _ast_strndup(const char *str, size_t len, const char *file, int lineno, const char *func),
455 char *newstr = NULL;
457 if (str) {
458 if (!(newstr = strndup(str, len)))
459 MALLOC_FAILURE_MSG;
462 return newstr;
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))
490 AST_INLINE_API(
491 int _ast_vasprintf(char **ret, const char *file, int lineno, const char *func, const char *fmt, va_list ap),
493 int res;
495 if ((res = vasprintf(ret, fmt, ap)) == -1)
496 MALLOC_FAILURE_MSG;
498 return res;
502 #else
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) \
526 (__extension__ \
527 ({ \
528 const char *__old = (s); \
529 size_t __len = strlen(__old) + 1; \
530 char *__new = __builtin_alloca(__len); \
531 memcpy (__new, __old, __len); \
532 __new; \
534 #endif
537 \brief Disable PMTU discovery on a socket
538 \param sock The socket to manipulate
539 \return Nothing
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]))
553 #ifdef AST_DEVMODE
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(). */
567 usleep(1);
568 #ifdef DO_CRASH
569 abort();
570 /* Just in case abort() doesn't work or something else super silly,
571 * and for Qwell's amusement. */
572 *((int*)0)=0;
573 #endif
576 #else
577 #define ast_assert(a)
578 #endif
580 #endif /* _ASTERISK_UTILS_H */