utils.h 37 KB

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