utils.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2005, Digium, Inc.
  5. *
  6. * See http://www.asterisk.org for more information about
  7. * the Asterisk project. Please do not directly contact
  8. * any of the maintainers of this project for assistance;
  9. * the project provides a web site, mailing lists and IRC
  10. * channels for your use.
  11. *
  12. * This program is free software, distributed under the terms of
  13. * the GNU General Public License Version 2. See the LICENSE file
  14. * at the top of the source tree.
  15. */
  16. /*! \file
  17. *
  18. * \brief Utility functions
  19. *
  20. * \note These are important for portability and security,
  21. * so please use them in favour of other routines.
  22. * Please consult the CODING GUIDELINES for more information.
  23. */
  24. #include <ctype.h>
  25. #include <string.h>
  26. #include <unistd.h>
  27. #include <stdlib.h>
  28. #include <errno.h>
  29. #include <stdarg.h>
  30. #include <stdio.h>
  31. #include <sys/types.h>
  32. #include <sys/socket.h>
  33. #include <netinet/in.h>
  34. #include <arpa/inet.h>
  35. #include "asterisk.h"
  36. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  37. #define AST_API_MODULE
  38. #include "asterisk/lock.h"
  39. #include "asterisk/io.h"
  40. #include "asterisk/logger.h"
  41. #include "asterisk/md5.h"
  42. #include "asterisk/options.h"
  43. #include "asterisk/compat.h"
  44. #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
  45. #include "asterisk/strings.h"
  46. #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
  47. #include "asterisk/time.h"
  48. #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
  49. #include "asterisk/utils.h"
  50. static char base64[64];
  51. static char b2a[256];
  52. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined( __NetBSD__ ) || defined(__APPLE__) || defined(__CYGWIN__)
  53. /* duh? ERANGE value copied from web... */
  54. #define ERANGE 34
  55. #undef gethostbyname
  56. AST_MUTEX_DEFINE_STATIC(__mutex);
  57. /* Recursive replacement for gethostbyname for BSD-based systems. This
  58. routine is derived from code originally written and placed in the public
  59. domain by Enzo Michelangeli <em@em.no-ip.com> */
  60. static int gethostbyname_r (const char *name, struct hostent *ret, char *buf,
  61. size_t buflen, struct hostent **result,
  62. int *h_errnop)
  63. {
  64. int hsave;
  65. struct hostent *ph;
  66. ast_mutex_lock(&__mutex); /* begin critical area */
  67. hsave = h_errno;
  68. ph = gethostbyname(name);
  69. *h_errnop = h_errno; /* copy h_errno to *h_herrnop */
  70. if (ph == NULL) {
  71. *result = NULL;
  72. } else {
  73. char **p, **q;
  74. char *pbuf;
  75. int nbytes=0;
  76. int naddr=0, naliases=0;
  77. /* determine if we have enough space in buf */
  78. /* count how many addresses */
  79. for (p = ph->h_addr_list; *p != 0; p++) {
  80. nbytes += ph->h_length; /* addresses */
  81. nbytes += sizeof(*p); /* pointers */
  82. naddr++;
  83. }
  84. nbytes += sizeof(*p); /* one more for the terminating NULL */
  85. /* count how many aliases, and total length of strings */
  86. for (p = ph->h_aliases; *p != 0; p++) {
  87. nbytes += (strlen(*p)+1); /* aliases */
  88. nbytes += sizeof(*p); /* pointers */
  89. naliases++;
  90. }
  91. nbytes += sizeof(*p); /* one more for the terminating NULL */
  92. /* here nbytes is the number of bytes required in buffer */
  93. /* as a terminator must be there, the minimum value is ph->h_length */
  94. if(nbytes > buflen) {
  95. *result = NULL;
  96. ast_mutex_unlock(&__mutex); /* end critical area */
  97. return ERANGE; /* not enough space in buf!! */
  98. }
  99. /* There is enough space. Now we need to do a deep copy! */
  100. /* Allocation in buffer:
  101. from [0] to [(naddr-1) * sizeof(*p)]:
  102. pointers to addresses
  103. at [naddr * sizeof(*p)]:
  104. NULL
  105. from [(naddr+1) * sizeof(*p)] to [(naddr+naliases) * sizeof(*p)] :
  106. pointers to aliases
  107. at [(naddr+naliases+1) * sizeof(*p)]:
  108. NULL
  109. then naddr addresses (fixed length), and naliases aliases (asciiz).
  110. */
  111. *ret = *ph; /* copy whole structure (not its address!) */
  112. /* copy addresses */
  113. q = (char **)buf; /* pointer to pointers area (type: char **) */
  114. ret->h_addr_list = q; /* update pointer to address list */
  115. pbuf = buf + ((naddr+naliases+2)*sizeof(*p)); /* skip that area */
  116. for (p = ph->h_addr_list; *p != 0; p++) {
  117. memcpy(pbuf, *p, ph->h_length); /* copy address bytes */
  118. *q++ = pbuf; /* the pointer is the one inside buf... */
  119. pbuf += ph->h_length; /* advance pbuf */
  120. }
  121. *q++ = NULL; /* address list terminator */
  122. /* copy aliases */
  123. ret->h_aliases = q; /* update pointer to aliases list */
  124. for (p = ph->h_aliases; *p != 0; p++) {
  125. strcpy(pbuf, *p); /* copy alias strings */
  126. *q++ = pbuf; /* the pointer is the one inside buf... */
  127. pbuf += strlen(*p); /* advance pbuf */
  128. *pbuf++ = 0; /* string terminator */
  129. }
  130. *q++ = NULL; /* terminator */
  131. strcpy(pbuf, ph->h_name); /* copy alias strings */
  132. ret->h_name = pbuf;
  133. pbuf += strlen(ph->h_name); /* advance pbuf */
  134. *pbuf++ = 0; /* string terminator */
  135. *result = ret; /* and let *result point to structure */
  136. }
  137. h_errno = hsave; /* restore h_errno */
  138. ast_mutex_unlock(&__mutex); /* end critical area */
  139. return (*result == NULL); /* return 0 on success, non-zero on error */
  140. }
  141. #endif
  142. /*! \brief Re-entrant (thread safe) version of gethostbyname that replaces the
  143. standard gethostbyname (which is not thread safe)
  144. */
  145. struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp)
  146. {
  147. int res;
  148. int herrno;
  149. int dots=0;
  150. const char *s;
  151. struct hostent *result = NULL;
  152. /* Although it is perfectly legitimate to lookup a pure integer, for
  153. the sake of the sanity of people who like to name their peers as
  154. integers, we break with tradition and refuse to look up a
  155. pure integer */
  156. s = host;
  157. res = 0;
  158. while(s && *s) {
  159. if (*s == '.')
  160. dots++;
  161. else if (!isdigit(*s))
  162. break;
  163. s++;
  164. }
  165. if (!s || !*s) {
  166. /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
  167. if (dots != 3)
  168. return NULL;
  169. memset(hp, 0, sizeof(struct ast_hostent));
  170. hp->hp.h_addrtype = AF_INET;
  171. hp->hp.h_addr_list = (void *) hp->buf;
  172. hp->hp.h_addr = hp->buf + sizeof(void *);
  173. if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
  174. return &hp->hp;
  175. return NULL;
  176. }
  177. #ifdef SOLARIS
  178. result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);
  179. if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
  180. return NULL;
  181. #else
  182. res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
  183. if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
  184. return NULL;
  185. #endif
  186. return &hp->hp;
  187. }
  188. AST_MUTEX_DEFINE_STATIC(test_lock);
  189. AST_MUTEX_DEFINE_STATIC(test_lock2);
  190. static pthread_t test_thread;
  191. static int lock_count = 0;
  192. static int test_errors = 0;
  193. /*! \brief This is a regression test for recursive mutexes.
  194. test_for_thread_safety() will return 0 if recursive mutex locks are
  195. working properly, and non-zero if they are not working properly. */
  196. static void *test_thread_body(void *data)
  197. {
  198. ast_mutex_lock(&test_lock);
  199. lock_count += 10;
  200. if (lock_count != 10)
  201. test_errors++;
  202. ast_mutex_lock(&test_lock);
  203. lock_count += 10;
  204. if (lock_count != 20)
  205. test_errors++;
  206. ast_mutex_lock(&test_lock2);
  207. ast_mutex_unlock(&test_lock);
  208. lock_count -= 10;
  209. if (lock_count != 10)
  210. test_errors++;
  211. ast_mutex_unlock(&test_lock);
  212. lock_count -= 10;
  213. ast_mutex_unlock(&test_lock2);
  214. if (lock_count != 0)
  215. test_errors++;
  216. return NULL;
  217. }
  218. int test_for_thread_safety(void)
  219. {
  220. ast_mutex_lock(&test_lock2);
  221. ast_mutex_lock(&test_lock);
  222. lock_count += 1;
  223. ast_mutex_lock(&test_lock);
  224. lock_count += 1;
  225. ast_pthread_create(&test_thread, NULL, test_thread_body, NULL);
  226. usleep(100);
  227. if (lock_count != 2)
  228. test_errors++;
  229. ast_mutex_unlock(&test_lock);
  230. lock_count -= 1;
  231. usleep(100);
  232. if (lock_count != 1)
  233. test_errors++;
  234. ast_mutex_unlock(&test_lock);
  235. lock_count -= 1;
  236. if (lock_count != 0)
  237. test_errors++;
  238. ast_mutex_unlock(&test_lock2);
  239. usleep(100);
  240. if (lock_count != 0)
  241. test_errors++;
  242. pthread_join(test_thread, NULL);
  243. return(test_errors); /* return 0 on success. */
  244. }
  245. /*! \brief ast_md5_hash: Produce 16 char MD5 hash of value. ---*/
  246. void ast_md5_hash(char *output, char *input)
  247. {
  248. struct MD5Context md5;
  249. unsigned char digest[16];
  250. char *ptr;
  251. int x;
  252. MD5Init(&md5);
  253. MD5Update(&md5, (unsigned char *)input, strlen(input));
  254. MD5Final(digest, &md5);
  255. ptr = output;
  256. for (x=0; x<16; x++)
  257. ptr += sprintf(ptr, "%2.2x", digest[x]);
  258. }
  259. int ast_base64decode(unsigned char *dst, const char *src, int max)
  260. {
  261. int cnt = 0;
  262. unsigned int byte = 0;
  263. unsigned int bits = 0;
  264. int incnt = 0;
  265. #if 0
  266. unsigned char *odst = dst;
  267. #endif
  268. while(*src && (cnt < max)) {
  269. /* Shift in 6 bits of input */
  270. byte <<= 6;
  271. byte |= (b2a[(int)(*src)]) & 0x3f;
  272. bits += 6;
  273. #if 0
  274. printf("Add: %c %s\n", *src, binary(b2a[(int)(*src)] & 0x3f, 6));
  275. #endif
  276. src++;
  277. incnt++;
  278. /* If we have at least 8 bits left over, take that character
  279. off the top */
  280. if (bits >= 8) {
  281. bits -= 8;
  282. *dst = (byte >> bits) & 0xff;
  283. #if 0
  284. printf("Remove: %02x %s\n", *dst, binary(*dst, 8));
  285. #endif
  286. dst++;
  287. cnt++;
  288. }
  289. }
  290. #if 0
  291. dump(odst, cnt);
  292. #endif
  293. /* Dont worry about left over bits, they're extra anyway */
  294. return cnt;
  295. }
  296. int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
  297. {
  298. int cnt = 0;
  299. unsigned int byte = 0;
  300. int bits = 0;
  301. int index;
  302. int cntin = 0;
  303. #if 0
  304. char *odst = dst;
  305. dump(src, srclen);
  306. #endif
  307. /* Reserve one bit for end */
  308. max--;
  309. while((cntin < srclen) && (cnt < max)) {
  310. byte <<= 8;
  311. #if 0
  312. printf("Add: %02x %s\n", *src, binary(*src, 8));
  313. #endif
  314. byte |= *(src++);
  315. bits += 8;
  316. cntin++;
  317. while((bits >= 6) && (cnt < max)) {
  318. bits -= 6;
  319. /* We want only the top */
  320. index = (byte >> bits) & 0x3f;
  321. *dst = base64[index];
  322. #if 0
  323. printf("Remove: %c %s\n", *dst, binary(index, 6));
  324. #endif
  325. dst++;
  326. cnt++;
  327. }
  328. }
  329. if (bits && (cnt < max)) {
  330. /* Add one last character for the remaining bits,
  331. padding the rest with 0 */
  332. byte <<= (6 - bits);
  333. index = (byte) & 0x3f;
  334. *(dst++) = base64[index];
  335. cnt++;
  336. }
  337. *dst = '\0';
  338. return cnt;
  339. }
  340. static void base64_init(void)
  341. {
  342. int x;
  343. memset(b2a, -1, sizeof(b2a));
  344. /* Initialize base-64 Conversion table */
  345. for (x=0;x<26;x++) {
  346. /* A-Z */
  347. base64[x] = 'A' + x;
  348. b2a['A' + x] = x;
  349. /* a-z */
  350. base64[x + 26] = 'a' + x;
  351. b2a['a' + x] = x + 26;
  352. /* 0-9 */
  353. if (x < 10) {
  354. base64[x + 52] = '0' + x;
  355. b2a['0' + x] = x + 52;
  356. }
  357. }
  358. base64[62] = '+';
  359. base64[63] = '/';
  360. b2a[(int)'+'] = 62;
  361. b2a[(int)'/'] = 63;
  362. }
  363. /*! \brief ast_uri_encode: Turn text string to URI-encoded %XX version ---*/
  364. /* At this point, we're converting from ISO-8859-x (8-bit), not UTF8
  365. as in the SIP protocol spec
  366. If doreserved == 1 we will convert reserved characters also.
  367. RFC 2396, section 2.4
  368. outbuf needs to have more memory allocated than the instring
  369. to have room for the expansion. Every char that is converted
  370. is replaced by three ASCII characters.
  371. Note: The doreserved option is needed for replaces header in
  372. SIP transfers.
  373. */
  374. char *ast_uri_encode(char *string, char *outbuf, int buflen, int doreserved)
  375. {
  376. char *reserved = ";/?:@&=+$, "; /* Reserved chars */
  377. char *ptr = string; /* Start with the string */
  378. char *out = NULL;
  379. char *buf = NULL;
  380. strncpy(outbuf, string, buflen);
  381. /* If there's no characters to convert, just go through and don't do anything */
  382. while (*ptr) {
  383. if (((unsigned char) *ptr) > 127 || (doreserved && strchr(reserved, *ptr)) ) {
  384. /* Oops, we need to start working here */
  385. if (!buf) {
  386. buf = outbuf;
  387. out = buf + (ptr - string) ; /* Set output ptr */
  388. }
  389. out += sprintf(out, "%%%02x", (unsigned char) *ptr);
  390. } else if (buf) {
  391. *out = *ptr; /* Continue copying the string */
  392. out++;
  393. }
  394. ptr++;
  395. }
  396. if (buf)
  397. *out = '\0';
  398. return outbuf;
  399. }
  400. /*! \brief ast_uri_decode: Decode SIP URI, URN, URL (overwrite the string) ---*/
  401. void ast_uri_decode(char *s)
  402. {
  403. char *o;
  404. unsigned int tmp;
  405. for (o = s; *s; s++, o++) {
  406. if (*s == '%' && strlen(s) > 2 && sscanf(s + 1, "%2x", &tmp) == 1) {
  407. /* have '%', two chars and correct parsing */
  408. *o = tmp;
  409. s += 2; /* Will be incremented once more when we break out */
  410. } else /* all other cases, just copy */
  411. *o = *s;
  412. }
  413. *o = '\0';
  414. }
  415. /*! \brief ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa */
  416. const char *ast_inet_ntoa(char *buf, int bufsiz, struct in_addr ia)
  417. {
  418. return inet_ntop(AF_INET, &ia, buf, bufsiz);
  419. }
  420. int ast_utils_init(void)
  421. {
  422. base64_init();
  423. return 0;
  424. }
  425. #ifndef __linux__
  426. #undef pthread_create /* For ast_pthread_create function only */
  427. #endif /* !__linux__ */
  428. int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize)
  429. {
  430. pthread_attr_t lattr;
  431. if (!attr) {
  432. pthread_attr_init(&lattr);
  433. attr = &lattr;
  434. }
  435. #ifdef __linux__
  436. /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
  437. which is kind of useless. Change this here to
  438. PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
  439. priority will propagate down to new threads by default.
  440. This does mean that callers cannot set a different priority using
  441. PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
  442. the priority afterwards with pthread_setschedparam(). */
  443. errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED);
  444. if (errno)
  445. ast_log(LOG_WARNING, "pthread_attr_setinheritsched returned non-zero: %s\n", strerror(errno));
  446. #endif
  447. if (!stacksize)
  448. stacksize = AST_STACKSIZE;
  449. errno = pthread_attr_setstacksize(attr, stacksize);
  450. if (errno)
  451. ast_log(LOG_WARNING, "pthread_attr_setstacksize returned non-zero: %s\n", strerror(errno));
  452. return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
  453. }
  454. int ast_wait_for_input(int fd, int ms)
  455. {
  456. struct pollfd pfd[1];
  457. memset(pfd, 0, sizeof(pfd));
  458. pfd[0].fd = fd;
  459. pfd[0].events = POLLIN|POLLPRI;
  460. return poll(pfd, 1, ms);
  461. }
  462. char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
  463. {
  464. char *e;
  465. char *q;
  466. s = ast_strip(s);
  467. if ((q = strchr(beg_quotes, *s)) && *q != '\0') {
  468. e = s + strlen(s) - 1;
  469. if (*e == *(end_quotes + (q - beg_quotes))) {
  470. s++;
  471. *e = '\0';
  472. }
  473. }
  474. return s;
  475. }
  476. int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap)
  477. {
  478. int result;
  479. if (!buffer || !*buffer || !space || !*space)
  480. return -1;
  481. result = vsnprintf(*buffer, *space, fmt, ap);
  482. if (result < 0)
  483. return -1;
  484. else if (result > *space)
  485. result = *space;
  486. *buffer += result;
  487. *space -= result;
  488. return 0;
  489. }
  490. int ast_build_string(char **buffer, size_t *space, const char *fmt, ...)
  491. {
  492. va_list ap;
  493. int result;
  494. va_start(ap, fmt);
  495. result = ast_build_string_va(buffer, space, fmt, ap);
  496. va_end(ap);
  497. return result;
  498. }
  499. int ast_true(const char *s)
  500. {
  501. if (ast_strlen_zero(s))
  502. return 0;
  503. /* Determine if this is a true value */
  504. if (!strcasecmp(s, "yes") ||
  505. !strcasecmp(s, "true") ||
  506. !strcasecmp(s, "y") ||
  507. !strcasecmp(s, "t") ||
  508. !strcasecmp(s, "1") ||
  509. !strcasecmp(s, "on"))
  510. return -1;
  511. return 0;
  512. }
  513. int ast_false(const char *s)
  514. {
  515. if (ast_strlen_zero(s))
  516. return 0;
  517. /* Determine if this is a false value */
  518. if (!strcasecmp(s, "no") ||
  519. !strcasecmp(s, "false") ||
  520. !strcasecmp(s, "n") ||
  521. !strcasecmp(s, "f") ||
  522. !strcasecmp(s, "0") ||
  523. !strcasecmp(s, "off"))
  524. return -1;
  525. return 0;
  526. }
  527. #define ONE_MILLION 1000000
  528. /*
  529. * put timeval in a valid range. usec is 0..999999
  530. * negative values are not allowed and truncated.
  531. */
  532. static struct timeval tvfix(struct timeval a)
  533. {
  534. if (a.tv_usec >= ONE_MILLION) {
  535. ast_log(LOG_WARNING, "warning too large timestamp %ld.%ld\n",
  536. a.tv_sec, (long int) a.tv_usec);
  537. a.tv_sec += a.tv_usec / ONE_MILLION;
  538. a.tv_usec %= ONE_MILLION;
  539. } else if (a.tv_usec < 0) {
  540. ast_log(LOG_WARNING, "warning negative timestamp %ld.%ld\n",
  541. a.tv_sec, (long int) a.tv_usec);
  542. a.tv_usec = 0;
  543. }
  544. return a;
  545. }
  546. struct timeval ast_tvadd(struct timeval a, struct timeval b)
  547. {
  548. /* consistency checks to guarantee usec in 0..999999 */
  549. a = tvfix(a);
  550. b = tvfix(b);
  551. a.tv_sec += b.tv_sec;
  552. a.tv_usec += b.tv_usec;
  553. if (a.tv_usec >= ONE_MILLION) {
  554. a.tv_sec++;
  555. a.tv_usec -= ONE_MILLION;
  556. }
  557. return a;
  558. }
  559. struct timeval ast_tvsub(struct timeval a, struct timeval b)
  560. {
  561. /* consistency checks to guarantee usec in 0..999999 */
  562. a = tvfix(a);
  563. b = tvfix(b);
  564. a.tv_sec -= b.tv_sec;
  565. a.tv_usec -= b.tv_usec;
  566. if (a.tv_usec < 0) {
  567. a.tv_sec-- ;
  568. a.tv_usec += ONE_MILLION;
  569. }
  570. return a;
  571. }
  572. #undef ONE_MILLION
  573. #ifndef HAVE_STRCASESTR
  574. static char *upper(const char *orig, char *buf, int bufsize)
  575. {
  576. int i = 0;
  577. while (i < (bufsize - 1) && orig[i]) {
  578. buf[i] = toupper(orig[i]);
  579. i++;
  580. }
  581. buf[i] = '\0';
  582. return buf;
  583. }
  584. char *strcasestr(const char *haystack, const char *needle)
  585. {
  586. char *u1, *u2;
  587. int u1len = strlen(haystack) + 1, u2len = strlen(needle) + 1;
  588. u1 = alloca(u1len);
  589. u2 = alloca(u2len);
  590. if (u1 && u2) {
  591. char *offset;
  592. if (u2len > u1len) {
  593. /* Needle bigger than haystack */
  594. return NULL;
  595. }
  596. offset = strstr(upper(haystack, u1, u1len), upper(needle, u2, u2len));
  597. if (offset) {
  598. /* Return the offset into the original string */
  599. return ((char *)((unsigned long)haystack + (unsigned long)(offset - u1)));
  600. } else {
  601. return NULL;
  602. }
  603. } else {
  604. ast_log(LOG_ERROR, "Out of memory\n");
  605. return NULL;
  606. }
  607. }
  608. #endif /* !HAVE_STRCASESTR */
  609. #ifndef HAVE_STRNLEN
  610. size_t strnlen(const char *s, size_t n)
  611. {
  612. size_t len;
  613. for (len=0; len < n; len++)
  614. if (s[len] == '\0')
  615. break;
  616. return len;
  617. }
  618. #endif /* !HAVE_STRNLEN */
  619. #if !defined(HAVE_STRNDUP) && !defined(__AST_DEBUG_MALLOC)
  620. char *strndup(const char *s, size_t n)
  621. {
  622. size_t len = strnlen(s, n);
  623. char *new = malloc(len + 1);
  624. if (!new)
  625. return NULL;
  626. new[len] = '\0';
  627. return memcpy(new, s, len);
  628. }
  629. #endif /* !defined(HAVE_STRNDUP) && !defined(__AST_DEBUG_MALLOC) */
  630. #if !defined(HAVE_VASPRINTF) && !defined(__AST_DEBUG_MALLOC)
  631. int vasprintf(char **strp, const char *fmt, va_list ap)
  632. {
  633. int size;
  634. va_list ap2;
  635. char s;
  636. *strp = NULL;
  637. va_copy(ap2, ap);
  638. size = vsnprintf(&s, 1, fmt, ap2);
  639. va_end(ap2);
  640. *strp = malloc(size + 1);
  641. if (!*strp)
  642. return -1;
  643. vsnprintf(*strp, size + 1, fmt, ap);
  644. return size;
  645. }
  646. #endif /* !defined(HAVE_VASPRINTF) && !defined(__AST_DEBUG_MALLOC) */
  647. #ifndef HAVE_STRTOQ
  648. #ifndef LONG_MIN
  649. #define LONG_MIN (-9223372036854775807L-1L)
  650. /* min value of a "long int" */
  651. #endif
  652. #ifndef LONG_MAX
  653. #define LONG_MAX 9223372036854775807L
  654. /* max value of a "long int" */
  655. #endif
  656. /*
  657. * Convert a string to a quad integer.
  658. *
  659. * Ignores `locale' stuff. Assumes that the upper and lower case
  660. * alphabets and digits are each contiguous.
  661. */
  662. uint64_t strtoq(const char *nptr, char **endptr, int base)
  663. {
  664. const char *s;
  665. uint64_t acc;
  666. unsigned char c;
  667. uint64_t qbase, cutoff;
  668. int neg, any, cutlim;
  669. /*
  670. * Skip white space and pick up leading +/- sign if any.
  671. * If base is 0, allow 0x for hex and 0 for octal, else
  672. * assume decimal; if base is already 16, allow 0x.
  673. */
  674. s = nptr;
  675. do {
  676. c = *s++;
  677. } while (isspace(c));
  678. if (c == '-') {
  679. neg = 1;
  680. c = *s++;
  681. } else {
  682. neg = 0;
  683. if (c == '+')
  684. c = *s++;
  685. }
  686. if ((base == 0 || base == 16) &&
  687. c == '\0' && (*s == 'x' || *s == 'X')) {
  688. c = s[1];
  689. s += 2;
  690. base = 16;
  691. }
  692. if (base == 0)
  693. base = c == '\0' ? 8 : 10;
  694. /*
  695. * Compute the cutoff value between legal numbers and illegal
  696. * numbers. That is the largest legal value, divided by the
  697. * base. An input number that is greater than this value, if
  698. * followed by a legal input character, is too big. One that
  699. * is equal to this value may be valid or not; the limit
  700. * between valid and invalid numbers is then based on the last
  701. * digit. For instance, if the range for quads is
  702. * [-9223372036854775808..9223372036854775807] and the input base
  703. * is 10, cutoff will be set to 922337203685477580 and cutlim to
  704. * either 7 (neg==0) or 8 (neg==1), meaning that if we have
  705. * accumulated a value > 922337203685477580, or equal but the
  706. * next digit is > 7 (or 8), the number is too big, and we will
  707. * return a range error.
  708. *
  709. * Set any if any `digits' consumed; make it negative to indicate
  710. * overflow.
  711. */
  712. qbase = (unsigned)base;
  713. cutoff = neg ? (uint64_t)-(LONG_MIN + LONG_MAX) + LONG_MAX : LONG_MAX;
  714. cutlim = cutoff % qbase;
  715. cutoff /= qbase;
  716. for (acc = 0, any = 0;; c = *s++) {
  717. if (!isascii(c))
  718. break;
  719. if (isdigit(c))
  720. c -= '\0';
  721. else if (isalpha(c))
  722. c -= isupper(c) ? 'A' - 10 : 'a' - 10;
  723. else
  724. break;
  725. if (c >= base)
  726. break;
  727. if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
  728. any = -1;
  729. else {
  730. any = 1;
  731. acc *= qbase;
  732. acc += c;
  733. }
  734. }
  735. if (any < 0) {
  736. acc = neg ? LONG_MIN : LONG_MAX;
  737. } else if (neg)
  738. acc = -acc;
  739. if (endptr != 0)
  740. *((const char **)endptr) = any ? s - 1 : nptr;
  741. return acc;
  742. }
  743. #endif /* !HAVE_STRTOQ */
  744. #ifndef HAVE_GETLOADAVG
  745. #ifdef linux
  746. /* Alternative method of getting load avg on Linux only */
  747. int getloadavg(double *list, int nelem)
  748. {
  749. FILE *LOADAVG;
  750. double avg[3] = { 0.0, 0.0, 0.0 };
  751. int i, res = -1;
  752. if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
  753. fscanf(LOADAVG, "%lf %lf %lf", &avg[0], &avg[1], &avg[2]);
  754. res = 0;
  755. fclose(LOADAVG);
  756. }
  757. for (i = 0; (i < nelem) && (i < 3); i++) {
  758. list[i] = avg[i];
  759. }
  760. return res;
  761. }
  762. #else /* !linux */
  763. /* Return something that won't cancel the call, but still return -1, in case
  764. * we correct the implementation to check return value */
  765. int getloadavg(double *list, int nelem)
  766. {
  767. int i;
  768. for (i = 0; i < nelem; i++) {
  769. list[i] = 0.1;
  770. }
  771. return -1;
  772. }
  773. #endif /* linux */
  774. #endif /* !defined(_BSD_SOURCE) */
  775. char *ast_process_quotes_and_slashes(char *start, char find, char replace_with)
  776. {
  777. char *dataPut = start;
  778. int inEscape = 0;
  779. int inQuotes = 0;
  780. for (; *start; start++) {
  781. if (inEscape) {
  782. *dataPut++ = *start; /* Always goes verbatim */
  783. inEscape = 0;
  784. } else {
  785. if (*start == '\\') {
  786. inEscape = 1; /* Do not copy \ into the data */
  787. } else if (*start == '\'') {
  788. inQuotes = 1-inQuotes; /* Do not copy ' into the data */
  789. } else {
  790. /* Replace , with |, unless in quotes */
  791. *dataPut++ = inQuotes ? *start : ((*start==find) ? replace_with : *start);
  792. }
  793. }
  794. }
  795. if (start != dataPut)
  796. *dataPut = 0;
  797. return dataPut;
  798. }
  799. void ast_enable_packet_fragmentation(int sock)
  800. {
  801. #ifdef __linux__
  802. int val = IP_PMTUDISC_DONT;
  803. if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
  804. ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
  805. #endif
  806. }
  807. AST_MUTEX_DEFINE_STATIC(fetchadd_m); /* used for all fetc&add ops */
  808. int ast_atomic_fetchadd_int_slow(volatile int *p, int v)
  809. {
  810. int ret;
  811. ast_mutex_lock(&fetchadd_m);
  812. ret = *p;
  813. *p += v;
  814. ast_mutex_unlock(&fetchadd_m);
  815. return ret;
  816. }