utils.c 22 KB

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