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