Asterisk - The Open Source Telephony Project  GIT-master-4a4f1a5
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"
36 #include "asterisk/stringfields.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 
61 extern 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 
118 extern 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 */
199 struct 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? */
204 struct ast_flags64 {
205  uint64_t flags;
206 };
207 
208 struct ast_hostent {
209  struct hostent hp;
210  char buf[1024];
211 };
212 
213 /*! \brief Thread-safe gethostbyname function to use in Asterisk */
214 struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp);
215 
216 /*! \brief Produces MD5 hash based on input string */
217 void ast_md5_hash(char *output, const char *input);
218 /*! \brief Produces SHA1 hash based on input string */
219 void ast_sha1_hash(char *output, const char *input);
220 /*! \brief Produces SHA1 hash based on input string, stored in uint8_t array */
221 void ast_sha1_hash_uint(uint8_t *digest, const char *input);
222 
223 int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks);
224 
225 #undef MIN
226 #define MIN(a, b) ({ typeof(a) __a = (a); typeof(b) __b = (b); ((__a > __b) ? __b : __a);})
227 #undef MAX
228 #define MAX(a, b) ({ typeof(a) __a = (a); typeof(b) __b = (b); ((__a < __b) ? __b : __a);})
229 
230 #define SWAP(a,b) do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)
231 
232 /*!
233  * \brief Encode data in base64
234  * \param dst the destination buffer
235  * \param src the source data to be encoded
236  * \param srclen the number of bytes present in the source buffer
237  * \param max the maximum number of bytes to write into the destination
238  * buffer, *including* the terminating NULL character.
239  */
240 int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max);
241 
242 /*!
243  * \brief Same as ast_base64encode, but does hte math for you and returns
244  * an encoded string
245  *
246  * \note The returned string will need to be freed later
247  *
248  * \param src The source buffer
249  *
250  * \retval NULL on failure
251  * \retval Encoded string on success
252  */
253 char *ast_base64encode_string(const char *src);
254 
255 /*!
256  * \brief Decode data from base64
257  * \param dst the destination buffer
258  * \param src the source buffer
259  * \param max The maximum number of bytes to write into the destination
260  * buffer. Note that this function will not ensure that the
261  * destination buffer is NULL terminated. So, in general,
262  * this parameter should be sizeof(dst) - 1.
263  */
264 int ast_base64decode(unsigned char *dst, const char *src, int max);
265 
266 /*!
267  * \brief Same as ast_base64decode, but does the math for you and returns
268  * a decoded string
269  *
270  * \note The returned string will need to be freed later and IS NULL terminated
271  *
272  * \param src The source buffer
273  *
274  * \retval NULL on failure
275  * \retval Decoded string on success
276  */
277 char *ast_base64decode_string(const char *src);
278 
279 /*!
280  * \brief Decode data from base64 URL
281  *
282  * \param dst The destination buffer
283  * \param src The source buffer
284  * \param max The maximum number of bytes to write into the destination
285  * buffer. Note that this function will not ensure that the
286  * destination buffer is NULL terminated. So, in general,
287  * this parameter should be sizeof(dst) - 1
288  */
289 int ast_base64url_decode(unsigned char *dst, const char *src, int max);
290 
291 /*!
292  * \brief Same as ast_base64encode_full but for base64 URL
293  *
294  * \param dst The destination buffer
295  * \param src The source buffer
296  * \param srclen The number of bytes present in the source buffer
297  * \param max The maximum number of bytes to write into the destination
298  * buffer, *including* the terminating NULL character.
299  * \param linebreaks Set to 1 if there should be linebreaks inserted
300  * in the result
301  */
302 int ast_base64url_encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks);
303 
304 /*!
305  * \brief Encode data in base64 URL
306  *
307  * \param dst The destination buffer
308  * \param src The source data to be encoded
309  * \param srclen The number of bytes present in the source buffer
310  * \param max The maximum number of bytes to write into the destination
311  * buffer, including the terminating NULL character
312  */
313 int ast_base64url_encode(char *dst, const unsigned char *src, int srclen, int max);
314 
315 /*!
316  * \brief Decode string from base64 URL
317  *
318  * \note The returned string will need to be freed later
319  *
320  * \param src The source buffer
321  *
322  * \retval NULL on failure
323  * \retval Decoded string on success
324  */
325 char *ast_base64url_decode_string(const char *src);
326 
327 /*!
328  * \brief Encode string in base64 URL
329  *
330  * \note The returned string will need to be freed later
331  *
332  * \param src The source data to be encoded
333  *
334  * \retval NULL on failure
335  * \retval Encoded string on success
336  */
337 char *ast_base64url_encode_string(const char *src);
338 
339 #define AST_URI_ALPHANUM (1 << 0)
340 #define AST_URI_MARK (1 << 1)
341 #define AST_URI_UNRESERVED (AST_URI_ALPHANUM | AST_URI_MARK)
342 #define AST_URI_LEGACY_SPACE (1 << 2)
343 
344 #define AST_URI_SIP_USER_UNRESERVED (1 << 20)
345 
346 extern const struct ast_flags ast_uri_http;
347 extern const struct ast_flags ast_uri_http_legacy;
348 extern const struct ast_flags ast_uri_sip_user;
349 
350 /*!
351  * \brief Turn text string to URI-encoded %XX version
352  *
353  * This function encodes characters according to the rules presented in RFC
354  * 2396 and/or RFC 3261 section 19.1.2 and section 25.1.
355  *
356  * Outbuf needs to have more memory allocated than the instring to have room
357  * for the expansion. Every byte that is converted is replaced by three ASCII
358  * characters.
359  *
360  * \param string string to be converted
361  * \param outbuf resulting encoded string
362  * \param buflen size of output buffer
363  * \param spec flags describing how the encoding should be performed
364  * \return a pointer to the uri encoded string
365  */
366 char *ast_uri_encode(const char *string, char *outbuf, int buflen, struct ast_flags spec);
367 
368 /*!
369  * \brief Decode URI, URN, URL (overwrite string)
370  *
371  * \note The ast_uri_http_legacy decode spec flag will cause this function to
372  * decode '+' as ' '.
373  *
374  * \param s string to be decoded
375  * \param spec flags describing how the decoding should be performed
376  */
377 void ast_uri_decode(char *s, struct ast_flags spec);
378 
379 /*! ast_xml_escape
380  \brief Escape reserved characters for use in XML.
381 
382  If \a outbuf is too short, the output string will be truncated.
383  Regardless, the output will always be null terminated.
384 
385  \param string String to be converted
386  \param outbuf Resulting encoded string
387  \param buflen Size of output buffer
388  \return 0 for success
389  \return -1 if buflen is too short.
390  */
391 int ast_xml_escape(const char *string, char *outbuf, size_t buflen);
392 
393 /*!
394  * \brief Escape characters found in a quoted string.
395  *
396  * \note This function escapes quoted characters based on the 'qdtext' set of
397  * allowed characters from RFC 3261 section 25.1.
398  *
399  * \param string string to be escaped
400  * \param outbuf resulting escaped string
401  * \param buflen size of output buffer
402  * \return a pointer to the escaped string
403  */
404 char *ast_escape_quoted(const char *string, char *outbuf, int buflen);
405 
406 /*!
407  * \brief Escape semicolons found in a string.
408  *
409  * \param string string to be escaped
410  * \param outbuf resulting escaped string
411  * \param buflen size of output buffer
412  * \return a pointer to the escaped string
413  */
414 char *ast_escape_semicolons(const char *string, char *outbuf, int buflen);
415 
416 /*!
417  * \brief Unescape quotes in a string
418  *
419  * \param quote_str The string with quotes to be unescaped
420  *
421  * \note This function mutates the passed-in string.
422  */
423 void ast_unescape_quoted(char *quote_str);
424 
426 {
427  int res;
428 
429  res = (int) *input + *value;
430  if (res > 32767)
431  *input = 32767;
432  else if (res < -32768)
433  *input = -32768;
434  else
435  *input = (short) res;
436 }
437 
439 {
440  int res;
441 
442  res = (int) *input - *value;
443  if (res > 32767)
444  *input = 32767;
445  else if (res < -32768)
446  *input = -32768;
447  else
448  *input = (short) res;
449 }
450 
452 {
453  int res;
454 
455  res = (int) *input * *value;
456  if (res > 32767)
457  *input = 32767;
458  else if (res < -32768)
459  *input = -32768;
460  else
461  *input = (short) res;
462 }
463 
465 {
466  float res;
467 
468  res = (float) *input * *value;
469  if (res > 32767)
470  *input = 32767;
471  else if (res < -32768)
472  *input = -32768;
473  else
474  *input = (short) res;
475 }
476 
478 {
479  *input /= *value;
480 }
481 
483 {
484  float res = (float) *input / *value;
485  if (res > 32767)
486  *input = 32767;
487  else if (res < -32768)
488  *input = -32768;
489  else
490  *input = (short) res;
491 }
492 
493 #ifdef localtime_r
494 #undef localtime_r
495 #endif
496 #define localtime_r __dont_use_localtime_r_use_ast_localtime_instead__
497 
498 int ast_utils_init(void);
499 int ast_wait_for_input(int fd, int ms);
500 int ast_wait_for_output(int fd, int ms);
501 
502 /*!
503  * \brief Try to write string, but wait no more than ms milliseconds
504  * before timing out.
505  *
506  * \note If you are calling ast_carefulwrite, it is assumed that you are calling
507  * it on a file descriptor that _DOES_ have NONBLOCK set. This way,
508  * there is only one system call made to do a write, unless we actually
509  * have a need to wait. This way, we get better performance.
510  */
511 int ast_carefulwrite(int fd, char *s, int len, int timeoutms);
512 
513 /*!
514  * \brief Write data to a file stream with a timeout
515  *
516  * \param f the file stream to write to
517  * \param fd the file description to poll on to know when the file stream can
518  * be written to without blocking.
519  * \param s the buffer to write from
520  * \param len the number of bytes to write
521  * \param timeoutms The maximum amount of time to block in this function trying
522  * to write, specified in milliseconds.
523  *
524  * \note This function assumes that the associated file stream has been set up
525  * as non-blocking.
526  *
527  * \retval 0 success
528  * \retval -1 error
529  */
530 int ast_careful_fwrite(FILE *f, int fd, const char *s, size_t len, int timeoutms);
531 
532 /*
533  * Thread management support (should be moved to lock.h or a different header)
534  */
535 
536 #if defined(PTHREAD_STACK_MIN)
537 # define AST_STACKSIZE MAX((((sizeof(void *) * 8 * 8) - 16) * 1024), PTHREAD_STACK_MIN)
538 # define AST_STACKSIZE_LOW MAX((((sizeof(void *) * 8 * 2) - 16) * 1024), PTHREAD_STACK_MIN)
539 #else
540 # define AST_STACKSIZE (((sizeof(void *) * 8 * 8) - 16) * 1024)
541 # define AST_STACKSIZE_LOW (((sizeof(void *) * 8 * 2) - 16) * 1024)
542 #endif
543 
544 int ast_background_stacksize(void);
545 
546 #define AST_BACKGROUND_STACKSIZE ast_background_stacksize()
547 
548 void ast_register_thread(char *name);
549 void ast_unregister_thread(void *id);
550 
551 int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
552  void *data, size_t stacksize, const char *file, const char *caller,
553  int line, const char *start_fn);
554 
555 int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void*(*start_routine)(void *),
556  void *data, size_t stacksize, const char *file, const char *caller,
557  int line, const char *start_fn);
558 
559 #define ast_pthread_create(a, b, c, d) \
560  ast_pthread_create_stack(a, b, c, d, \
561  0, __FILE__, __FUNCTION__, __LINE__, #c)
562 
563 #define ast_pthread_create_detached(a, b, c, d) \
564  ast_pthread_create_detached_stack(a, b, c, d, \
565  0, __FILE__, __FUNCTION__, __LINE__, #c)
566 
567 #define ast_pthread_create_background(a, b, c, d) \
568  ast_pthread_create_stack(a, b, c, d, \
569  AST_BACKGROUND_STACKSIZE, \
570  __FILE__, __FUNCTION__, __LINE__, #c)
571 
572 #define ast_pthread_create_detached_background(a, b, c, d) \
573  ast_pthread_create_detached_stack(a, b, c, d, \
574  AST_BACKGROUND_STACKSIZE, \
575  __FILE__, __FUNCTION__, __LINE__, #c)
576 
577 /* End of thread management support */
578 
579 /*!
580  * \brief Replace '^' in a string with ','
581  * \param s String within which to replace characters
582  */
584 
585 /*!
586  * \brief Process a string to find and replace characters
587  * \param start The string to analyze
588  * \param find The character to find
589  * \param replace_with The character that will replace the one we are looking for
590  */
591 char *ast_process_quotes_and_slashes(char *start, char find, char replace_with);
592 
593 long int ast_random(void);
594 
595 /*!
596  * \brief Returns a random number between 0.0 and 1.0, inclusive.
597  * \since 12
598  */
599 #define ast_random_double() (((double)ast_random()) / RAND_MAX)
600 
601 /*!
602  * \brief Disable PMTU discovery on a socket
603  * \param sock The socket to manipulate
604  * \return Nothing
605  *
606  * On Linux, UDP sockets default to sending packets with the Dont Fragment (DF)
607  * bit set. This is supposedly done to allow the application to do PMTU
608  * discovery, but Asterisk does not do this.
609  *
610  * Because of this, UDP packets sent by Asterisk that are larger than the MTU
611  * of any hop in the path will be lost. This function can be called on a socket
612  * to ensure that the DF bit will not be set.
613  */
614 void ast_enable_packet_fragmentation(int sock);
615 
616 /*!
617  * \brief Recursively create directory path
618  * \param path The directory path to create
619  * \param mode The permissions with which to try to create the directory
620  * \return 0 on success or an error code otherwise
621  *
622  * Creates a directory path, creating parent directories as needed.
623  */
624 int ast_mkdir(const char *path, int mode);
625 
626 /*!
627  * \brief Recursively create directory path, but only if it resolves within
628  * the given \a base_path.
629  *
630  * If \a base_path does not exist, it will not be created and this function
631  * returns \c EPERM.
632  *
633  * \param path The directory path to create
634  * \param mode The permissions with which to try to create the directory
635  * \return 0 on success or an error code otherwise
636  */
637 int ast_safe_mkdir(const char *base_path, const char *path, int mode);
638 
639 #define ARRAY_LEN(a) (size_t) (sizeof(a) / sizeof(0[a]))
640 
641 /*!
642  * \brief Checks to see if value is within the given bounds
643  *
644  * \param v the value to check
645  * \param min minimum lower bound (inclusive)
646  * \param max maximum upper bound (inclusive)
647  * \return 0 if value out of bounds, otherwise true (non-zero)
648  */
649 #define IN_BOUNDS(v, min, max) ((v) >= (min)) && ((v) <= (max))
650 
651 /*!
652  * \brief Checks to see if value is within the bounds of the given array
653  *
654  * \param v the value to check
655  * \param a the array to bound check
656  * \return 0 if value out of bounds, otherwise true (non-zero)
657  */
658 #define ARRAY_IN_BOUNDS(v, a) IN_BOUNDS((int) (v), 0, ARRAY_LEN(a) - 1)
659 
660 /* Definition for Digest authorization */
672  );
673  int qop; /* Flag set to 1, if we send/recv qop="quth" */
674 };
675 
676 /*!
677  * \brief Parse digest authorization header.
678  * \return Returns -1 if we have no auth or something wrong with digest.
679  * \note This function may be used for Digest request and responce header.
680  * request arg is set to nonzero, if we parse Digest Request.
681  * pedantic arg can be set to nonzero if we need to do addition Digest check.
682  */
683 int ast_parse_digest(const char *digest, struct ast_http_digest *d, int request, int pedantic);
684 
685 #ifdef DO_CRASH
686 #define DO_CRASH_NORETURN attribute_noreturn
687 #else
688 #define DO_CRASH_NORETURN
689 #endif
690 
691 void DO_CRASH_NORETURN __ast_assert_failed(int condition, const char *condition_str,
692  const char *file, int line, const char *function);
693 
694 #ifdef AST_DEVMODE
695 #define ast_assert(a) _ast_assert(a, # a, __FILE__, __LINE__, __PRETTY_FUNCTION__)
696 #define ast_assert_return(a, ...) \
697 ({ \
698  if (__builtin_expect(!(a), 1)) { \
699  _ast_assert(0, # a, __FILE__, __LINE__, __PRETTY_FUNCTION__); \
700  return __VA_ARGS__; \
701  }\
702 })
703 static void force_inline _ast_assert(int condition, const char *condition_str, const char *file, int line, const char *function)
704 {
705  if (__builtin_expect(!condition, 1)) {
706  __ast_assert_failed(condition, condition_str, file, line, function);
707  }
708 }
709 #else
710 #define ast_assert(a)
711 #define ast_assert_return(a, ...) \
712 ({ \
713  if (__builtin_expect(!(a), 1)) { \
714  return __VA_ARGS__; \
715  }\
716 })
717 #endif
718 
719 /*!
720  * \brief Force a crash if DO_CRASH is defined.
721  *
722  * \note If DO_CRASH is not defined then the function returns.
723  *
724  * \return Nothing
725  */
727 
728 #include "asterisk/strings.h"
729 
730 /*!
731  * \brief Return the number of bytes used in the alignment of type.
732  * \param type
733  * \return The number of bytes required for alignment.
734  *
735  * This is really just __alignof__(), but tucked away in this header so we
736  * don't have to look at the nasty underscores in the source.
737  */
738 #define ast_alignof(type) __alignof__(type)
739 
740 /*!
741  * \brief Increase offset so it is a multiple of the required alignment of type.
742  * \param offset The value that should be increased.
743  * \param type The data type that offset should be aligned to.
744  * \return The smallest multiple of alignof(type) larger than or equal to offset.
745  * \see ast_make_room_for()
746  *
747  * Many systems prefer integers to be stored on aligned on memory locations.
748  * This macro will increase an offset so a value of the supplied type can be
749  * safely be stored on such a memory location.
750  *
751  * Examples:
752  * ast_align_for(0x17, int64_t) ==> 0x18
753  * ast_align_for(0x18, int64_t) ==> 0x18
754  * ast_align_for(0x19, int64_t) ==> 0x20
755  *
756  * Don't mind the ugliness, the compiler will optimize it.
757  */
758 #define ast_align_for(offset, type) (((offset + __alignof__(type) - 1) / __alignof__(type)) * __alignof__(type))
759 
760 /*!
761  * \brief Increase offset by the required alignment of type and make sure it is
762  * a multiple of said alignment.
763  * \param offset The value that should be increased.
764  * \param type The data type that room should be reserved for.
765  * \return The smallest multiple of alignof(type) larger than or equal to offset
766  * plus alignof(type).
767  * \see ast_align_for()
768  *
769  * A use case for this is when prepending length fields of type int to a buffer.
770  * If you keep the offset a multiple of the alignment of the integer type,
771  * a next block of length+buffer will have the length field automatically
772  * aligned.
773  *
774  * Examples:
775  * ast_make_room_for(0x17, int64_t) ==> 0x20
776  * ast_make_room_for(0x18, int64_t) ==> 0x20
777  * ast_make_room_for(0x19, int64_t) ==> 0x28
778  *
779  * Don't mind the ugliness, the compiler will optimize it.
780  */
781 #define ast_make_room_for(offset, type) (((offset + (2 * __alignof__(type) - 1)) / __alignof__(type)) * __alignof__(type))
782 
783 /*!
784  * \brief An Entity ID is essentially a MAC address, brief and unique
785  */
786 struct ast_eid {
787  unsigned char eid[6];
788 } __attribute__((__packed__));
789 
790 /*!
791  * \brief Global EID
792  *
793  * This is set in asterisk.conf, or determined automatically by taking the mac
794  * address of an Ethernet interface on the system.
795  */
796 extern struct ast_eid ast_eid_default;
797 
798 /*!
799  * \brief Fill in an ast_eid with the default eid of this machine
800  * \since 1.6.1
801  */
802 void ast_set_default_eid(struct ast_eid *eid);
803 
804 /*!
805  * \brief Convert an EID to a string
806  * \since 1.6.1
807  */
808 char *ast_eid_to_str(char *s, int maxlen, struct ast_eid *eid);
809 
810 /*!
811  * \brief Convert a string into an EID
812  *
813  * This function expects an EID in the format:
814  * 00:11:22:33:44:55
815  *
816  * \return 0 success, non-zero failure
817  * \since 1.6.1
818  */
819 int ast_str_to_eid(struct ast_eid *eid, const char *s);
820 
821 /*!
822  * \brief Compare two EIDs
823  *
824  * \return 0 if the two are the same, non-zero otherwise
825  * \since 1.6.1
826  */
827 int ast_eid_cmp(const struct ast_eid *eid1, const struct ast_eid *eid2);
828 
829 /*!
830  * \brief Check if EID is empty
831  *
832  * \return 1 if the EID is empty, zero otherwise
833  * \since 13.12.0
834  */
835 int ast_eid_is_empty(const struct ast_eid *eid);
836 
837 /*!
838  * \brief Get current thread ID
839  * \return the ID if platform is supported, else -1
840  */
841 int ast_get_tid(void);
842 
843 /*!
844  * \brief Resolve a binary to a full pathname
845  * \param binary Name of the executable to resolve
846  * \param fullpath Buffer to hold the complete pathname
847  * \param fullpath_size Size of \a fullpath
848  * \retval NULL \a binary was not found or the environment variable PATH is not set
849  * \return \a fullpath
850  */
851 char *ast_utils_which(const char *binary, char *fullpath, size_t fullpath_size);
852 
853 /*!
854  * \brief Declare a variable that will call a destructor function when it goes out of scope.
855  *
856  * Resource Allocation Is Initialization (RAII) variable declaration.
857  *
858  * \since 11.0
859  * \param vartype The type of the variable
860  * \param varname The name of the variable
861  * \param initval The initial value of the variable
862  * \param dtor The destructor function of type' void func(vartype *)'
863  *
864  * \code
865  * void mything_cleanup(struct mything *t)
866  * {
867  * if (t) {
868  * ast_free(t->stuff);
869  * }
870  * }
871  *
872  * void do_stuff(const char *name)
873  * {
874  * RAII_VAR(struct mything *, thing, mything_alloc(name), mything_cleanup);
875  * ...
876  * }
877  * \endcode
878  *
879  * \note This macro is especially useful for working with ao2 objects. A common idiom
880  * would be a function that needed to look up an ao2 object and might have several error
881  * conditions after the allocation that would normally need to unref the ao2 object.
882  * With RAII_VAR, it is possible to just return and leave the cleanup to the destructor
883  * function. For example:
884  *
885  * \code
886  * void do_stuff(const char *name)
887  * {
888  * RAII_VAR(struct mything *, thing, find_mything(name), ao2_cleanup);
889  * if (!thing) {
890  * return;
891  * }
892  * if (error) {
893  * return;
894  * }
895  * do_stuff_with_thing(thing);
896  * }
897  * \endcode
898  */
899 
900 #if defined(__clang__)
901 typedef void (^_raii_cleanup_block_t)(void);
902 static inline void _raii_cleanup_block(_raii_cleanup_block_t *b) { (*b)(); }
903 
904 #define RAII_VAR(vartype, varname, initval, dtor) \
905  __block vartype varname = initval; \
906  _raii_cleanup_block_t _raii_cleanup_ ## varname __attribute__((cleanup(_raii_cleanup_block),unused)) = \
907  ^{ {(void)dtor(varname);} };
908 
909 #elif defined(__GNUC__)
910 
911 #define RAII_VAR(vartype, varname, initval, dtor) \
912  auto void _dtor_ ## varname (vartype * v); \
913  void _dtor_ ## varname (vartype * v) { dtor(*v); } \
914  vartype varname __attribute__((cleanup(_dtor_ ## varname))) = (initval)
915 
916 #else
917  #error "Cannot compile Asterisk: unknown and unsupported compiler."
918 #endif /* #if __GNUC__ */
919 
920 /*!
921  * \brief Asterisk wrapper around crypt(3).
922  *
923  * The interpretation of the salt (which determines the password hashing
924  * algorithm) is system specific. Application code should prefer to use
925  * ast_crypt_encrypt() or ast_crypt_validate().
926  *
927  * The returned string is heap allocated, and should be freed with ast_free().
928  *
929  * \param key User's password to crypt.
930  * \param salt Salt to crypt with.
931  * \return Crypted password.
932  * \return \c NULL on error.
933  */
934 char *ast_crypt(const char *key, const char *salt);
935 
936 /*!
937  * \brief Asterisk wrapper around crypt(3) for encrypting passwords.
938  *
939  * This function will generate a random salt and encrypt the given password.
940  *
941  * The returned string is heap allocated, and should be freed with ast_free().
942  *
943  * \param key User's password to crypt.
944  * \return Crypted password.
945  * \return \c NULL on error.
946  */
947 char *ast_crypt_encrypt(const char *key);
948 
949 /*!
950  * \brief Asterisk wrapper around crypt(3) for validating passwords.
951  *
952  * \param key User's password to validate.
953  * \param expected Expected result from crypt.
954  * \return True (non-zero) if \a key matches \a expected.
955  * \return False (zero) if \a key doesn't match.
956  */
957 int ast_crypt_validate(const char *key, const char *expected);
958 
959 /*!
960  * \brief Test that a file exists and is readable by the effective user.
961  * \since 13.7.0
962  *
963  * \param filename File to test.
964  * \return True (non-zero) if the file exists and is readable.
965  * \return False (zero) if the file either doesn't exists or is not readable.
966  */
967 int ast_file_is_readable(const char *filename);
968 
969 /*!
970  * \brief Compare 2 major.minor.patch.extra version strings.
971  * \since 13.7.0
972  *
973  * \param version1.
974  * \param version2.
975  *
976  * \return <0 if version 1 < version 2.
977  * \return =0 if version 1 = version 2.
978  * \return >0 if version 1 > version 2.
979  */
980 int ast_compare_versions(const char *version1, const char *version2);
981 
982 /*!
983  * \brief Test that an OS supports IPv6 Networking.
984  * \since 13.14.0
985  *
986  * \return True (non-zero) if the IPv6 supported.
987  * \return False (zero) if the OS doesn't support IPv6.
988  */
989 int ast_check_ipv6(void);
990 
994 };
995 
996 /*!
997  * \brief Set flags on the given file descriptor
998  * \since 13.19
999  *
1000  * If getting or setting flags of the given file descriptor fails, logs an
1001  * error message.
1002  *
1003  * \param fd File descriptor to set flags on
1004  * \param flags The flag(s) to set
1005  *
1006  * \return -1 on error
1007  * \return 0 if successful
1008  */
1009 #define ast_fd_set_flags(fd, flags) \
1010  __ast_fd_set_flags((fd), (flags), AST_FD_FLAG_SET, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1011 
1012 /*!
1013  * \brief Clear flags on the given file descriptor
1014  * \since 13.19
1015  *
1016  * If getting or setting flags of the given file descriptor fails, logs an
1017  * error message.
1018  *
1019  * \param fd File descriptor to clear flags on
1020  * \param flags The flag(s) to clear
1021  *
1022  * \return -1 on error
1023  * \return 0 if successful
1024  */
1025 #define ast_fd_clear_flags(fd, flags) \
1026  __ast_fd_set_flags((fd), (flags), AST_FD_FLAG_CLEAR, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1027 
1028 int __ast_fd_set_flags(int fd, int flags, enum ast_fd_flag_operation op,
1029  const char *file, int lineno, const char *function);
1030 
1031 /*!
1032  * \brief Create a non-blocking socket
1033  * \since 13.25
1034  *
1035  * Wrapper around socket(2) that sets the O_NONBLOCK flag on the resulting
1036  * socket.
1037  *
1038  * \details
1039  * For parameter and return information, see the man page for
1040  * socket(2).
1041  */
1042 #ifdef HAVE_SOCK_NONBLOCK
1043 # define ast_socket_nonblock(domain, type, protocol) socket((domain), (type) | SOCK_NONBLOCK, (protocol))
1044 #else
1045 int ast_socket_nonblock(int domain, int type, int protocol);
1046 #endif
1047 
1048 /*!
1049  * \brief Create a non-blocking pipe
1050  * \since 13.25
1051  *
1052  * Wrapper around pipe(2) that sets the O_NONBLOCK flag on the resulting
1053  * file descriptors.
1054  *
1055  * \details
1056  * For parameter and return information, see the man page for
1057  * pipe(2).
1058  */
1059 #ifdef HAVE_PIPE2
1060 # define ast_pipe_nonblock(filedes) pipe2((filedes), O_NONBLOCK)
1061 #else
1062 int ast_pipe_nonblock(int filedes[2]);
1063 #endif
1064 
1065 /*!
1066  * \brief Set the current thread's user interface status.
1067  *
1068  * \param is_user_interface Non-zero to mark the thread as a user interface.
1069  *
1070  * \return 0 if successfuly marked current thread.
1071  * \return Non-zero if marking current thread failed.
1072  */
1073 int ast_thread_user_interface_set(int is_user_interface);
1074 
1075 /*!
1076  * \brief Indicates whether the current thread is a user interface
1077  *
1078  * \return True (non-zero) if thread is a user interface.
1079  * \return False (zero) if thread is not a user interface.
1080  */
1082 
1083 #endif /* _ASTERISK_UTILS_H */
pthread_t thread
Definition: app_meetme.c:1091
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1584
static const char type[]
Definition: chan_ooh323.c:109
static int request(void *obj)
Definition: chan_pjsip.c:2560
static struct hostent * hp
Definition: chan_skinny.c:1239
#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)
Custom localtime functions for multiple timezones.
Asterisk locking-related definitions:
Support for logging to various files, console and syslog Configuration in file logger....
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:337
#define AST_STRING_FIELD(name)
Declare a string field.
Definition: stringfields.h:299
String manipulation functions.
An Entity ID is essentially a MAC address, brief and unique.
Definition: utils.h:786
unsigned char eid[6]
Definition: utils.h:787
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:672
const ast_string_field uri
Definition: utils.h:672
const ast_string_field opaque
Definition: utils.h:672
const ast_string_field cnonce
Definition: utils.h:672
const ast_string_field nonce
Definition: utils.h:672
const ast_string_field username
Definition: utils.h:672
const ast_string_field realm
Definition: utils.h:672
const ast_string_field nc
Definition: utils.h:672
Domain data structure.
Definition: sip.h:881
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: main/utils.c:2996
char * ast_crypt_encrypt(const char *key)
Asterisk wrapper around crypt(3) for encrypting passwords.
Definition: crypt.c:190
void ast_unescape_quoted(char *quote_str)
Unescape quotes in a string.
Definition: main/utils.c:696
static force_inline void ast_slinear_saturated_divide_float(short *input, float *value)
Definition: utils.h:482
static force_inline void ast_slinear_saturated_subtract(short *input, short *value)
Definition: utils.h:438
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: main/utils.c:469
int ast_base64decode(unsigned char *dst, const char *src, int max)
Decode data from base64.
Definition: main/utils.c:294
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: main/utils.c:2336
unsigned int __unsigned_int_flags_dummy
int ast_file_is_readable(const char *filename)
Test that a file exists and is readable by the effective user.
Definition: main/utils.c:2855
char * ast_process_quotes_and_slashes(char *start, char find, char replace_with)
Process a string to find and replace characters.
Definition: main/utils.c:2104
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: main/utils.c:1592
#define DO_CRASH_NORETURN
Definition: utils.h:688
ast_fd_flag_operation
Definition: utils.h:991
@ AST_FD_FLAG_SET
Definition: utils.h:992
@ AST_FD_FLAG_CLEAR
Definition: utils.h:993
int __ast_fd_set_flags(int fd, int flags, enum ast_fd_flag_operation op, const char *file, int lineno, const char *function)
Definition: main/utils.c:2898
int ast_background_stacksize(void)
Definition: main/utils.c:1437
static force_inline void ast_slinear_saturated_multiply_float(short *input, float *value)
Definition: utils.h:464
char * ast_base64url_decode_string(const char *src)
Decode string from base64 URL.
Definition: main/utils.c:448
#define ast_socket_nonblock(domain, type, protocol)
Create a non-blocking socket.
Definition: utils.h:1043
char * ast_escape_quoted(const char *string, char *outbuf, int buflen)
Escape characters found in a quoted string.
Definition: main/utils.c:635
void ast_set_default_eid(struct ast_eid *eid)
Fill in an ast_eid with the default eid of this machine.
Definition: main/utils.c:2749
int ast_thread_user_interface_set(int is_user_interface)
Set the current thread's user interface status.
Definition: main/utils.c:2981
int ast_eid_cmp(const struct ast_eid *eid1, const struct ast_eid *eid2)
Compare two EIDs.
Definition: main/utils.c:2842
int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
Encode data in base64.
Definition: main/utils.c:404
static force_inline void ast_slinear_saturated_multiply(short *input, short *value)
Definition: utils.h:451
int ast_wait_for_input(int fd, int ms)
Definition: main/utils.c:1519
int ast_parse_digest(const char *digest, struct ast_http_digest *d, int request, int pedantic)
Parse digest authorization header.
Definition: main/utils.c:2390
char * ast_uri_encode(const char *string, char *outbuf, int buflen, struct ast_flags spec)
Turn text string to URI-encoded XX version.
Definition: main/utils.c:577
int ast_crypt_validate(const char *key, const char *expected)
Asterisk wrapper around crypt(3) for validating passwords.
Definition: crypt.c:136
char * ast_escape_semicolons(const char *string, char *outbuf, int buflen)
Escape semicolons found in a string.
Definition: main/utils.c:665
uint64_t __unsigned_int_flags_dummy64
int ast_get_tid(void)
Get current thread ID.
Definition: main/utils.c:2504
long int ast_random(void)
Definition: main/utils.c:2064
int ast_mkdir(const char *path, int mode)
Recursively create directory path.
Definition: main/utils.c:2231
const struct ast_flags ast_uri_http
Definition: main/utils.c:573
int ast_utils_init(void)
Definition: main/utils.c:2369
int ast_wait_for_output(int fd, int ms)
Definition: main/utils.c:1529
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:425
void ast_enable_packet_fragmentation(int sock)
Disable PMTU discovery on a socket.
Definition: main/utils.c:2221
int ast_xml_escape(const char *string, char *outbuf, size_t buflen)
Escape reserved characters for use in XML.
Definition: main/utils.c:718
int ast_base64url_decode(unsigned char *dst, const char *src, int max)
Decode data from base64 URL.
Definition: main/utils.c:427
int ast_compare_versions(const char *version1, const char *version2)
Compare 2 major.minor.patch.extra version strings.
Definition: main/utils.c:2872
void ast_register_thread(char *name)
Definition: asterisk.c:414
char * ast_eid_to_str(char *s, int maxlen, struct ast_eid *eid)
Convert an EID to a string.
Definition: main/utils.c:2587
int ast_eid_is_empty(const struct ast_eid *eid)
Check if EID is empty.
Definition: main/utils.c:2847
int ast_base64url_encode(char *dst, const unsigned char *src, int srclen, int max)
Encode data in base64 URL.
Definition: main/utils.c:516
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: main/utils.c:2552
#define ast_pipe_nonblock(filedes)
Create a non-blocking pipe.
Definition: utils.h:1060
char * ast_base64url_encode_string(const char *src)
Encode string in base64 URL.
Definition: main/utils.c:521
int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
encode text to BASE64 coding
Definition: main/utils.c:353
char * ast_base64encode_string(const char *src)
Same as ast_base64encode, but does hte math for you and returns an encoded string.
Definition: main/utils.c:410
void ast_sha1_hash_uint(uint8_t *digest, const char *input)
Produces SHA1 hash based on input string, stored in uint8_t array.
Definition: main/utils.c:282
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: main/utils.c:2540
struct hostent * ast_gethostbyname(const char *host, struct ast_hostent *hp)
Thread-safe gethostbyname function to use in Asterisk.
Definition: main/utils.c:197
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: main/utils.c:2825
void ast_uri_decode(char *s, struct ast_flags spec)
Decode URI, URN, URL (overwrite string)
Definition: main/utils.c:616
char * ast_base64decode_string(const char *src)
Same as ast_base64decode, but does the math for you and returns a decoded string.
Definition: main/utils.c:321
void ast_replace_subargument_delimiter(char *s)
Replace '^' in a string with ','.
Definition: main/utils.c:2095
void DO_CRASH_NORETURN __ast_assert_failed(int condition, const char *condition_str, const char *file, int line, const char *function)
Definition: main/utils.c:2564
const struct ast_flags ast_uri_sip_user
Definition: main/utils.c:575
void ast_md5_hash(char *output, const char *input)
Produces MD5 hash based on input string.
Definition: main/utils.c:248
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: main/utils.c:1494
void ast_sha1_hash(char *output, const char *input)
Produces SHA1 hash based on input string.
Definition: main/utils.c:264
static force_inline void ast_slinear_saturated_divide(short *input, short *value)
Definition: utils.h:477
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: main/utils.c:1446
const struct ast_flags ast_uri_http_legacy
Definition: main/utils.c:574
char * ast_utils_which(const char *binary, char *fullpath, size_t fullpath_size)
Resolve a binary to a full pathname.
Definition: main/utils.c:2522