Asterisk - The Open Source Telephony Project GIT-master-009e3ef
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros Modules Pages
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 if (res > 0)
499 *input = (short) (res + 0.5);
500 else
501 *input = (short) (res - 0.5);
502
503}
504
506{
507 *input /= *value;
508}
509
511{
512 float res = (float) *input / *value;
513 if (res > 32767)
514 *input = 32767;
515 else if (res < -32768)
516 *input = -32768;
517 else if (res > 0)
518 *input = (short) (res + 0.5);
519 else
520 *input = (short) (res - 0.5);
521
522}
523
524#ifdef localtime_r
525#undef localtime_r
526#endif
527#define localtime_r __dont_use_localtime_r_use_ast_localtime_instead__
528
529int ast_utils_init(void);
530int ast_wait_for_input(int fd, int ms);
531int ast_wait_for_output(int fd, int ms);
532
533/*!
534 * \brief Try to write string, but wait no more than ms milliseconds
535 * before timing out.
536 *
537 * \note If you are calling ast_carefulwrite, it is assumed that you are calling
538 * it on a file descriptor that _DOES_ have NONBLOCK set. This way,
539 * there is only one system call made to do a write, unless we actually
540 * have a need to wait. This way, we get better performance.
541 */
542int ast_carefulwrite(int fd, char *s, int len, int timeoutms);
543
544/*!
545 * \brief Write data to a file stream with a timeout
546 *
547 * \param f the file stream to write to
548 * \param fd the file description to poll on to know when the file stream can
549 * be written to without blocking.
550 * \param s the buffer to write from
551 * \param len the number of bytes to write
552 * \param timeoutms The maximum amount of time to block in this function trying
553 * to write, specified in milliseconds.
554 *
555 * \note This function assumes that the associated file stream has been set up
556 * as non-blocking.
557 *
558 * \retval 0 success
559 * \retval -1 error
560 */
561int ast_careful_fwrite(FILE *f, int fd, const char *s, size_t len, int timeoutms);
562
563/*
564 * Thread management support (should be moved to lock.h or a different header)
565 */
566
567#if defined(PTHREAD_STACK_MIN)
568# define AST_STACKSIZE MAX((((sizeof(void *) * 8 * 8) - 16) * 1024), PTHREAD_STACK_MIN)
569# define AST_STACKSIZE_LOW MAX((((sizeof(void *) * 8 * 2) - 16) * 1024), PTHREAD_STACK_MIN)
570#else
571# define AST_STACKSIZE (((sizeof(void *) * 8 * 8) - 16) * 1024)
572# define AST_STACKSIZE_LOW (((sizeof(void *) * 8 * 2) - 16) * 1024)
573#endif
574
576
577#define AST_BACKGROUND_STACKSIZE ast_background_stacksize()
578
579void ast_register_thread(char *name);
580void ast_unregister_thread(void *id);
581
582int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
583 void *data, size_t stacksize, const char *file, const char *caller,
584 int line, const char *start_fn);
585
586int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void*(*start_routine)(void *),
587 void *data, size_t stacksize, const char *file, const char *caller,
588 int line, const char *start_fn);
589
590#define ast_pthread_create(a, b, c, d) \
591 ast_pthread_create_stack(a, b, c, d, \
592 0, __FILE__, __FUNCTION__, __LINE__, #c)
593
594#define ast_pthread_create_detached(a, b, c, d) \
595 ast_pthread_create_detached_stack(a, b, c, d, \
596 0, __FILE__, __FUNCTION__, __LINE__, #c)
597
598#define ast_pthread_create_background(a, b, c, d) \
599 ast_pthread_create_stack(a, b, c, d, \
600 AST_BACKGROUND_STACKSIZE, \
601 __FILE__, __FUNCTION__, __LINE__, #c)
602
603#define ast_pthread_create_detached_background(a, b, c, d) \
604 ast_pthread_create_detached_stack(a, b, c, d, \
605 AST_BACKGROUND_STACKSIZE, \
606 __FILE__, __FUNCTION__, __LINE__, #c)
607
608/* End of thread management support */
609
610/*!
611 * \brief Replace '^' in a string with ','
612 * \param s String within which to replace characters
613 */
615
616/*!
617 * \brief Process a string to find and replace characters
618 * \param start The string to analyze
619 * \param find The character to find
620 * \param replace_with The character that will replace the one we are looking for
621 */
622char *ast_process_quotes_and_slashes(char *start, char find, char replace_with);
623
624long int ast_random(void);
625
626/*!
627 * \brief Returns a random number between 0.0 and 1.0, inclusive.
628 * \since 12
629 */
630#define ast_random_double() (((double)ast_random()) / RAND_MAX)
631
632/*!
633 * \brief Disable PMTU discovery on a socket
634 * \param sock The socket to manipulate
635 *
636 * On Linux, UDP sockets default to sending packets with the Dont Fragment (DF)
637 * bit set. This is supposedly done to allow the application to do PMTU
638 * discovery, but Asterisk does not do this.
639 *
640 * Because of this, UDP packets sent by Asterisk that are larger than the MTU
641 * of any hop in the path will be lost. This function can be called on a socket
642 * to ensure that the DF bit will not be set.
643 */
645
646/*!
647 * \brief Recursively create directory path
648 * \param path The directory path to create
649 * \param mode The permissions with which to try to create the directory
650 * \retval 0 on success
651 * \return error code otherwise
652 *
653 * Creates a directory path, creating parent directories as needed.
654 */
655int ast_mkdir(const char *path, int mode);
656
657/*!
658 * \brief Recursively create directory path, but only if it resolves within
659 * the given \a base_path.
660 *
661 * If \a base_path does not exist, it will not be created and this function
662 * returns \c EPERM.
663 *
664 * \param base_path
665 * \param path The directory path to create
666 * \param mode The permissions with which to try to create the directory
667 * \retval 0 on success
668 * \return an error code otherwise
669 */
670int ast_safe_mkdir(const char *base_path, const char *path, int mode);
671
672#define ARRAY_LEN(a) (size_t) (sizeof(a) / sizeof(0[a]))
673
674/*!
675 * \brief Checks to see if value is within the given bounds
676 *
677 * \param v the value to check
678 * \param min minimum lower bound (inclusive)
679 * \param max maximum upper bound (inclusive)
680 * \retval 0 if value out of bounds
681 * \retval non-zero otherwise
682 */
683#define IN_BOUNDS(v, min, max) ((v) >= (min)) && ((v) <= (max))
684
685/*!
686 * \brief Checks to see if value is within the bounds of the given array
687 *
688 * \param v the value to check
689 * \param a the array to bound check
690 * \retval 0 if value out of bounds
691 * \retval non-zero otherwise
692 */
693#define ARRAY_IN_BOUNDS(v, a) IN_BOUNDS((int) (v), 0, ARRAY_LEN(a) - 1)
694
695/* Definition for Digest authorization */
707 );
708 int qop; /* Flag set to 1, if we send/recv qop="quth" */
709};
710
711/*!
712 * \brief Parse digest authorization header.
713 * \return -1 if we have no auth or something wrong with digest.
714 * \note This function may be used for Digest request and responce header.
715 * request arg is set to nonzero, if we parse Digest Request.
716 * pedantic arg can be set to nonzero if we need to do addition Digest check.
717 */
718int ast_parse_digest(const char *digest, struct ast_http_digest *d, int request, int pedantic);
719
720#ifdef DO_CRASH
721#define DO_CRASH_NORETURN attribute_noreturn
722#else
723#define DO_CRASH_NORETURN
724#endif
725
726void DO_CRASH_NORETURN __ast_assert_failed(int condition, const char *condition_str,
727 const char *file, int line, const char *function);
728
729#ifdef AST_DEVMODE
730#define ast_assert(a) _ast_assert(a, # a, __FILE__, __LINE__, __PRETTY_FUNCTION__)
731#define ast_assert_return(a, ...) \
732({ \
733 if (__builtin_expect(!(a), 1)) { \
734 _ast_assert(0, # a, __FILE__, __LINE__, __PRETTY_FUNCTION__); \
735 return __VA_ARGS__; \
736 }\
737})
738static void force_inline _ast_assert(int condition, const char *condition_str, const char *file, int line, const char *function)
739{
740 if (__builtin_expect(!condition, 1)) {
741 __ast_assert_failed(condition, condition_str, file, line, function);
742 }
743}
744#else
745#define ast_assert(a)
746#define ast_assert_return(a, ...) \
747({ \
748 if (__builtin_expect(!(a), 1)) { \
749 return __VA_ARGS__; \
750 }\
751})
752#endif
753
754/*!
755 * \brief Force a crash if DO_CRASH is defined.
756 *
757 * \note If DO_CRASH is not defined then the function returns.
758 */
760
761#include "asterisk/strings.h"
762
763/*!
764 * \brief Return the number of bytes used in the alignment of type.
765 * \param type
766 * \return The number of bytes required for alignment.
767 *
768 * This is really just __alignof__(), but tucked away in this header so we
769 * don't have to look at the nasty underscores in the source.
770 */
771#define ast_alignof(type) __alignof__(type)
772
773/*!
774 * \brief Increase offset so it is a multiple of the required alignment of type.
775 * \param offset The value that should be increased.
776 * \param type The data type that offset should be aligned to.
777 * \return The smallest multiple of alignof(type) larger than or equal to offset.
778 * \see ast_make_room_for()
779 *
780 * Many systems prefer integers to be stored on aligned on memory locations.
781 * This macro will increase an offset so a value of the supplied type can be
782 * safely be stored on such a memory location.
783 *
784 * Examples:
785 * ast_align_for(0x17, int64_t) ==> 0x18
786 * ast_align_for(0x18, int64_t) ==> 0x18
787 * ast_align_for(0x19, int64_t) ==> 0x20
788 *
789 * Don't mind the ugliness, the compiler will optimize it.
790 */
791#define ast_align_for(offset, type) (((offset + __alignof__(type) - 1) / __alignof__(type)) * __alignof__(type))
792
793/*!
794 * \brief Increase offset by the required alignment of type and make sure it is
795 * a multiple of said alignment.
796 * \param offset The value that should be increased.
797 * \param type The data type that room should be reserved for.
798 * \return The smallest multiple of alignof(type) larger than or equal to offset
799 * plus alignof(type).
800 * \see ast_align_for()
801 *
802 * A use case for this is when prepending length fields of type int to a buffer.
803 * If you keep the offset a multiple of the alignment of the integer type,
804 * a next block of length+buffer will have the length field automatically
805 * aligned.
806 *
807 * Examples:
808 * ast_make_room_for(0x17, int64_t) ==> 0x20
809 * ast_make_room_for(0x18, int64_t) ==> 0x20
810 * ast_make_room_for(0x19, int64_t) ==> 0x28
811 *
812 * Don't mind the ugliness, the compiler will optimize it.
813 */
814#define ast_make_room_for(offset, type) (((offset + (2 * __alignof__(type) - 1)) / __alignof__(type)) * __alignof__(type))
815
816/*!
817 * \brief An Entity ID is essentially a MAC address, brief and unique
818 */
819struct ast_eid {
820 unsigned char eid[6];
821} __attribute__((__packed__));
822
823/*!
824 * \brief Global EID
825 *
826 * This is set in asterisk.conf, or determined automatically by taking the mac
827 * address of an Ethernet interface on the system.
828 */
829extern struct ast_eid ast_eid_default;
830
831/*!
832 * \brief Fill in an ast_eid with the default eid of this machine
833 * \since 1.6.1
834 */
835void ast_set_default_eid(struct ast_eid *eid);
836
837/*!
838 * \brief Convert an EID to a string
839 * \since 1.6.1
840 */
841char *ast_eid_to_str(char *s, int maxlen, struct ast_eid *eid);
842
843/*!
844 * \brief Convert a string into an EID
845 *
846 * This function expects an EID in the format:
847 * 00:11:22:33:44:55
848 *
849 * \retval 0 success
850 * \retval non-zero failure
851 * \since 1.6.1
852 */
853int ast_str_to_eid(struct ast_eid *eid, const char *s);
854
855/*!
856 * \brief Compare two EIDs
857 *
858 * \retval 0 if the two are the same
859 * \retval non-zero otherwise
860 * \since 1.6.1
861 */
862int ast_eid_cmp(const struct ast_eid *eid1, const struct ast_eid *eid2);
863
864/*!
865 * \brief Check if EID is empty
866 *
867 * \retval 1 if the EID is empty
868 * \retval 0 otherwise
869 * \since 13.12.0
870 */
871int ast_eid_is_empty(const struct ast_eid *eid);
872
873/*!
874 * \brief Get current thread ID
875 * \return the ID if platform is supported, else -1
876 */
877int ast_get_tid(void);
878
879/*!
880 * \brief Resolve a binary to a full pathname
881 * \param binary Name of the executable to resolve
882 * \param fullpath Buffer to hold the complete pathname
883 * \param fullpath_size Size of \a fullpath
884 * \retval NULL \a binary was not found or the environment variable PATH is not set
885 * \return \a fullpath
886 */
887char *ast_utils_which(const char *binary, char *fullpath, size_t fullpath_size);
888
889/*!
890 * \brief Declare a variable that will call a destructor function when it goes out of scope.
891 *
892 * Resource Allocation Is Initialization (RAII) variable declaration.
893 *
894 * \since 11.0
895 * \param vartype The type of the variable
896 * \param varname The name of the variable
897 * \param initval The initial value of the variable
898 * \param dtor The destructor function of type' void func(vartype *)'
899 *
900 * \code
901 * void mything_cleanup(struct mything *t)
902 * {
903 * if (t) {
904 * ast_free(t->stuff);
905 * }
906 * }
907 *
908 * void do_stuff(const char *name)
909 * {
910 * RAII_VAR(struct mything *, thing, mything_alloc(name), mything_cleanup);
911 * ...
912 * }
913 * \endcode
914 *
915 * \note This macro is especially useful for working with ao2 objects. A common idiom
916 * would be a function that needed to look up an ao2 object and might have several error
917 * conditions after the allocation that would normally need to unref the ao2 object.
918 * With RAII_VAR, it is possible to just return and leave the cleanup to the destructor
919 * function. For example:
920 *
921 * \code
922 * void do_stuff(const char *name)
923 * {
924 * RAII_VAR(struct mything *, thing, find_mything(name), ao2_cleanup);
925 * if (!thing) {
926 * return;
927 * }
928 * if (error) {
929 * return;
930 * }
931 * do_stuff_with_thing(thing);
932 * }
933 * \endcode
934 */
935
936#if defined(__clang__)
937typedef void (^_raii_cleanup_block_t)(void);
938static inline void _raii_cleanup_block(_raii_cleanup_block_t *b) { (*b)(); }
939
940#define RAII_VAR(vartype, varname, initval, dtor) \
941 __block vartype varname = initval; \
942 _raii_cleanup_block_t _raii_cleanup_ ## varname __attribute__((cleanup(_raii_cleanup_block),unused)) = \
943 ^{ {(void)dtor(varname);} };
944
945#elif defined(__GNUC__)
946
947#define RAII_VAR(vartype, varname, initval, dtor) \
948 auto void _dtor_ ## varname (vartype * v); \
949 void _dtor_ ## varname (vartype * v) { dtor(*v); } \
950 vartype varname __attribute__((cleanup(_dtor_ ## varname))) = (initval)
951
952#else
953 #error "Cannot compile Asterisk: unknown and unsupported compiler."
954#endif /* #if __GNUC__ */
955
956/*!
957 * \brief Asterisk wrapper around crypt(3).
958 *
959 * The interpretation of the salt (which determines the password hashing
960 * algorithm) is system specific. Application code should prefer to use
961 * ast_crypt_encrypt() or ast_crypt_validate().
962 *
963 * The returned string is heap allocated, and should be freed with ast_free().
964 *
965 * \param key User's password to crypt.
966 * \param salt Salt to crypt with.
967 * \return Crypted password.
968 * \retval NULL on error.
969 */
970char *ast_crypt(const char *key, const char *salt);
971
972/*!
973 * \brief Asterisk wrapper around crypt(3) for encrypting passwords.
974 *
975 * This function will generate a random salt and encrypt the given password.
976 *
977 * The returned string is heap allocated, and should be freed with ast_free().
978 *
979 * \param key User's password to crypt.
980 * \return Crypted password.
981 * \retval NULL on error.
982 */
983char *ast_crypt_encrypt(const char *key);
984
985/*!
986 * \brief Asterisk wrapper around crypt(3) for validating passwords.
987 *
988 * \param key User's password to validate.
989 * \param expected Expected result from crypt.
990 * \retval True (non-zero) if \a key matches \a expected.
991 * \retval False (zero) if \a key doesn't match.
992 */
993int ast_crypt_validate(const char *key, const char *expected);
994
995/*!
996 * \brief Test that a file exists and is readable by the effective user.
997 * \since 13.7.0
998 *
999 * \param filename File to test.
1000 * \retval True (non-zero) if the file exists and is readable.
1001 * \retval False (zero) if the file either doesn't exists or is not readable.
1002 */
1003int ast_file_is_readable(const char *filename);
1004
1005/*!
1006 * \brief Compare 2 major.minor.patch.extra version strings.
1007 * \since 13.7.0
1008 *
1009 * \param version1
1010 * \param version2
1011 *
1012 * \retval negative if version 1 < version 2.
1013 * \retval 0 if version 1 = version 2.
1014 * \retval positive if version 1 > version 2.
1015 */
1016int ast_compare_versions(const char *version1, const char *version2);
1017
1018/*!
1019 * \brief Test that an OS supports IPv6 Networking.
1020 * \since 13.14.0
1021 *
1022 * \retval True (non-zero) if the IPv6 supported.
1023 * \retval False (zero) if the OS doesn't support IPv6.
1024 */
1025int ast_check_ipv6(void);
1026
1030};
1031
1032/*!
1033 * \brief Set flags on the given file descriptor
1034 * \since 13.19
1035 *
1036 * If getting or setting flags of the given file descriptor fails, logs an
1037 * error message.
1038 *
1039 * \param fd File descriptor to set flags on
1040 * \param flags The flag(s) to set
1041 *
1042 * \retval -1 on error
1043 * \retval 0 if successful
1044 */
1045#define ast_fd_set_flags(fd, flags) \
1046 __ast_fd_set_flags((fd), (flags), AST_FD_FLAG_SET, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1047
1048/*!
1049 * \brief Clear flags on the given file descriptor
1050 * \since 13.19
1051 *
1052 * If getting or setting flags of the given file descriptor fails, logs an
1053 * error message.
1054 *
1055 * \param fd File descriptor to clear flags on
1056 * \param flags The flag(s) to clear
1057 *
1058 * \retval -1 on error
1059 * \retval 0 if successful
1060 */
1061#define ast_fd_clear_flags(fd, flags) \
1062 __ast_fd_set_flags((fd), (flags), AST_FD_FLAG_CLEAR, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1063
1064int __ast_fd_set_flags(int fd, int flags, enum ast_fd_flag_operation op,
1065 const char *file, int lineno, const char *function);
1066
1067/*!
1068 * \brief Create a non-blocking socket
1069 * \since 13.25
1070 *
1071 * Wrapper around socket(2) that sets the O_NONBLOCK flag on the resulting
1072 * socket.
1073 *
1074 * \details
1075 * For parameter and return information, see the man page for
1076 * socket(2).
1077 */
1078#ifdef HAVE_SOCK_NONBLOCK
1079# define ast_socket_nonblock(domain, type, protocol) socket((domain), (type) | SOCK_NONBLOCK, (protocol))
1080#else
1081int ast_socket_nonblock(int domain, int type, int protocol);
1082#endif
1083
1084/*!
1085 * \brief Create a non-blocking pipe
1086 * \since 13.25
1087 *
1088 * Wrapper around pipe(2) that sets the O_NONBLOCK flag on the resulting
1089 * file descriptors.
1090 *
1091 * \details
1092 * For parameter and return information, see the man page for
1093 * pipe(2).
1094 */
1095#ifdef HAVE_PIPE2
1096# define ast_pipe_nonblock(filedes) pipe2((filedes), O_NONBLOCK)
1097#else
1098int ast_pipe_nonblock(int filedes[2]);
1099#endif
1100
1101/*!
1102 * \brief Set the current thread's user interface status.
1103 *
1104 * \param is_user_interface Non-zero to mark the thread as a user interface.
1105 *
1106 * \retval True (non-zero) if marking current thread failed.
1107 * \retval False (zero) if successfuly marked current thread.
1108 */
1109int ast_thread_user_interface_set(int is_user_interface);
1110
1111/*!
1112 * \brief Indicates whether the current thread is a user interface
1113 *
1114 * \retval True (non-zero) if thread is a user interface.
1115 * \retval False (zero) if thread is not a user interface.
1116 */
1118
1119/*!
1120 * \brief Test for the presence of an executable command in $PATH
1121 *
1122 * \param cmd Name of command to locate.
1123 *
1124 * \retval True (non-zero) if command is in $PATH.
1125 * \retval False (zero) command not found.
1126 */
1127int ast_check_command_in_path(const char *cmd);
1128
1129#endif /* _ASTERISK_UTILS_H */
pthread_t thread
Definition: app_sla.c:335
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:2619
#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:819
unsigned char eid[6]
Definition: utils.h:820
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:707
const ast_string_field uri
Definition: utils.h:707
const ast_string_field domain
Definition: utils.h:707
const ast_string_field opaque
Definition: utils.h:707
const ast_string_field cnonce
Definition: utils.h:707
const ast_string_field nonce
Definition: utils.h:707
const ast_string_field username
Definition: utils.h:707
const ast_string_field realm
Definition: utils.h:707
const ast_string_field nc
Definition: utils.h:707
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:510
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:723
ast_fd_flag_operation
Definition: utils.h:1027
@ AST_FD_FLAG_SET
Definition: utils.h:1028
@ AST_FD_FLAG_CLEAR
Definition: utils.h:1029
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:1079
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:421
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:437
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:1096
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:94
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:505
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