Asterisk - The Open Source Telephony Project GIT-master-67613d1
utils.h
Go to the documentation of this file.
1/*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2006, Digium, Inc.
5 *
6 * Mark Spencer <markster@digium.com>
7 *
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.
13 *
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.
17 */
18
19/*! \file
20 * \brief Utility functions
21 */
22
23#ifndef _ASTERISK_UTILS_H
24#define _ASTERISK_UTILS_H
25
26#include "asterisk/network.h"
27
28#include <time.h> /* we want to override localtime_r */
29#include <unistd.h>
30#include <string.h>
31
32#include "asterisk/lock.h"
33#include "asterisk/time.h"
34#include "asterisk/logger.h"
35#include "asterisk/localtime.h"
37
38/*!
39\note \verbatim
40 Note:
41 It is very important to use only unsigned variables to hold
42 bit flags, as otherwise you can fall prey to the compiler's
43 sign-extension antics if you try to use the top two bits in
44 your variable.
45
46 The flag macros below use a set of compiler tricks to verify
47 that the caller is using an "unsigned int" variable to hold
48 the flags, and nothing else. If the caller uses any other
49 type of variable, a warning message similar to this:
50
51 warning: comparison of distinct pointer types lacks cast
52 will be generated.
53
54 The "dummy" variable below is used to make these comparisons.
55
56 Also note that at -O2 or above, this type-safety checking
57 does _not_ produce any additional object code at all.
58 \endverbatim
59*/
60
61extern unsigned int __unsigned_int_flags_dummy;
62
63#define ast_test_flag(p,flag) ({ \
64 typeof ((p)->flags) __p = (p)->flags; \
65 typeof (__unsigned_int_flags_dummy) __x = 0; \
66 (void) (&__p == &__x); \
67 ((p)->flags & (flag)); \
68 })
69
70#define ast_set_flag(p,flag) do { \
71 typeof ((p)->flags) __p = (p)->flags; \
72 typeof (__unsigned_int_flags_dummy) __x = 0; \
73 (void) (&__p == &__x); \
74 ((p)->flags |= (flag)); \
75 } while(0)
76
77#define ast_clear_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)
83
84#define ast_copy_flags(dest,src,flagz) do { \
85 typeof ((dest)->flags) __d = (dest)->flags; \
86 typeof ((src)->flags) __s = (src)->flags; \
87 typeof (__unsigned_int_flags_dummy) __x = 0; \
88 (void) (&__d == &__x); \
89 (void) (&__s == &__x); \
90 (dest)->flags &= ~(flagz); \
91 (dest)->flags |= ((src)->flags & (flagz)); \
92 } while (0)
93
94#define ast_set2_flag(p,value,flag) do { \
95 typeof ((p)->flags) __p = (p)->flags; \
96 typeof (__unsigned_int_flags_dummy) __x = 0; \
97 (void) (&__p == &__x); \
98 if (value) \
99 (p)->flags |= (flag); \
100 else \
101 (p)->flags &= ~(flag); \
102 } while (0)
103
104#define ast_set_flags_to(p,flag,value) do { \
105 typeof ((p)->flags) __p = (p)->flags; \
106 typeof (__unsigned_int_flags_dummy) __x = 0; \
107 (void) (&__p == &__x); \
108 (p)->flags &= ~(flag); \
109 (p)->flags |= (value); \
110 } while (0)
111
112
113/* The following 64-bit flag code can most likely be erased after app_dial
114 is reorganized to either reduce the large number of options, or handle
115 them in some other way. At the time of this writing, app_dial would be
116 the only user of 64-bit option flags */
117
118extern uint64_t __unsigned_int_flags_dummy64;
119
120#define ast_test_flag64(p,flag) ({ \
121 typeof ((p)->flags) __p = (p)->flags; \
122 typeof (__unsigned_int_flags_dummy64) __x = 0; \
123 (void) (&__p == &__x); \
124 ((p)->flags & (flag)); \
125 })
126
127#define ast_set_flag64(p,flag) do { \
128 typeof ((p)->flags) __p = (p)->flags; \
129 typeof (__unsigned_int_flags_dummy64) __x = 0; \
130 (void) (&__p == &__x); \
131 ((p)->flags |= (flag)); \
132 } while(0)
133
134#define ast_clear_flag64(p,flag) do { \
135 typeof ((p)->flags) __p = (p)->flags; \
136 typeof (__unsigned_int_flags_dummy64) __x = 0; \
137 (void) (&__p == &__x); \
138 ((p)->flags &= ~(flag)); \
139 } while(0)
140
141#define ast_copy_flags64(dest,src,flagz) do { \
142 typeof ((dest)->flags) __d = (dest)->flags; \
143 typeof ((src)->flags) __s = (src)->flags; \
144 typeof (__unsigned_int_flags_dummy64) __x = 0; \
145 (void) (&__d == &__x); \
146 (void) (&__s == &__x); \
147 (dest)->flags &= ~(flagz); \
148 (dest)->flags |= ((src)->flags & (flagz)); \
149 } while (0)
150
151#define ast_set2_flag64(p,value,flag) do { \
152 typeof ((p)->flags) __p = (p)->flags; \
153 typeof (__unsigned_int_flags_dummy64) __x = 0; \
154 (void) (&__p == &__x); \
155 if (value) \
156 (p)->flags |= (flag); \
157 else \
158 (p)->flags &= ~(flag); \
159 } while (0)
160
161#define ast_set_flags_to64(p,flag,value) do { \
162 typeof ((p)->flags) __p = (p)->flags; \
163 typeof (__unsigned_int_flags_dummy64) __x = 0; \
164 (void) (&__p == &__x); \
165 (p)->flags &= ~(flag); \
166 (p)->flags |= (value); \
167 } while (0)
168
169
170/* Non-type checking variations for non-unsigned int flags. You
171 should only use non-unsigned int flags where required by
172 protocol etc and if you know what you're doing :) */
173#define ast_test_flag_nonstd(p,flag) \
174 ((p)->flags & (flag))
175
176#define ast_set_flag_nonstd(p,flag) do { \
177 ((p)->flags |= (flag)); \
178 } while(0)
179
180#define ast_clear_flag_nonstd(p,flag) do { \
181 ((p)->flags &= ~(flag)); \
182 } while(0)
183
184#define ast_copy_flags_nonstd(dest,src,flagz) do { \
185 (dest)->flags &= ~(flagz); \
186 (dest)->flags |= ((src)->flags & (flagz)); \
187 } while (0)
188
189#define ast_set2_flag_nonstd(p,value,flag) do { \
190 if (value) \
191 (p)->flags |= (flag); \
192 else \
193 (p)->flags &= ~(flag); \
194 } while (0)
195
196#define AST_FLAGS_ALL UINT_MAX
197
198/*! \brief Structure used to handle boolean flags */
199struct ast_flags {
200 unsigned int flags;
201};
202
203/*! \brief Structure used to handle a large number of boolean flags == used only in app_dial? */
205 uint64_t flags;
206};
207
209 struct hostent hp;
210 char buf[1024];
211};
212
213/*!
214 * \brief Thread-safe gethostbyname function to use in Asterisk
215 *
216 * \deprecated Replaced by \c ast_sockaddr_resolve() and \c ast_sockaddr_resolve_first_af()
217 * \note To be removed in Asterisk 23.
218 */
219struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp);
220
221/*! \brief Produces MD5 hash based on input string */
222void ast_md5_hash(char *output, const char *input);
223/*! \brief Produces SHA1 hash based on input string */
224void ast_sha1_hash(char *output, const char *input);
225/*! \brief Produces SHA1 hash based on input string, stored in uint8_t array */
226void ast_sha1_hash_uint(uint8_t *digest, const char *input);
227
228int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks);
229
230#undef MIN
231#define MIN(a, b) ({ typeof(a) __a = (a); typeof(b) __b = (b); ((__a > __b) ? __b : __a);})
232#undef MAX
233#define MAX(a, b) ({ typeof(a) __a = (a); typeof(b) __b = (b); ((__a < __b) ? __b : __a);})
234
235#define SWAP(a,b) do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)
236
237/*!
238 * \brief Encode data in base64
239 * \param dst the destination buffer
240 * \param src the source data to be encoded
241 * \param srclen the number of bytes present in the source buffer
242 * \param max the maximum number of bytes to write into the destination
243 * buffer, *including* the terminating NULL character.
244 */
245int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max);
246
247/*!
248 * \brief Same as ast_base64encode, but does hte math for you and returns
249 * an encoded string
250 *
251 * \note The returned string will need to be freed later
252 *
253 * \param src The source buffer
254 *
255 * \retval NULL on failure
256 * \return Encoded string on success
257 */
258char *ast_base64encode_string(const char *src);
259
260/*!
261 * \brief Decode data from base64
262 * \param dst the destination buffer
263 * \param src the source buffer
264 * \param max The maximum number of bytes to write into the destination
265 * buffer. Note that this function will not ensure that the
266 * destination buffer is NULL terminated. So, in general,
267 * this parameter should be sizeof(dst) - 1.
268 */
269int ast_base64decode(unsigned char *dst, const char *src, int max);
270
271/*!
272 * \brief Same as ast_base64decode, but does the math for you and returns
273 * a decoded string
274 *
275 * \note The returned string will need to be freed later and IS NULL terminated
276 *
277 * \param src The source buffer
278 *
279 * \retval NULL on failure
280 * \return Decoded string on success
281 */
282char *ast_base64decode_string(const char *src);
283
284/*!
285 * \brief Decode data from base64 URL
286 *
287 * \param dst The destination buffer
288 * \param src The source buffer
289 * \param max The maximum number of bytes to write into the destination
290 * buffer. Note that this function will not ensure that the
291 * destination buffer is NULL terminated. So, in general,
292 * this parameter should be sizeof(dst) - 1
293 */
294int ast_base64url_decode(unsigned char *dst, const char *src, int max);
295
296/*!
297 * \brief Same as ast_base64encode_full but for base64 URL
298 *
299 * \param dst The destination buffer
300 * \param src The source buffer
301 * \param srclen The number of bytes present in the source buffer
302 * \param max The maximum number of bytes to write into the destination
303 * buffer, *including* the terminating NULL character.
304 * \param linebreaks Set to 1 if there should be linebreaks inserted
305 * in the result
306 */
307int ast_base64url_encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks);
308
309/*!
310 * \brief Encode data in base64 URL
311 *
312 * \param dst The destination buffer
313 * \param src The source data to be encoded
314 * \param srclen The number of bytes present in the source buffer
315 * \param max The maximum number of bytes to write into the destination
316 * buffer, including the terminating NULL character
317 */
318int ast_base64url_encode(char *dst, const unsigned char *src, int srclen, int max);
319
320/*!
321 * \brief Decode string from base64 URL
322 *
323 * \note The returned string will need to be freed later
324 *
325 * \param src The source buffer
326 *
327 * \retval NULL on failure
328 * \return Decoded string on success
329 */
330char *ast_base64url_decode_string(const char *src);
331
332/*!
333 * \brief Encode string in base64 URL
334 *
335 * \note The returned string will need to be freed later
336 *
337 * \param src The source data to be encoded
338 *
339 * \retval NULL on failure
340 * \return Encoded string on success
341 */
342char *ast_base64url_encode_string(const char *src);
343
344/*!
345 * \brief Performs a base 64 encode algorithm on the contents of a File
346 * \param inputfile A FILE handle to the input file to be encoded. Must be readable. This handle is not automatically closed.
347 * \param outputfile A FILE handle to the output file to receive the base 64 encoded contents of the input file, identified by filename.
348 * \param endl The line ending to use (e.g. either "\n" or "\r\n")
349 *
350 * \return zero on success, -1 on error.
351 */
352int ast_base64_encode_file(FILE *inputfile, FILE *outputfile, const char *endl);
353
354/*!
355 * \brief Performs a base 64 encode algorithm on the contents of a File
356 * \param filename The path to the file to be encoded. Must be readable, file is opened in read mode.
357 * \param outputfile A FILE handle to the output file to receive the base 64 encoded contents of the input file, identified by filename.
358 * \param endl The line ending to use (e.g. either "\n" or "\r\n")
359 *
360 * \return zero on success, -1 on error.
361 */
362int ast_base64_encode_file_path(const char *filename, FILE *outputfile, const char *endl);
363
364#define AST_URI_ALPHANUM (1 << 0)
365#define AST_URI_MARK (1 << 1)
366#define AST_URI_UNRESERVED (AST_URI_ALPHANUM | AST_URI_MARK)
367#define AST_URI_LEGACY_SPACE (1 << 2)
368
369#define AST_URI_SIP_USER_UNRESERVED (1 << 20)
370
371extern const struct ast_flags ast_uri_http;
372extern const struct ast_flags ast_uri_http_legacy;
373extern const struct ast_flags ast_uri_sip_user;
374
375/*!
376 * \brief Turn text string to URI-encoded %XX version
377 *
378 * This function encodes characters according to the rules presented in RFC
379 * 2396 and/or RFC 3261 section 19.1.2 and section 25.1.
380 *
381 * Outbuf needs to have more memory allocated than the instring to have room
382 * for the expansion. Every byte that is converted is replaced by three ASCII
383 * characters.
384 *
385 * \param string string to be converted
386 * \param outbuf resulting encoded string
387 * \param buflen size of output buffer
388 * \param spec flags describing how the encoding should be performed
389 * \return a pointer to the uri encoded string
390 */
391char *ast_uri_encode(const char *string, char *outbuf, int buflen, struct ast_flags spec);
392
393/*!
394 * \brief Decode URI, URN, URL (overwrite string)
395 *
396 * \note The ast_uri_http_legacy decode spec flag will cause this function to
397 * decode '+' as ' '.
398 *
399 * \param s string to be decoded
400 * \param spec flags describing how the decoding should be performed
401 */
402void ast_uri_decode(char *s, struct ast_flags spec);
403
404/*! ast_xml_escape
405 \brief Escape reserved characters for use in XML.
406
407 If \a outbuf is too short, the output string will be truncated.
408 Regardless, the output will always be null terminated.
409
410 \param string String to be converted
411 \param outbuf Resulting encoded string
412 \param buflen Size of output buffer
413 \retval 0 for success
414 \retval -1 if buflen is too short.
415 */
416int ast_xml_escape(const char *string, char *outbuf, size_t buflen);
417
418/*!
419 * \brief Escape characters found in a quoted string.
420 *
421 * \note This function escapes quoted characters based on the 'qdtext' set of
422 * allowed characters from RFC 3261 section 25.1.
423 *
424 * \param string string to be escaped
425 * \param outbuf resulting escaped string
426 * \param buflen size of output buffer
427 * \return a pointer to the escaped string
428 */
429char *ast_escape_quoted(const char *string, char *outbuf, int buflen);
430
431/*!
432 * \brief Escape semicolons found in a string.
433 *
434 * \param string string to be escaped
435 * \param outbuf resulting escaped string
436 * \param buflen size of output buffer
437 * \return a pointer to the escaped string
438 */
439char *ast_escape_semicolons(const char *string, char *outbuf, int buflen);
440
441/*!
442 * \brief Unescape quotes in a string
443 *
444 * \param quote_str The string with quotes to be unescaped
445 *
446 * \note This function mutates the passed-in string.
447 */
448void ast_unescape_quoted(char *quote_str);
449
451{
452 int res;
453
454 res = (int) *input + *value;
455 if (res > 32767)
456 *input = 32767;
457 else if (res < -32768)
458 *input = -32768;
459 else
460 *input = (short) res;
461}
462
464{
465 int res;
466
467 res = (int) *input - *value;
468 if (res > 32767)
469 *input = 32767;
470 else if (res < -32768)
471 *input = -32768;
472 else
473 *input = (short) res;
474}
475
477{
478 int res;
479
480 res = (int) *input * *value;
481 if (res > 32767)
482 *input = 32767;
483 else if (res < -32768)
484 *input = -32768;
485 else
486 *input = (short) res;
487}
488
490{
491 float res;
492
493 res = (float) *input * *value;
494 if (res > 32767)
495 *input = 32767;
496 else if (res < -32768)
497 *input = -32768;
498 else
499 *input = (short) res;
500}
501
503{
504 *input /= *value;
505}
506
508{
509 float res = (float) *input / *value;
510 if (res > 32767)
511 *input = 32767;
512 else if (res < -32768)
513 *input = -32768;
514 else
515 *input = (short) res;
516}
517
518#ifdef localtime_r
519#undef localtime_r
520#endif
521#define localtime_r __dont_use_localtime_r_use_ast_localtime_instead__
522
523int ast_utils_init(void);
524int ast_wait_for_input(int fd, int ms);
525int ast_wait_for_output(int fd, int ms);
526
527/*!
528 * \brief Try to write string, but wait no more than ms milliseconds
529 * before timing out.
530 *
531 * \note If you are calling ast_carefulwrite, it is assumed that you are calling
532 * it on a file descriptor that _DOES_ have NONBLOCK set. This way,
533 * there is only one system call made to do a write, unless we actually
534 * have a need to wait. This way, we get better performance.
535 */
536int ast_carefulwrite(int fd, char *s, int len, int timeoutms);
537
538/*!
539 * \brief Write data to a file stream with a timeout
540 *
541 * \param f the file stream to write to
542 * \param fd the file description to poll on to know when the file stream can
543 * be written to without blocking.
544 * \param s the buffer to write from
545 * \param len the number of bytes to write
546 * \param timeoutms The maximum amount of time to block in this function trying
547 * to write, specified in milliseconds.
548 *
549 * \note This function assumes that the associated file stream has been set up
550 * as non-blocking.
551 *
552 * \retval 0 success
553 * \retval -1 error
554 */
555int ast_careful_fwrite(FILE *f, int fd, const char *s, size_t len, int timeoutms);
556
557/*
558 * Thread management support (should be moved to lock.h or a different header)
559 */
560
561#if defined(PTHREAD_STACK_MIN)
562# define AST_STACKSIZE MAX((((sizeof(void *) * 8 * 8) - 16) * 1024), PTHREAD_STACK_MIN)
563# define AST_STACKSIZE_LOW MAX((((sizeof(void *) * 8 * 2) - 16) * 1024), PTHREAD_STACK_MIN)
564#else
565# define AST_STACKSIZE (((sizeof(void *) * 8 * 8) - 16) * 1024)
566# define AST_STACKSIZE_LOW (((sizeof(void *) * 8 * 2) - 16) * 1024)
567#endif
568
570
571#define AST_BACKGROUND_STACKSIZE ast_background_stacksize()
572
573void ast_register_thread(char *name);
574void ast_unregister_thread(void *id);
575
576int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
577 void *data, size_t stacksize, const char *file, const char *caller,
578 int line, const char *start_fn);
579
580int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void*(*start_routine)(void *),
581 void *data, size_t stacksize, const char *file, const char *caller,
582 int line, const char *start_fn);
583
584#define ast_pthread_create(a, b, c, d) \
585 ast_pthread_create_stack(a, b, c, d, \
586 0, __FILE__, __FUNCTION__, __LINE__, #c)
587
588#define ast_pthread_create_detached(a, b, c, d) \
589 ast_pthread_create_detached_stack(a, b, c, d, \
590 0, __FILE__, __FUNCTION__, __LINE__, #c)
591
592#define ast_pthread_create_background(a, b, c, d) \
593 ast_pthread_create_stack(a, b, c, d, \
594 AST_BACKGROUND_STACKSIZE, \
595 __FILE__, __FUNCTION__, __LINE__, #c)
596
597#define ast_pthread_create_detached_background(a, b, c, d) \
598 ast_pthread_create_detached_stack(a, b, c, d, \
599 AST_BACKGROUND_STACKSIZE, \
600 __FILE__, __FUNCTION__, __LINE__, #c)
601
602/* End of thread management support */
603
604/*!
605 * \brief Replace '^' in a string with ','
606 * \param s String within which to replace characters
607 */
609
610/*!
611 * \brief Process a string to find and replace characters
612 * \param start The string to analyze
613 * \param find The character to find
614 * \param replace_with The character that will replace the one we are looking for
615 */
616char *ast_process_quotes_and_slashes(char *start, char find, char replace_with);
617
618long int ast_random(void);
619
620/*!
621 * \brief Returns a random number between 0.0 and 1.0, inclusive.
622 * \since 12
623 */
624#define ast_random_double() (((double)ast_random()) / RAND_MAX)
625
626/*!
627 * \brief Disable PMTU discovery on a socket
628 * \param sock The socket to manipulate
629 *
630 * On Linux, UDP sockets default to sending packets with the Dont Fragment (DF)
631 * bit set. This is supposedly done to allow the application to do PMTU
632 * discovery, but Asterisk does not do this.
633 *
634 * Because of this, UDP packets sent by Asterisk that are larger than the MTU
635 * of any hop in the path will be lost. This function can be called on a socket
636 * to ensure that the DF bit will not be set.
637 */
639
640/*!
641 * \brief Recursively create directory path
642 * \param path The directory path to create
643 * \param mode The permissions with which to try to create the directory
644 * \retval 0 on success
645 * \return error code otherwise
646 *
647 * Creates a directory path, creating parent directories as needed.
648 */
649int ast_mkdir(const char *path, int mode);
650
651/*!
652 * \brief Recursively create directory path, but only if it resolves within
653 * the given \a base_path.
654 *
655 * If \a base_path does not exist, it will not be created and this function
656 * returns \c EPERM.
657 *
658 * \param base_path
659 * \param path The directory path to create
660 * \param mode The permissions with which to try to create the directory
661 * \retval 0 on success
662 * \return an error code otherwise
663 */
664int ast_safe_mkdir(const char *base_path, const char *path, int mode);
665
666#define ARRAY_LEN(a) (size_t) (sizeof(a) / sizeof(0[a]))
667
668/*!
669 * \brief Checks to see if value is within the given bounds
670 *
671 * \param v the value to check
672 * \param min minimum lower bound (inclusive)
673 * \param max maximum upper bound (inclusive)
674 * \retval 0 if value out of bounds
675 * \retval non-zero otherwise
676 */
677#define IN_BOUNDS(v, min, max) ((v) >= (min)) && ((v) <= (max))
678
679/*!
680 * \brief Checks to see if value is within the bounds of the given array
681 *
682 * \param v the value to check
683 * \param a the array to bound check
684 * \retval 0 if value out of bounds
685 * \retval non-zero otherwise
686 */
687#define ARRAY_IN_BOUNDS(v, a) IN_BOUNDS((int) (v), 0, ARRAY_LEN(a) - 1)
688
689/* Definition for Digest authorization */
701 );
702 int qop; /* Flag set to 1, if we send/recv qop="quth" */
703};
704
705/*!
706 * \brief Parse digest authorization header.
707 * \return -1 if we have no auth or something wrong with digest.
708 * \note This function may be used for Digest request and responce header.
709 * request arg is set to nonzero, if we parse Digest Request.
710 * pedantic arg can be set to nonzero if we need to do addition Digest check.
711 */
712int ast_parse_digest(const char *digest, struct ast_http_digest *d, int request, int pedantic);
713
714#ifdef DO_CRASH
715#define DO_CRASH_NORETURN attribute_noreturn
716#else
717#define DO_CRASH_NORETURN
718#endif
719
720void DO_CRASH_NORETURN __ast_assert_failed(int condition, const char *condition_str,
721 const char *file, int line, const char *function);
722
723#ifdef AST_DEVMODE
724#define ast_assert(a) _ast_assert(a, # a, __FILE__, __LINE__, __PRETTY_FUNCTION__)
725#define ast_assert_return(a, ...) \
726({ \
727 if (__builtin_expect(!(a), 1)) { \
728 _ast_assert(0, # a, __FILE__, __LINE__, __PRETTY_FUNCTION__); \
729 return __VA_ARGS__; \
730 }\
731})
732static void force_inline _ast_assert(int condition, const char *condition_str, const char *file, int line, const char *function)
733{
734 if (__builtin_expect(!condition, 1)) {
735 __ast_assert_failed(condition, condition_str, file, line, function);
736 }
737}
738#else
739#define ast_assert(a)
740#define ast_assert_return(a, ...) \
741({ \
742 if (__builtin_expect(!(a), 1)) { \
743 return __VA_ARGS__; \
744 }\
745})
746#endif
747
748/*!
749 * \brief Force a crash if DO_CRASH is defined.
750 *
751 * \note If DO_CRASH is not defined then the function returns.
752 */
754
755#include "asterisk/strings.h"
756
757/*!
758 * \brief Return the number of bytes used in the alignment of type.
759 * \param type
760 * \return The number of bytes required for alignment.
761 *
762 * This is really just __alignof__(), but tucked away in this header so we
763 * don't have to look at the nasty underscores in the source.
764 */
765#define ast_alignof(type) __alignof__(type)
766
767/*!
768 * \brief Increase offset so it is a multiple of the required alignment of type.
769 * \param offset The value that should be increased.
770 * \param type The data type that offset should be aligned to.
771 * \return The smallest multiple of alignof(type) larger than or equal to offset.
772 * \see ast_make_room_for()
773 *
774 * Many systems prefer integers to be stored on aligned on memory locations.
775 * This macro will increase an offset so a value of the supplied type can be
776 * safely be stored on such a memory location.
777 *
778 * Examples:
779 * ast_align_for(0x17, int64_t) ==> 0x18
780 * ast_align_for(0x18, int64_t) ==> 0x18
781 * ast_align_for(0x19, int64_t) ==> 0x20
782 *
783 * Don't mind the ugliness, the compiler will optimize it.
784 */
785#define ast_align_for(offset, type) (((offset + __alignof__(type) - 1) / __alignof__(type)) * __alignof__(type))
786
787/*!
788 * \brief Increase offset by the required alignment of type and make sure it is
789 * a multiple of said alignment.
790 * \param offset The value that should be increased.
791 * \param type The data type that room should be reserved for.
792 * \return The smallest multiple of alignof(type) larger than or equal to offset
793 * plus alignof(type).
794 * \see ast_align_for()
795 *
796 * A use case for this is when prepending length fields of type int to a buffer.
797 * If you keep the offset a multiple of the alignment of the integer type,
798 * a next block of length+buffer will have the length field automatically
799 * aligned.
800 *
801 * Examples:
802 * ast_make_room_for(0x17, int64_t) ==> 0x20
803 * ast_make_room_for(0x18, int64_t) ==> 0x20
804 * ast_make_room_for(0x19, int64_t) ==> 0x28
805 *
806 * Don't mind the ugliness, the compiler will optimize it.
807 */
808#define ast_make_room_for(offset, type) (((offset + (2 * __alignof__(type) - 1)) / __alignof__(type)) * __alignof__(type))
809
810/*!
811 * \brief An Entity ID is essentially a MAC address, brief and unique
812 */
813struct ast_eid {
814 unsigned char eid[6];
815} __attribute__((__packed__));
816
817/*!
818 * \brief Global EID
819 *
820 * This is set in asterisk.conf, or determined automatically by taking the mac
821 * address of an Ethernet interface on the system.
822 */
823extern struct ast_eid ast_eid_default;
824
825/*!
826 * \brief Fill in an ast_eid with the default eid of this machine
827 * \since 1.6.1
828 */
829void ast_set_default_eid(struct ast_eid *eid);
830
831/*!
832 * \brief Convert an EID to a string
833 * \since 1.6.1
834 */
835char *ast_eid_to_str(char *s, int maxlen, struct ast_eid *eid);
836
837/*!
838 * \brief Convert a string into an EID
839 *
840 * This function expects an EID in the format:
841 * 00:11:22:33:44:55
842 *
843 * \retval 0 success
844 * \retval non-zero failure
845 * \since 1.6.1
846 */
847int ast_str_to_eid(struct ast_eid *eid, const char *s);
848
849/*!
850 * \brief Compare two EIDs
851 *
852 * \retval 0 if the two are the same
853 * \retval non-zero otherwise
854 * \since 1.6.1
855 */
856int ast_eid_cmp(const struct ast_eid *eid1, const struct ast_eid *eid2);
857
858/*!
859 * \brief Check if EID is empty
860 *
861 * \retval 1 if the EID is empty
862 * \retval 0 otherwise
863 * \since 13.12.0
864 */
865int ast_eid_is_empty(const struct ast_eid *eid);
866
867/*!
868 * \brief Get current thread ID
869 * \return the ID if platform is supported, else -1
870 */
871int ast_get_tid(void);
872
873/*!
874 * \brief Resolve a binary to a full pathname
875 * \param binary Name of the executable to resolve
876 * \param fullpath Buffer to hold the complete pathname
877 * \param fullpath_size Size of \a fullpath
878 * \retval NULL \a binary was not found or the environment variable PATH is not set
879 * \return \a fullpath
880 */
881char *ast_utils_which(const char *binary, char *fullpath, size_t fullpath_size);
882
883/*!
884 * \brief Declare a variable that will call a destructor function when it goes out of scope.
885 *
886 * Resource Allocation Is Initialization (RAII) variable declaration.
887 *
888 * \since 11.0
889 * \param vartype The type of the variable
890 * \param varname The name of the variable
891 * \param initval The initial value of the variable
892 * \param dtor The destructor function of type' void func(vartype *)'
893 *
894 * \code
895 * void mything_cleanup(struct mything *t)
896 * {
897 * if (t) {
898 * ast_free(t->stuff);
899 * }
900 * }
901 *
902 * void do_stuff(const char *name)
903 * {
904 * RAII_VAR(struct mything *, thing, mything_alloc(name), mything_cleanup);
905 * ...
906 * }
907 * \endcode
908 *
909 * \note This macro is especially useful for working with ao2 objects. A common idiom
910 * would be a function that needed to look up an ao2 object and might have several error
911 * conditions after the allocation that would normally need to unref the ao2 object.
912 * With RAII_VAR, it is possible to just return and leave the cleanup to the destructor
913 * function. For example:
914 *
915 * \code
916 * void do_stuff(const char *name)
917 * {
918 * RAII_VAR(struct mything *, thing, find_mything(name), ao2_cleanup);
919 * if (!thing) {
920 * return;
921 * }
922 * if (error) {
923 * return;
924 * }
925 * do_stuff_with_thing(thing);
926 * }
927 * \endcode
928 */
929
930#if defined(__clang__)
931typedef void (^_raii_cleanup_block_t)(void);
932static inline void _raii_cleanup_block(_raii_cleanup_block_t *b) { (*b)(); }
933
934#define RAII_VAR(vartype, varname, initval, dtor) \
935 __block vartype varname = initval; \
936 _raii_cleanup_block_t _raii_cleanup_ ## varname __attribute__((cleanup(_raii_cleanup_block),unused)) = \
937 ^{ {(void)dtor(varname);} };
938
939#elif defined(__GNUC__)
940
941#define RAII_VAR(vartype, varname, initval, dtor) \
942 auto void _dtor_ ## varname (vartype * v); \
943 void _dtor_ ## varname (vartype * v) { dtor(*v); } \
944 vartype varname __attribute__((cleanup(_dtor_ ## varname))) = (initval)
945
946#else
947 #error "Cannot compile Asterisk: unknown and unsupported compiler."
948#endif /* #if __GNUC__ */
949
950/*!
951 * \brief Asterisk wrapper around crypt(3).
952 *
953 * The interpretation of the salt (which determines the password hashing
954 * algorithm) is system specific. Application code should prefer to use
955 * ast_crypt_encrypt() or ast_crypt_validate().
956 *
957 * The returned string is heap allocated, and should be freed with ast_free().
958 *
959 * \param key User's password to crypt.
960 * \param salt Salt to crypt with.
961 * \return Crypted password.
962 * \retval NULL on error.
963 */
964char *ast_crypt(const char *key, const char *salt);
965
966/*!
967 * \brief Asterisk wrapper around crypt(3) for encrypting passwords.
968 *
969 * This function will generate a random salt and encrypt the given password.
970 *
971 * The returned string is heap allocated, and should be freed with ast_free().
972 *
973 * \param key User's password to crypt.
974 * \return Crypted password.
975 * \retval NULL on error.
976 */
977char *ast_crypt_encrypt(const char *key);
978
979/*!
980 * \brief Asterisk wrapper around crypt(3) for validating passwords.
981 *
982 * \param key User's password to validate.
983 * \param expected Expected result from crypt.
984 * \retval True (non-zero) if \a key matches \a expected.
985 * \retval False (zero) if \a key doesn't match.
986 */
987int ast_crypt_validate(const char *key, const char *expected);
988
989/*!
990 * \brief Test that a file exists and is readable by the effective user.
991 * \since 13.7.0
992 *
993 * \param filename File to test.
994 * \retval True (non-zero) if the file exists and is readable.
995 * \retval False (zero) if the file either doesn't exists or is not readable.
996 */
997int ast_file_is_readable(const char *filename);
998
999/*!
1000 * \brief Compare 2 major.minor.patch.extra version strings.
1001 * \since 13.7.0
1002 *
1003 * \param version1
1004 * \param version2
1005 *
1006 * \retval negative if version 1 < version 2.
1007 * \retval 0 if version 1 = version 2.
1008 * \retval positive if version 1 > version 2.
1009 */
1010int ast_compare_versions(const char *version1, const char *version2);
1011
1012/*!
1013 * \brief Test that an OS supports IPv6 Networking.
1014 * \since 13.14.0
1015 *
1016 * \retval True (non-zero) if the IPv6 supported.
1017 * \retval False (zero) if the OS doesn't support IPv6.
1018 */
1019int ast_check_ipv6(void);
1020
1024};
1025
1026/*!
1027 * \brief Set flags on the given file descriptor
1028 * \since 13.19
1029 *
1030 * If getting or setting flags of the given file descriptor fails, logs an
1031 * error message.
1032 *
1033 * \param fd File descriptor to set flags on
1034 * \param flags The flag(s) to set
1035 *
1036 * \retval -1 on error
1037 * \retval 0 if successful
1038 */
1039#define ast_fd_set_flags(fd, flags) \
1040 __ast_fd_set_flags((fd), (flags), AST_FD_FLAG_SET, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1041
1042/*!
1043 * \brief Clear flags on the given file descriptor
1044 * \since 13.19
1045 *
1046 * If getting or setting flags of the given file descriptor fails, logs an
1047 * error message.
1048 *
1049 * \param fd File descriptor to clear flags on
1050 * \param flags The flag(s) to clear
1051 *
1052 * \retval -1 on error
1053 * \retval 0 if successful
1054 */
1055#define ast_fd_clear_flags(fd, flags) \
1056 __ast_fd_set_flags((fd), (flags), AST_FD_FLAG_CLEAR, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1057
1058int __ast_fd_set_flags(int fd, int flags, enum ast_fd_flag_operation op,
1059 const char *file, int lineno, const char *function);
1060
1061/*!
1062 * \brief Create a non-blocking socket
1063 * \since 13.25
1064 *
1065 * Wrapper around socket(2) that sets the O_NONBLOCK flag on the resulting
1066 * socket.
1067 *
1068 * \details
1069 * For parameter and return information, see the man page for
1070 * socket(2).
1071 */
1072#ifdef HAVE_SOCK_NONBLOCK
1073# define ast_socket_nonblock(domain, type, protocol) socket((domain), (type) | SOCK_NONBLOCK, (protocol))
1074#else
1075int ast_socket_nonblock(int domain, int type, int protocol);
1076#endif
1077
1078/*!
1079 * \brief Create a non-blocking pipe
1080 * \since 13.25
1081 *
1082 * Wrapper around pipe(2) that sets the O_NONBLOCK flag on the resulting
1083 * file descriptors.
1084 *
1085 * \details
1086 * For parameter and return information, see the man page for
1087 * pipe(2).
1088 */
1089#ifdef HAVE_PIPE2
1090# define ast_pipe_nonblock(filedes) pipe2((filedes), O_NONBLOCK)
1091#else
1092int ast_pipe_nonblock(int filedes[2]);
1093#endif
1094
1095/*!
1096 * \brief Set the current thread's user interface status.
1097 *
1098 * \param is_user_interface Non-zero to mark the thread as a user interface.
1099 *
1100 * \retval True (non-zero) if marking current thread failed.
1101 * \retval False (zero) if successfuly marked current thread.
1102 */
1103int ast_thread_user_interface_set(int is_user_interface);
1104
1105/*!
1106 * \brief Indicates whether the current thread is a user interface
1107 *
1108 * \retval True (non-zero) if thread is a user interface.
1109 * \retval False (zero) if thread is not a user interface.
1110 */
1112
1113/*!
1114 * \brief Test for the presence of an executable command in $PATH
1115 *
1116 * \param cmd Name of command to locate.
1117 *
1118 * \retval True (non-zero) if command is in $PATH.
1119 * \retval False (zero) command not found.
1120 */
1121int ast_check_command_in_path(const char *cmd);
1122
1123#endif /* _ASTERISK_UTILS_H */
pthread_t thread
Definition: app_sla.c:329
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1570
static const char type[]
Definition: chan_ooh323.c:109
static int request(void *obj)
Definition: chan_pjsip.c:2601
#define force_inline
Definition: compiler.h:29
#define max(a, b)
Definition: f2c.h:198
static const char name[]
Definition: format_mp3.c:68
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
Support for logging to various files, console and syslog Configuration in file logger....
Custom localtime functions for multiple timezones.
Asterisk locking-related definitions:
Wrapper for network related headers, masking differences between various operating systems....
#define AST_DECLARE_STRING_FIELDS(field_list)
Declare the fields needed in a structure.
Definition: stringfields.h:341
#define AST_STRING_FIELD(name)
Declare a string field.
Definition: stringfields.h:303
String manipulation functions.
An Entity ID is essentially a MAC address, brief and unique.
Definition: utils.h:813
unsigned char eid[6]
Definition: utils.h:814
Structure used to handle a large number of boolean flags == used only in app_dial?
Definition: utils.h:204
uint64_t flags
Definition: utils.h:205
Structure used to handle boolean flags.
Definition: utils.h:199
unsigned int flags
Definition: utils.h:200
char buf[1024]
Definition: utils.h:210
struct hostent hp
Definition: utils.h:209
const ast_string_field response
Definition: utils.h:701
const ast_string_field uri
Definition: utils.h:701
const ast_string_field domain
Definition: utils.h:701
const ast_string_field opaque
Definition: utils.h:701
const ast_string_field cnonce
Definition: utils.h:701
const ast_string_field nonce
Definition: utils.h:701
const ast_string_field username
Definition: utils.h:701
const ast_string_field realm
Definition: utils.h:701
const ast_string_field nc
Definition: utils.h:701
int value
Definition: syslog.c:37
static struct test_val b
static struct test_val d
Time-related functions and macros.
int ast_thread_is_user_interface(void)
Indicates whether the current thread is a user interface.
Definition: utils.c:3248
void ast_unescape_quoted(char *quote_str)
Unescape quotes in a string.
Definition: utils.c:842
static force_inline void ast_slinear_saturated_divide_float(short *input, float *value)
Definition: utils.h:507
static force_inline void ast_slinear_saturated_subtract(short *input, short *value)
Definition: utils.h:463
int ast_base64url_encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
Same as ast_base64encode_full but for base64 URL.
Definition: utils.c:471
int ast_base64_encode_file(FILE *inputfile, FILE *outputfile, const char *endl)
Performs a base 64 encode algorithm on the contents of a File.
Definition: utils.c:648
int ast_base64decode(unsigned char *dst, const char *src, int max)
Decode data from base64.
Definition: utils.c:296
int ast_check_command_in_path(const char *cmd)
Test for the presence of an executable command in $PATH.
Definition: utils.c:3263
int ast_safe_mkdir(const char *base_path, const char *path, int mode)
Recursively create directory path, but only if it resolves within the given base_path.
Definition: utils.c:2584
unsigned int __unsigned_int_flags_dummy
char * ast_base64url_encode_string(const char *src)
Encode string in base64 URL.
Definition: utils.c:523
int ast_file_is_readable(const char *filename)
Test that a file exists and is readable by the effective user.
Definition: utils.c:3107
int ast_carefulwrite(int fd, char *s, int len, int timeoutms)
Try to write string, but wait no more than ms milliseconds before timing out.
Definition: utils.c:1771
#define DO_CRASH_NORETURN
Definition: utils.h:717
ast_fd_flag_operation
Definition: utils.h:1021
@ AST_FD_FLAG_SET
Definition: utils.h:1022
@ AST_FD_FLAG_CLEAR
Definition: utils.h:1023
int __ast_fd_set_flags(int fd, int flags, enum ast_fd_flag_operation op, const char *file, int lineno, const char *function)
Definition: utils.c:3150
int ast_background_stacksize(void)
Definition: utils.c:1616
static force_inline void ast_slinear_saturated_multiply_float(short *input, float *value)
Definition: utils.h:489
char * ast_utils_which(const char *binary, char *fullpath, size_t fullpath_size)
Resolve a binary to a full pathname.
Definition: utils.c:2774
char * ast_uri_encode(const char *string, char *outbuf, int buflen, struct ast_flags spec)
Turn text string to URI-encoded XX version.
Definition: utils.c:723
#define ast_socket_nonblock(domain, type, protocol)
Create a non-blocking socket.
Definition: utils.h:1073
void ast_set_default_eid(struct ast_eid *eid)
Fill in an ast_eid with the default eid of this machine.
Definition: utils.c:3001
int ast_thread_user_interface_set(int is_user_interface)
Set the current thread's user interface status.
Definition: utils.c:3233
int ast_eid_cmp(const struct ast_eid *eid1, const struct ast_eid *eid2)
Compare two EIDs.
Definition: utils.c:3094
char * ast_escape_quoted(const char *string, char *outbuf, int buflen)
Escape characters found in a quoted string.
Definition: utils.c:781
int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
Encode data in base64.
Definition: utils.c:406
static force_inline void ast_slinear_saturated_multiply(short *input, short *value)
Definition: utils.h:476
int ast_wait_for_input(int fd, int ms)
Definition: utils.c:1698
int ast_parse_digest(const char *digest, struct ast_http_digest *d, int request, int pedantic)
Parse digest authorization header.
Definition: utils.c:2638
char * ast_base64decode_string(const char *src)
Same as ast_base64decode, but does the math for you and returns a decoded string.
Definition: utils.c:323
int ast_crypt_validate(const char *key, const char *expected)
Asterisk wrapper around crypt(3) for validating passwords.
Definition: crypt.c:136
char * ast_eid_to_str(char *s, int maxlen, struct ast_eid *eid)
Convert an EID to a string.
Definition: utils.c:2839
char * ast_base64encode_string(const char *src)
Same as ast_base64encode, but does hte math for you and returns an encoded string.
Definition: utils.c:412
uint64_t __unsigned_int_flags_dummy64
int ast_get_tid(void)
Get current thread ID.
Definition: utils.c:2752
long int ast_random(void)
Definition: utils.c:2312
int ast_mkdir(const char *path, int mode)
Recursively create directory path.
Definition: utils.c:2479
const struct ast_flags ast_uri_http
Definition: utils.c:719
int ast_utils_init(void)
Definition: utils.c:2617
int ast_wait_for_output(int fd, int ms)
Definition: utils.c:1708
char * ast_crypt(const char *key, const char *salt)
Asterisk wrapper around crypt(3).
Definition: crypt.c:121
static force_inline void ast_slinear_saturated_add(short *input, short *value)
Definition: utils.h:450
void ast_enable_packet_fragmentation(int sock)
Disable PMTU discovery on a socket.
Definition: utils.c:2469
int ast_xml_escape(const char *string, char *outbuf, size_t buflen)
Escape reserved characters for use in XML.
Definition: utils.c:864
int ast_base64url_decode(unsigned char *dst, const char *src, int max)
Decode data from base64 URL.
Definition: utils.c:429
int ast_compare_versions(const char *version1, const char *version2)
Compare 2 major.minor.patch.extra version strings.
Definition: utils.c:3124
void ast_register_thread(char *name)
Definition: asterisk.c:414
int ast_eid_is_empty(const struct ast_eid *eid)
Check if EID is empty.
Definition: utils.c:3099
int ast_base64url_encode(char *dst, const unsigned char *src, int srclen, int max)
Encode data in base64 URL.
Definition: utils.c:518
void ast_unregister_thread(void *id)
Definition: asterisk.c:430
void DO_CRASH_NORETURN ast_do_crash(void)
Force a crash if DO_CRASH is defined.
Definition: utils.c:2804
char * ast_process_quotes_and_slashes(char *start, char find, char replace_with)
Process a string to find and replace characters.
Definition: utils.c:2352
#define ast_pipe_nonblock(filedes)
Create a non-blocking pipe.
Definition: utils.h:1090
char * ast_escape_semicolons(const char *string, char *outbuf, int buflen)
Escape semicolons found in a string.
Definition: utils.c:811
int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
encode text to BASE64 coding
Definition: utils.c:355
void ast_sha1_hash_uint(uint8_t *digest, const char *input)
Produces SHA1 hash based on input string, stored in uint8_t array.
Definition: utils.c:284
int ast_careful_fwrite(FILE *f, int fd, const char *s, size_t len, int timeoutms)
Write data to a file stream with a timeout.
int ast_check_ipv6(void)
Test that an OS supports IPv6 Networking.
Definition: utils.c:2792
char * ast_base64url_decode_string(const char *src)
Decode string from base64 URL.
Definition: utils.c:450
struct ast_eid ast_eid_default
Global EID.
Definition: options.c:93
int ast_str_to_eid(struct ast_eid *eid, const char *s)
Convert a string into an EID.
Definition: utils.c:3077
void ast_uri_decode(char *s, struct ast_flags spec)
Decode URI, URN, URL (overwrite string)
Definition: utils.c:762
int ast_base64_encode_file_path(const char *filename, FILE *outputfile, const char *endl)
Performs a base 64 encode algorithm on the contents of a File.
Definition: utils.c:702
struct hostent * ast_gethostbyname(const char *host, struct ast_hostent *hp)
Thread-safe gethostbyname function to use in Asterisk.
Definition: utils.c:199
void ast_replace_subargument_delimiter(char *s)
Replace '^' in a string with ','.
Definition: utils.c:2343
void DO_CRASH_NORETURN __ast_assert_failed(int condition, const char *condition_str, const char *file, int line, const char *function)
Definition: utils.c:2816
const struct ast_flags ast_uri_sip_user
Definition: utils.c:721
void ast_md5_hash(char *output, const char *input)
Produces MD5 hash based on input string.
Definition: utils.c:250
int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
Definition: utils.c:1673
void ast_sha1_hash(char *output, const char *input)
Produces SHA1 hash based on input string.
Definition: utils.c:266
static force_inline void ast_slinear_saturated_divide(short *input, short *value)
Definition: utils.h:502
int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
Definition: utils.c:1625
const struct ast_flags ast_uri_http_legacy
Definition: utils.c:720
char * ast_crypt_encrypt(const char *key)
Asterisk wrapper around crypt(3) for encrypting passwords.
Definition: crypt.c:190