utils.c 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2006, 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. /*** MODULEINFO
  25. <support_level>core</support_level>
  26. ***/
  27. #include "asterisk.h"
  28. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  29. #include <ctype.h>
  30. #include <fcntl.h>
  31. #include <sys/stat.h>
  32. #include <sys/syscall.h>
  33. #include <unistd.h>
  34. #if defined(__APPLE__)
  35. #include <mach/mach.h>
  36. #elif defined(HAVE_SYS_THR_H)
  37. #include <sys/thr.h>
  38. #endif
  39. #include "asterisk/network.h"
  40. #include "asterisk/ast_version.h"
  41. #define AST_API_MODULE /* ensure that inlinable API functions will be built in lock.h if required */
  42. #include "asterisk/lock.h"
  43. #include "asterisk/io.h"
  44. #include "asterisk/md5.h"
  45. #include "asterisk/sha1.h"
  46. #include "asterisk/cli.h"
  47. #include "asterisk/linkedlists.h"
  48. #include "asterisk/astobj2.h"
  49. #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
  50. #include "asterisk/strings.h"
  51. #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
  52. #include "asterisk/time.h"
  53. #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
  54. #include "asterisk/stringfields.h"
  55. #define AST_API_MODULE /* ensure that inlinable API functions will be built in this module if required */
  56. #include "asterisk/utils.h"
  57. #define AST_API_MODULE
  58. #include "asterisk/threadstorage.h"
  59. #define AST_API_MODULE
  60. #include "asterisk/config.h"
  61. static char base64[64];
  62. static char b2a[256];
  63. /* This is for binary compatibility with modules built before
  64. * ast_log_safe existed. */
  65. #define _AST_MEM_BACKTRACE_BUFLEN 60
  66. void *_ast_mem_backtrace_buffer[_AST_MEM_BACKTRACE_BUFLEN];
  67. AST_THREADSTORAGE(inet_ntoa_buf);
  68. #if !defined(HAVE_GETHOSTBYNAME_R_5) && !defined(HAVE_GETHOSTBYNAME_R_6)
  69. #define ERANGE 34 /*!< duh? ERANGE value copied from web... */
  70. #undef gethostbyname
  71. AST_MUTEX_DEFINE_STATIC(__mutex);
  72. /*! \brief Reentrant replacement for gethostbyname for BSD-based systems.
  73. \note This
  74. routine is derived from code originally written and placed in the public
  75. domain by Enzo Michelangeli <em@em.no-ip.com> */
  76. static int gethostbyname_r (const char *name, struct hostent *ret, char *buf,
  77. size_t buflen, struct hostent **result,
  78. int *h_errnop)
  79. {
  80. int hsave;
  81. struct hostent *ph;
  82. ast_mutex_lock(&__mutex); /* begin critical area */
  83. hsave = h_errno;
  84. ph = gethostbyname(name);
  85. *h_errnop = h_errno; /* copy h_errno to *h_herrnop */
  86. if (ph == NULL) {
  87. *result = NULL;
  88. } else {
  89. char **p, **q;
  90. char *pbuf;
  91. int nbytes = 0;
  92. int naddr = 0, naliases = 0;
  93. /* determine if we have enough space in buf */
  94. /* count how many addresses */
  95. for (p = ph->h_addr_list; *p != 0; p++) {
  96. nbytes += ph->h_length; /* addresses */
  97. nbytes += sizeof(*p); /* pointers */
  98. naddr++;
  99. }
  100. nbytes += sizeof(*p); /* one more for the terminating NULL */
  101. /* count how many aliases, and total length of strings */
  102. for (p = ph->h_aliases; *p != 0; p++) {
  103. nbytes += (strlen(*p)+1); /* aliases */
  104. nbytes += sizeof(*p); /* pointers */
  105. naliases++;
  106. }
  107. nbytes += sizeof(*p); /* one more for the terminating NULL */
  108. /* here nbytes is the number of bytes required in buffer */
  109. /* as a terminator must be there, the minimum value is ph->h_length */
  110. if (nbytes > buflen) {
  111. *result = NULL;
  112. ast_mutex_unlock(&__mutex); /* end critical area */
  113. return ERANGE; /* not enough space in buf!! */
  114. }
  115. /* There is enough space. Now we need to do a deep copy! */
  116. /* Allocation in buffer:
  117. from [0] to [(naddr-1) * sizeof(*p)]:
  118. pointers to addresses
  119. at [naddr * sizeof(*p)]:
  120. NULL
  121. from [(naddr+1) * sizeof(*p)] to [(naddr+naliases) * sizeof(*p)] :
  122. pointers to aliases
  123. at [(naddr+naliases+1) * sizeof(*p)]:
  124. NULL
  125. then naddr addresses (fixed length), and naliases aliases (asciiz).
  126. */
  127. *ret = *ph; /* copy whole structure (not its address!) */
  128. /* copy addresses */
  129. q = (char **)buf; /* pointer to pointers area (type: char **) */
  130. ret->h_addr_list = q; /* update pointer to address list */
  131. pbuf = buf + ((naddr + naliases + 2) * sizeof(*p)); /* skip that area */
  132. for (p = ph->h_addr_list; *p != 0; p++) {
  133. memcpy(pbuf, *p, ph->h_length); /* copy address bytes */
  134. *q++ = pbuf; /* the pointer is the one inside buf... */
  135. pbuf += ph->h_length; /* advance pbuf */
  136. }
  137. *q++ = NULL; /* address list terminator */
  138. /* copy aliases */
  139. ret->h_aliases = q; /* update pointer to aliases list */
  140. for (p = ph->h_aliases; *p != 0; p++) {
  141. strcpy(pbuf, *p); /* copy alias strings */
  142. *q++ = pbuf; /* the pointer is the one inside buf... */
  143. pbuf += strlen(*p); /* advance pbuf */
  144. *pbuf++ = 0; /* string terminator */
  145. }
  146. *q++ = NULL; /* terminator */
  147. strcpy(pbuf, ph->h_name); /* copy alias strings */
  148. ret->h_name = pbuf;
  149. pbuf += strlen(ph->h_name); /* advance pbuf */
  150. *pbuf++ = 0; /* string terminator */
  151. *result = ret; /* and let *result point to structure */
  152. }
  153. h_errno = hsave; /* restore h_errno */
  154. ast_mutex_unlock(&__mutex); /* end critical area */
  155. return (*result == NULL); /* return 0 on success, non-zero on error */
  156. }
  157. #endif
  158. /*! \brief Re-entrant (thread safe) version of gethostbyname that replaces the
  159. standard gethostbyname (which is not thread safe)
  160. */
  161. struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp)
  162. {
  163. int res;
  164. int herrno;
  165. int dots = 0;
  166. const char *s;
  167. struct hostent *result = NULL;
  168. /* Although it is perfectly legitimate to lookup a pure integer, for
  169. the sake of the sanity of people who like to name their peers as
  170. integers, we break with tradition and refuse to look up a
  171. pure integer */
  172. s = host;
  173. res = 0;
  174. while (s && *s) {
  175. if (*s == '.')
  176. dots++;
  177. else if (!isdigit(*s))
  178. break;
  179. s++;
  180. }
  181. if (!s || !*s) {
  182. /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
  183. if (dots != 3)
  184. return NULL;
  185. memset(hp, 0, sizeof(struct ast_hostent));
  186. hp->hp.h_addrtype = AF_INET;
  187. hp->hp.h_addr_list = (void *) hp->buf;
  188. hp->hp.h_addr = hp->buf + sizeof(void *);
  189. /* For AF_INET, this will always be 4 */
  190. hp->hp.h_length = 4;
  191. if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
  192. return &hp->hp;
  193. return NULL;
  194. }
  195. #ifdef HAVE_GETHOSTBYNAME_R_5
  196. result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);
  197. if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
  198. return NULL;
  199. #else
  200. res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
  201. if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
  202. return NULL;
  203. #endif
  204. return &hp->hp;
  205. }
  206. /*! \brief Produce 32 char MD5 hash of value. */
  207. void ast_md5_hash(char *output, const char *input)
  208. {
  209. struct MD5Context md5;
  210. unsigned char digest[16];
  211. char *ptr;
  212. int x;
  213. MD5Init(&md5);
  214. MD5Update(&md5, (const unsigned char *) input, strlen(input));
  215. MD5Final(digest, &md5);
  216. ptr = output;
  217. for (x = 0; x < 16; x++)
  218. ptr += sprintf(ptr, "%02hhx", digest[x]);
  219. }
  220. /*! \brief Produce 40 char SHA1 hash of value. */
  221. void ast_sha1_hash(char *output, const char *input)
  222. {
  223. struct SHA1Context sha;
  224. char *ptr;
  225. int x;
  226. uint8_t Message_Digest[20];
  227. SHA1Reset(&sha);
  228. SHA1Input(&sha, (const unsigned char *) input, strlen(input));
  229. SHA1Result(&sha, Message_Digest);
  230. ptr = output;
  231. for (x = 0; x < 20; x++)
  232. ptr += sprintf(ptr, "%02hhx", Message_Digest[x]);
  233. }
  234. /*! \brief Produce a 20 byte SHA1 hash of value. */
  235. void ast_sha1_hash_uint(uint8_t *digest, const char *input)
  236. {
  237. struct SHA1Context sha;
  238. SHA1Reset(&sha);
  239. SHA1Input(&sha, (const unsigned char *) input, strlen(input));
  240. SHA1Result(&sha, digest);
  241. }
  242. /*! \brief decode BASE64 encoded text */
  243. int ast_base64decode(unsigned char *dst, const char *src, int max)
  244. {
  245. int cnt = 0;
  246. unsigned int byte = 0;
  247. unsigned int bits = 0;
  248. int incnt = 0;
  249. while(*src && *src != '=' && (cnt < max)) {
  250. /* Shift in 6 bits of input */
  251. byte <<= 6;
  252. byte |= (b2a[(int)(*src)]) & 0x3f;
  253. bits += 6;
  254. src++;
  255. incnt++;
  256. /* If we have at least 8 bits left over, take that character
  257. off the top */
  258. if (bits >= 8) {
  259. bits -= 8;
  260. *dst = (byte >> bits) & 0xff;
  261. dst++;
  262. cnt++;
  263. }
  264. }
  265. /* Don't worry about left over bits, they're extra anyway */
  266. return cnt;
  267. }
  268. /*! \brief encode text to BASE64 coding */
  269. int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
  270. {
  271. int cnt = 0;
  272. int col = 0;
  273. unsigned int byte = 0;
  274. int bits = 0;
  275. int cntin = 0;
  276. /* Reserve space for null byte at end of string */
  277. max--;
  278. while ((cntin < srclen) && (cnt < max)) {
  279. byte <<= 8;
  280. byte |= *(src++);
  281. bits += 8;
  282. cntin++;
  283. if ((bits == 24) && (cnt + 4 <= max)) {
  284. *dst++ = base64[(byte >> 18) & 0x3f];
  285. *dst++ = base64[(byte >> 12) & 0x3f];
  286. *dst++ = base64[(byte >> 6) & 0x3f];
  287. *dst++ = base64[byte & 0x3f];
  288. cnt += 4;
  289. col += 4;
  290. bits = 0;
  291. byte = 0;
  292. }
  293. if (linebreaks && (cnt < max) && (col == 64)) {
  294. *dst++ = '\n';
  295. cnt++;
  296. col = 0;
  297. }
  298. }
  299. if (bits && (cnt + 4 <= max)) {
  300. /* Add one last character for the remaining bits,
  301. padding the rest with 0 */
  302. byte <<= 24 - bits;
  303. *dst++ = base64[(byte >> 18) & 0x3f];
  304. *dst++ = base64[(byte >> 12) & 0x3f];
  305. if (bits == 16)
  306. *dst++ = base64[(byte >> 6) & 0x3f];
  307. else
  308. *dst++ = '=';
  309. *dst++ = '=';
  310. cnt += 4;
  311. }
  312. if (linebreaks && (cnt < max)) {
  313. *dst++ = '\n';
  314. cnt++;
  315. }
  316. *dst = '\0';
  317. return cnt;
  318. }
  319. int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
  320. {
  321. return ast_base64encode_full(dst, src, srclen, max, 0);
  322. }
  323. static void base64_init(void)
  324. {
  325. int x;
  326. memset(b2a, -1, sizeof(b2a));
  327. /* Initialize base-64 Conversion table */
  328. for (x = 0; x < 26; x++) {
  329. /* A-Z */
  330. base64[x] = 'A' + x;
  331. b2a['A' + x] = x;
  332. /* a-z */
  333. base64[x + 26] = 'a' + x;
  334. b2a['a' + x] = x + 26;
  335. /* 0-9 */
  336. if (x < 10) {
  337. base64[x + 52] = '0' + x;
  338. b2a['0' + x] = x + 52;
  339. }
  340. }
  341. base64[62] = '+';
  342. base64[63] = '/';
  343. b2a[(int)'+'] = 62;
  344. b2a[(int)'/'] = 63;
  345. }
  346. const struct ast_flags ast_uri_http = {AST_URI_UNRESERVED};
  347. const struct ast_flags ast_uri_http_legacy = {AST_URI_LEGACY_SPACE | AST_URI_UNRESERVED};
  348. const struct ast_flags ast_uri_sip_user = {AST_URI_UNRESERVED | AST_URI_SIP_USER_UNRESERVED};
  349. char *ast_uri_encode(const char *string, char *outbuf, int buflen, struct ast_flags spec)
  350. {
  351. const char *ptr = string; /* Start with the string */
  352. char *out = outbuf;
  353. const char *mark = "-_.!~*'()"; /* no encode set, RFC 2396 section 2.3, RFC 3261 sec 25 */
  354. const char *user_unreserved = "&=+$,;?/"; /* user-unreserved set, RFC 3261 sec 25 */
  355. while (*ptr && out - outbuf < buflen - 1) {
  356. if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *ptr == ' ') {
  357. /* for legacy encoding, encode spaces as '+' */
  358. *out = '+';
  359. out++;
  360. } else if (!(ast_test_flag(&spec, AST_URI_MARK)
  361. && strchr(mark, *ptr))
  362. && !(ast_test_flag(&spec, AST_URI_ALPHANUM)
  363. && ((*ptr >= '0' && *ptr <= '9')
  364. || (*ptr >= 'A' && *ptr <= 'Z')
  365. || (*ptr >= 'a' && *ptr <= 'z')))
  366. && !(ast_test_flag(&spec, AST_URI_SIP_USER_UNRESERVED)
  367. && strchr(user_unreserved, *ptr))) {
  368. if (out - outbuf >= buflen - 3) {
  369. break;
  370. }
  371. out += sprintf(out, "%%%02hhX", (unsigned char) *ptr);
  372. } else {
  373. *out = *ptr; /* Continue copying the string */
  374. out++;
  375. }
  376. ptr++;
  377. }
  378. if (buflen) {
  379. *out = '\0';
  380. }
  381. return outbuf;
  382. }
  383. void ast_uri_decode(char *s, struct ast_flags spec)
  384. {
  385. char *o;
  386. unsigned int tmp;
  387. for (o = s; *s; s++, o++) {
  388. if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *s == '+') {
  389. /* legacy mode, decode '+' as space */
  390. *o = ' ';
  391. } else if (*s == '%' && s[1] != '\0' && s[2] != '\0' && sscanf(s + 1, "%2x", &tmp) == 1) {
  392. /* have '%', two chars and correct parsing */
  393. *o = tmp;
  394. s += 2; /* Will be incremented once more when we break out */
  395. } else /* all other cases, just copy */
  396. *o = *s;
  397. }
  398. *o = '\0';
  399. }
  400. char *ast_escape_quoted(const char *string, char *outbuf, int buflen)
  401. {
  402. const char *ptr = string;
  403. char *out = outbuf;
  404. char *allow = "\t\v !"; /* allow LWS (minus \r and \n) and "!" */
  405. while (*ptr && out - outbuf < buflen - 1) {
  406. if (!(strchr(allow, *ptr))
  407. && !(*ptr >= '#' && *ptr <= '[') /* %x23 - %x5b */
  408. && !(*ptr >= ']' && *ptr <= '~') /* %x5d - %x7e */
  409. && !((unsigned char) *ptr > 0x7f)) { /* UTF8-nonascii */
  410. if (out - outbuf >= buflen - 2) {
  411. break;
  412. }
  413. out += sprintf(out, "\\%c", (unsigned char) *ptr);
  414. } else {
  415. *out = *ptr;
  416. out++;
  417. }
  418. ptr++;
  419. }
  420. if (buflen) {
  421. *out = '\0';
  422. }
  423. return outbuf;
  424. }
  425. char *ast_escape_semicolons(const char *string, char *outbuf, int buflen)
  426. {
  427. const char *ptr = string;
  428. char *out = outbuf;
  429. if (string == NULL || outbuf == NULL) {
  430. ast_assert(string != NULL && outbuf != NULL);
  431. return NULL;
  432. }
  433. while (*ptr && out - outbuf < buflen - 1) {
  434. if (*ptr == ';') {
  435. if (out - outbuf >= buflen - 2) {
  436. break;
  437. }
  438. strcpy(out, "\\;");
  439. out += 2;
  440. } else {
  441. *out = *ptr;
  442. out++;
  443. }
  444. ptr++;
  445. }
  446. if (buflen) {
  447. *out = '\0';
  448. }
  449. return outbuf;
  450. }
  451. void ast_unescape_quoted(char *quote_str)
  452. {
  453. int esc_pos;
  454. int unesc_pos;
  455. int quote_str_len = strlen(quote_str);
  456. for (esc_pos = 0, unesc_pos = 0;
  457. esc_pos < quote_str_len;
  458. esc_pos++, unesc_pos++) {
  459. if (quote_str[esc_pos] == '\\') {
  460. /* at least one more char and current is \\ */
  461. esc_pos++;
  462. if (esc_pos >= quote_str_len) {
  463. break;
  464. }
  465. }
  466. quote_str[unesc_pos] = quote_str[esc_pos];
  467. }
  468. quote_str[unesc_pos] = '\0';
  469. }
  470. int ast_xml_escape(const char *string, char * const outbuf, const size_t buflen)
  471. {
  472. char *dst = outbuf;
  473. char *end = outbuf + buflen - 1; /* save one for the null terminator */
  474. /* Handle the case for the empty output buffer */
  475. if (buflen == 0) {
  476. return -1;
  477. }
  478. /* Escaping rules from http://www.w3.org/TR/REC-xml/#syntax */
  479. /* This also prevents partial entities at the end of a string */
  480. while (*string && dst < end) {
  481. const char *entity = NULL;
  482. int len = 0;
  483. switch (*string) {
  484. case '<':
  485. entity = "&lt;";
  486. len = 4;
  487. break;
  488. case '&':
  489. entity = "&amp;";
  490. len = 5;
  491. break;
  492. case '>':
  493. /* necessary if ]]> is in the string; easier to escape them all */
  494. entity = "&gt;";
  495. len = 4;
  496. break;
  497. case '\'':
  498. /* necessary in single-quoted strings; easier to escape them all */
  499. entity = "&apos;";
  500. len = 6;
  501. break;
  502. case '"':
  503. /* necessary in double-quoted strings; easier to escape them all */
  504. entity = "&quot;";
  505. len = 6;
  506. break;
  507. default:
  508. *dst++ = *string++;
  509. break;
  510. }
  511. if (entity) {
  512. ast_assert(len == strlen(entity));
  513. if (end - dst < len) {
  514. /* no room for the entity; stop */
  515. break;
  516. }
  517. /* just checked for length; strcpy is fine */
  518. strcpy(dst, entity);
  519. dst += len;
  520. ++string;
  521. }
  522. }
  523. /* Write null terminator */
  524. *dst = '\0';
  525. /* If any chars are left in string, return failure */
  526. return *string == '\0' ? 0 : -1;
  527. }
  528. /*! \brief ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa */
  529. const char *ast_inet_ntoa(struct in_addr ia)
  530. {
  531. char *buf;
  532. if (!(buf = ast_threadstorage_get(&inet_ntoa_buf, INET_ADDRSTRLEN)))
  533. return "";
  534. return inet_ntop(AF_INET, &ia, buf, INET_ADDRSTRLEN);
  535. }
  536. static int dev_urandom_fd = -1;
  537. #ifndef __linux__
  538. #undef pthread_create /* For ast_pthread_create function only */
  539. #endif /* !__linux__ */
  540. #if !defined(LOW_MEMORY)
  541. #ifdef DEBUG_THREADS
  542. /*! \brief A reasonable maximum number of locks a thread would be holding ... */
  543. #define AST_MAX_LOCKS 64
  544. /* Allow direct use of pthread_mutex_t and friends */
  545. #undef pthread_mutex_t
  546. #undef pthread_mutex_lock
  547. #undef pthread_mutex_unlock
  548. #undef pthread_mutex_init
  549. #undef pthread_mutex_destroy
  550. /*!
  551. * \brief Keep track of which locks a thread holds
  552. *
  553. * There is an instance of this struct for every active thread
  554. */
  555. struct thr_lock_info {
  556. /*! The thread's ID */
  557. pthread_t thread_id;
  558. /*! The thread name which includes where the thread was started */
  559. const char *thread_name;
  560. /*! This is the actual container of info for what locks this thread holds */
  561. struct {
  562. const char *file;
  563. const char *func;
  564. const char *lock_name;
  565. void *lock_addr;
  566. int times_locked;
  567. int line_num;
  568. enum ast_lock_type type;
  569. /*! This thread is waiting on this lock */
  570. int pending:2;
  571. /*! A condition has suspended this lock */
  572. int suspended:1;
  573. #ifdef HAVE_BKTR
  574. struct ast_bt *backtrace;
  575. #endif
  576. } locks[AST_MAX_LOCKS];
  577. /*! This is the number of locks currently held by this thread.
  578. * The index (num_locks - 1) has the info on the last one in the
  579. * locks member */
  580. unsigned int num_locks;
  581. /*! The LWP id (which GDB prints) */
  582. int lwp;
  583. /*! Protects the contents of the locks member
  584. * Intentionally not ast_mutex_t */
  585. pthread_mutex_t lock;
  586. AST_LIST_ENTRY(thr_lock_info) entry;
  587. };
  588. /*!
  589. * \brief Locked when accessing the lock_infos list
  590. */
  591. AST_MUTEX_DEFINE_STATIC(lock_infos_lock);
  592. /*!
  593. * \brief A list of each thread's lock info
  594. */
  595. static AST_LIST_HEAD_NOLOCK_STATIC(lock_infos, thr_lock_info);
  596. /*!
  597. * \brief Destroy a thread's lock info
  598. *
  599. * This gets called automatically when the thread stops
  600. */
  601. static void lock_info_destroy(void *data)
  602. {
  603. struct thr_lock_info *lock_info = data;
  604. int i;
  605. pthread_mutex_lock(&lock_infos_lock.mutex);
  606. AST_LIST_REMOVE(&lock_infos, lock_info, entry);
  607. pthread_mutex_unlock(&lock_infos_lock.mutex);
  608. for (i = 0; i < lock_info->num_locks; i++) {
  609. if (lock_info->locks[i].pending == -1) {
  610. /* This just means that the last lock this thread went for was by
  611. * using trylock, and it failed. This is fine. */
  612. break;
  613. }
  614. ast_log(LOG_ERROR,
  615. "Thread '%s' still has a lock! - '%s' (%p) from '%s' in %s:%d!\n",
  616. lock_info->thread_name,
  617. lock_info->locks[i].lock_name,
  618. lock_info->locks[i].lock_addr,
  619. lock_info->locks[i].func,
  620. lock_info->locks[i].file,
  621. lock_info->locks[i].line_num
  622. );
  623. }
  624. pthread_mutex_destroy(&lock_info->lock);
  625. if (lock_info->thread_name) {
  626. ast_free((void *) lock_info->thread_name);
  627. }
  628. ast_free(lock_info);
  629. }
  630. /*!
  631. * \brief The thread storage key for per-thread lock info
  632. */
  633. AST_THREADSTORAGE_CUSTOM(thread_lock_info, NULL, lock_info_destroy);
  634. #ifdef HAVE_BKTR
  635. void ast_store_lock_info(enum ast_lock_type type, const char *filename,
  636. int line_num, const char *func, const char *lock_name, void *lock_addr, struct ast_bt *bt)
  637. #else
  638. void ast_store_lock_info(enum ast_lock_type type, const char *filename,
  639. int line_num, const char *func, const char *lock_name, void *lock_addr)
  640. #endif
  641. {
  642. struct thr_lock_info *lock_info;
  643. int i;
  644. if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
  645. return;
  646. pthread_mutex_lock(&lock_info->lock);
  647. for (i = 0; i < lock_info->num_locks; i++) {
  648. if (lock_info->locks[i].lock_addr == lock_addr) {
  649. lock_info->locks[i].times_locked++;
  650. #ifdef HAVE_BKTR
  651. lock_info->locks[i].backtrace = bt;
  652. #endif
  653. pthread_mutex_unlock(&lock_info->lock);
  654. return;
  655. }
  656. }
  657. if (lock_info->num_locks == AST_MAX_LOCKS) {
  658. /* Can't use ast_log here, because it will cause infinite recursion */
  659. fprintf(stderr, "XXX ERROR XXX A thread holds more locks than '%d'."
  660. " Increase AST_MAX_LOCKS!\n", AST_MAX_LOCKS);
  661. pthread_mutex_unlock(&lock_info->lock);
  662. return;
  663. }
  664. if (i && lock_info->locks[i - 1].pending == -1) {
  665. /* The last lock on the list was one that this thread tried to lock but
  666. * failed at doing so. It has now moved on to something else, so remove
  667. * the old lock from the list. */
  668. i--;
  669. lock_info->num_locks--;
  670. memset(&lock_info->locks[i], 0, sizeof(lock_info->locks[0]));
  671. }
  672. lock_info->locks[i].file = filename;
  673. lock_info->locks[i].line_num = line_num;
  674. lock_info->locks[i].func = func;
  675. lock_info->locks[i].lock_name = lock_name;
  676. lock_info->locks[i].lock_addr = lock_addr;
  677. lock_info->locks[i].times_locked = 1;
  678. lock_info->locks[i].type = type;
  679. lock_info->locks[i].pending = 1;
  680. #ifdef HAVE_BKTR
  681. lock_info->locks[i].backtrace = bt;
  682. #endif
  683. lock_info->num_locks++;
  684. pthread_mutex_unlock(&lock_info->lock);
  685. }
  686. void ast_mark_lock_acquired(void *lock_addr)
  687. {
  688. struct thr_lock_info *lock_info;
  689. if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
  690. return;
  691. pthread_mutex_lock(&lock_info->lock);
  692. if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
  693. lock_info->locks[lock_info->num_locks - 1].pending = 0;
  694. }
  695. pthread_mutex_unlock(&lock_info->lock);
  696. }
  697. void ast_mark_lock_failed(void *lock_addr)
  698. {
  699. struct thr_lock_info *lock_info;
  700. if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
  701. return;
  702. pthread_mutex_lock(&lock_info->lock);
  703. if (lock_info->locks[lock_info->num_locks - 1].lock_addr == lock_addr) {
  704. lock_info->locks[lock_info->num_locks - 1].pending = -1;
  705. lock_info->locks[lock_info->num_locks - 1].times_locked--;
  706. }
  707. pthread_mutex_unlock(&lock_info->lock);
  708. }
  709. int ast_find_lock_info(void *lock_addr, char *filename, size_t filename_size, int *lineno, char *func, size_t func_size, char *mutex_name, size_t mutex_name_size)
  710. {
  711. struct thr_lock_info *lock_info;
  712. int i = 0;
  713. if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
  714. return -1;
  715. pthread_mutex_lock(&lock_info->lock);
  716. for (i = lock_info->num_locks - 1; i >= 0; i--) {
  717. if (lock_info->locks[i].lock_addr == lock_addr)
  718. break;
  719. }
  720. if (i == -1) {
  721. /* Lock not found :( */
  722. pthread_mutex_unlock(&lock_info->lock);
  723. return -1;
  724. }
  725. ast_copy_string(filename, lock_info->locks[i].file, filename_size);
  726. *lineno = lock_info->locks[i].line_num;
  727. ast_copy_string(func, lock_info->locks[i].func, func_size);
  728. ast_copy_string(mutex_name, lock_info->locks[i].lock_name, mutex_name_size);
  729. pthread_mutex_unlock(&lock_info->lock);
  730. return 0;
  731. }
  732. void ast_suspend_lock_info(void *lock_addr)
  733. {
  734. struct thr_lock_info *lock_info;
  735. int i = 0;
  736. if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info)))) {
  737. return;
  738. }
  739. pthread_mutex_lock(&lock_info->lock);
  740. for (i = lock_info->num_locks - 1; i >= 0; i--) {
  741. if (lock_info->locks[i].lock_addr == lock_addr)
  742. break;
  743. }
  744. if (i == -1) {
  745. /* Lock not found :( */
  746. pthread_mutex_unlock(&lock_info->lock);
  747. return;
  748. }
  749. lock_info->locks[i].suspended = 1;
  750. pthread_mutex_unlock(&lock_info->lock);
  751. }
  752. void ast_restore_lock_info(void *lock_addr)
  753. {
  754. struct thr_lock_info *lock_info;
  755. int i = 0;
  756. if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
  757. return;
  758. pthread_mutex_lock(&lock_info->lock);
  759. for (i = lock_info->num_locks - 1; i >= 0; i--) {
  760. if (lock_info->locks[i].lock_addr == lock_addr)
  761. break;
  762. }
  763. if (i == -1) {
  764. /* Lock not found :( */
  765. pthread_mutex_unlock(&lock_info->lock);
  766. return;
  767. }
  768. lock_info->locks[i].suspended = 0;
  769. pthread_mutex_unlock(&lock_info->lock);
  770. }
  771. #ifdef HAVE_BKTR
  772. void ast_remove_lock_info(void *lock_addr, struct ast_bt *bt)
  773. #else
  774. void ast_remove_lock_info(void *lock_addr)
  775. #endif
  776. {
  777. struct thr_lock_info *lock_info;
  778. int i = 0;
  779. if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
  780. return;
  781. pthread_mutex_lock(&lock_info->lock);
  782. for (i = lock_info->num_locks - 1; i >= 0; i--) {
  783. if (lock_info->locks[i].lock_addr == lock_addr)
  784. break;
  785. }
  786. if (i == -1) {
  787. /* Lock not found :( */
  788. pthread_mutex_unlock(&lock_info->lock);
  789. return;
  790. }
  791. if (lock_info->locks[i].times_locked > 1) {
  792. lock_info->locks[i].times_locked--;
  793. #ifdef HAVE_BKTR
  794. lock_info->locks[i].backtrace = bt;
  795. #endif
  796. pthread_mutex_unlock(&lock_info->lock);
  797. return;
  798. }
  799. if (i < lock_info->num_locks - 1) {
  800. /* Not the last one ... *should* be rare! */
  801. memmove(&lock_info->locks[i], &lock_info->locks[i + 1],
  802. (lock_info->num_locks - (i + 1)) * sizeof(lock_info->locks[0]));
  803. }
  804. lock_info->num_locks--;
  805. pthread_mutex_unlock(&lock_info->lock);
  806. }
  807. static const char *locktype2str(enum ast_lock_type type)
  808. {
  809. switch (type) {
  810. case AST_MUTEX:
  811. return "MUTEX";
  812. case AST_RDLOCK:
  813. return "RDLOCK";
  814. case AST_WRLOCK:
  815. return "WRLOCK";
  816. }
  817. return "UNKNOWN";
  818. }
  819. #ifdef HAVE_BKTR
  820. static void append_backtrace_information(struct ast_str **str, struct ast_bt *bt)
  821. {
  822. char **symbols;
  823. int num_frames;
  824. if (!bt) {
  825. ast_str_append(str, 0, "\tNo backtrace to print\n");
  826. return;
  827. }
  828. /* store frame count locally to avoid the memory corruption that
  829. * sometimes happens on virtualized CentOS 6.x systems */
  830. num_frames = bt->num_frames;
  831. if ((symbols = ast_bt_get_symbols(bt->addresses, num_frames))) {
  832. int frame_iterator;
  833. for (frame_iterator = 0; frame_iterator < num_frames; ++frame_iterator) {
  834. ast_str_append(str, 0, "\t%s\n", symbols[frame_iterator]);
  835. }
  836. ast_std_free(symbols);
  837. } else {
  838. ast_str_append(str, 0, "\tCouldn't retrieve backtrace symbols\n");
  839. }
  840. }
  841. #endif
  842. static void append_lock_information(struct ast_str **str, struct thr_lock_info *lock_info, int i)
  843. {
  844. int j;
  845. ast_mutex_t *lock;
  846. struct ast_lock_track *lt;
  847. ast_str_append(str, 0, "=== ---> %sLock #%d (%s): %s %d %s %s %p (%d%s)\n",
  848. lock_info->locks[i].pending > 0 ? "Waiting for " :
  849. lock_info->locks[i].pending < 0 ? "Tried and failed to get " : "", i,
  850. lock_info->locks[i].file,
  851. locktype2str(lock_info->locks[i].type),
  852. lock_info->locks[i].line_num,
  853. lock_info->locks[i].func, lock_info->locks[i].lock_name,
  854. lock_info->locks[i].lock_addr,
  855. lock_info->locks[i].times_locked,
  856. lock_info->locks[i].suspended ? " - suspended" : "");
  857. #ifdef HAVE_BKTR
  858. append_backtrace_information(str, lock_info->locks[i].backtrace);
  859. #endif
  860. if (!lock_info->locks[i].pending || lock_info->locks[i].pending == -1)
  861. return;
  862. /* We only have further details for mutexes right now */
  863. if (lock_info->locks[i].type != AST_MUTEX)
  864. return;
  865. lock = lock_info->locks[i].lock_addr;
  866. lt = lock->track;
  867. ast_reentrancy_lock(lt);
  868. for (j = 0; *str && j < lt->reentrancy; j++) {
  869. ast_str_append(str, 0, "=== --- ---> Locked Here: %s line %d (%s)\n",
  870. lt->file[j], lt->lineno[j], lt->func[j]);
  871. }
  872. ast_reentrancy_unlock(lt);
  873. }
  874. /*! This function can help you find highly temporal locks; locks that happen for a
  875. short time, but at unexpected times, usually at times that create a deadlock,
  876. Why is this thing locked right then? Who is locking it? Who am I fighting
  877. with for this lock?
  878. To answer such questions, just call this routine before you would normally try
  879. to aquire a lock. It doesn't do anything if the lock is not acquired. If the
  880. lock is taken, it will publish a line or two to the console via ast_log().
  881. Sometimes, the lock message is pretty uninformative. For instance, you might
  882. find that the lock is being aquired deep within the astobj2 code; this tells
  883. you little about higher level routines that call the astobj2 routines.
  884. But, using gdb, you can set a break at the ast_log below, and for that
  885. breakpoint, you can set the commands:
  886. where
  887. cont
  888. which will give a stack trace and continue. -- that aught to do the job!
  889. */
  890. void ast_log_show_lock(void *this_lock_addr)
  891. {
  892. struct thr_lock_info *lock_info;
  893. struct ast_str *str;
  894. if (!(str = ast_str_create(4096))) {
  895. ast_log(LOG_NOTICE,"Could not create str\n");
  896. return;
  897. }
  898. pthread_mutex_lock(&lock_infos_lock.mutex);
  899. AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
  900. int i;
  901. pthread_mutex_lock(&lock_info->lock);
  902. for (i = 0; str && i < lock_info->num_locks; i++) {
  903. /* ONLY show info about this particular lock, if
  904. it's acquired... */
  905. if (lock_info->locks[i].lock_addr == this_lock_addr) {
  906. append_lock_information(&str, lock_info, i);
  907. ast_log(LOG_NOTICE, "%s", ast_str_buffer(str));
  908. break;
  909. }
  910. }
  911. pthread_mutex_unlock(&lock_info->lock);
  912. }
  913. pthread_mutex_unlock(&lock_infos_lock.mutex);
  914. ast_free(str);
  915. }
  916. struct ast_str *ast_dump_locks(void)
  917. {
  918. struct thr_lock_info *lock_info;
  919. struct ast_str *str;
  920. if (!(str = ast_str_create(4096))) {
  921. return NULL;
  922. }
  923. ast_str_append(&str, 0, "\n"
  924. "=======================================================================\n"
  925. "=== %s\n"
  926. "=== Currently Held Locks\n"
  927. "=======================================================================\n"
  928. "===\n"
  929. "=== <pending> <lock#> (<file>): <lock type> <line num> <function> <lock name> <lock addr> (times locked)\n"
  930. "===\n", ast_get_version());
  931. if (!str) {
  932. return NULL;
  933. }
  934. pthread_mutex_lock(&lock_infos_lock.mutex);
  935. AST_LIST_TRAVERSE(&lock_infos, lock_info, entry) {
  936. int i;
  937. int header_printed = 0;
  938. pthread_mutex_lock(&lock_info->lock);
  939. for (i = 0; str && i < lock_info->num_locks; i++) {
  940. /* Don't show suspended locks */
  941. if (lock_info->locks[i].suspended) {
  942. continue;
  943. }
  944. if (!header_printed) {
  945. if (lock_info->lwp != -1) {
  946. ast_str_append(&str, 0, "=== Thread ID: 0x%lx LWP:%d (%s)\n",
  947. (long unsigned) lock_info->thread_id, lock_info->lwp, lock_info->thread_name);
  948. } else {
  949. ast_str_append(&str, 0, "=== Thread ID: 0x%lx (%s)\n",
  950. (long unsigned) lock_info->thread_id, lock_info->thread_name);
  951. }
  952. header_printed = 1;
  953. }
  954. append_lock_information(&str, lock_info, i);
  955. }
  956. pthread_mutex_unlock(&lock_info->lock);
  957. if (!str) {
  958. break;
  959. }
  960. if (header_printed) {
  961. ast_str_append(&str, 0, "=== -------------------------------------------------------------------\n"
  962. "===\n");
  963. }
  964. if (!str) {
  965. break;
  966. }
  967. }
  968. pthread_mutex_unlock(&lock_infos_lock.mutex);
  969. if (!str) {
  970. return NULL;
  971. }
  972. ast_str_append(&str, 0, "=======================================================================\n"
  973. "\n");
  974. return str;
  975. }
  976. static char *handle_show_locks(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  977. {
  978. struct ast_str *str;
  979. switch (cmd) {
  980. case CLI_INIT:
  981. e->command = "core show locks";
  982. e->usage =
  983. "Usage: core show locks\n"
  984. " This command is for lock debugging. It prints out which locks\n"
  985. "are owned by each active thread.\n";
  986. return NULL;
  987. case CLI_GENERATE:
  988. return NULL;
  989. }
  990. str = ast_dump_locks();
  991. if (!str) {
  992. return CLI_FAILURE;
  993. }
  994. ast_cli(a->fd, "%s", ast_str_buffer(str));
  995. ast_free(str);
  996. return CLI_SUCCESS;
  997. }
  998. static struct ast_cli_entry utils_cli[] = {
  999. AST_CLI_DEFINE(handle_show_locks, "Show which locks are held by which thread"),
  1000. };
  1001. #endif /* DEBUG_THREADS */
  1002. /*
  1003. * support for 'show threads'. The start routine is wrapped by
  1004. * dummy_start(), so that ast_register_thread() and
  1005. * ast_unregister_thread() know the thread identifier.
  1006. */
  1007. struct thr_arg {
  1008. void *(*start_routine)(void *);
  1009. void *data;
  1010. char *name;
  1011. };
  1012. /*
  1013. * on OS/X, pthread_cleanup_push() and pthread_cleanup_pop()
  1014. * are odd macros which start and end a block, so they _must_ be
  1015. * used in pairs (the latter with a '1' argument to call the
  1016. * handler on exit.
  1017. * On BSD we don't need this, but we keep it for compatibility.
  1018. */
  1019. static void *dummy_start(void *data)
  1020. {
  1021. void *ret;
  1022. struct thr_arg a = *((struct thr_arg *) data); /* make a local copy */
  1023. #ifdef DEBUG_THREADS
  1024. struct thr_lock_info *lock_info;
  1025. pthread_mutexattr_t mutex_attr;
  1026. if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
  1027. return NULL;
  1028. lock_info->thread_id = pthread_self();
  1029. lock_info->lwp = ast_get_tid();
  1030. lock_info->thread_name = strdup(a.name);
  1031. pthread_mutexattr_init(&mutex_attr);
  1032. pthread_mutexattr_settype(&mutex_attr, AST_MUTEX_KIND);
  1033. pthread_mutex_init(&lock_info->lock, &mutex_attr);
  1034. pthread_mutexattr_destroy(&mutex_attr);
  1035. pthread_mutex_lock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
  1036. AST_LIST_INSERT_TAIL(&lock_infos, lock_info, entry);
  1037. pthread_mutex_unlock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
  1038. #endif /* DEBUG_THREADS */
  1039. /* note that even though data->name is a pointer to allocated memory,
  1040. we are not freeing it here because ast_register_thread is going to
  1041. keep a copy of the pointer and then ast_unregister_thread will
  1042. free the memory
  1043. */
  1044. ast_free(data);
  1045. ast_register_thread(a.name);
  1046. pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
  1047. ret = a.start_routine(a.data);
  1048. pthread_cleanup_pop(1);
  1049. return ret;
  1050. }
  1051. #endif /* !LOW_MEMORY */
  1052. int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
  1053. void *data, size_t stacksize, const char *file, const char *caller,
  1054. int line, const char *start_fn)
  1055. {
  1056. #if !defined(LOW_MEMORY)
  1057. struct thr_arg *a;
  1058. #endif
  1059. if (!attr) {
  1060. attr = ast_alloca(sizeof(*attr));
  1061. pthread_attr_init(attr);
  1062. }
  1063. #ifdef __linux__
  1064. /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
  1065. which is kind of useless. Change this here to
  1066. PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
  1067. priority will propagate down to new threads by default.
  1068. This does mean that callers cannot set a different priority using
  1069. PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
  1070. the priority afterwards with pthread_setschedparam(). */
  1071. if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
  1072. ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
  1073. #endif
  1074. if (!stacksize)
  1075. stacksize = AST_STACKSIZE;
  1076. if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
  1077. ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
  1078. #if !defined(LOW_MEMORY)
  1079. if ((a = ast_malloc(sizeof(*a)))) {
  1080. a->start_routine = start_routine;
  1081. a->data = data;
  1082. start_routine = dummy_start;
  1083. if (ast_asprintf(&a->name, "%-20s started at [%5d] %s %s()",
  1084. start_fn, line, file, caller) < 0) {
  1085. a->name = NULL;
  1086. }
  1087. data = a;
  1088. }
  1089. #endif /* !LOW_MEMORY */
  1090. return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
  1091. }
  1092. int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),
  1093. void *data, size_t stacksize, const char *file, const char *caller,
  1094. int line, const char *start_fn)
  1095. {
  1096. unsigned char attr_destroy = 0;
  1097. int res;
  1098. if (!attr) {
  1099. attr = ast_alloca(sizeof(*attr));
  1100. pthread_attr_init(attr);
  1101. attr_destroy = 1;
  1102. }
  1103. if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
  1104. ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
  1105. res = ast_pthread_create_stack(thread, attr, start_routine, data,
  1106. stacksize, file, caller, line, start_fn);
  1107. if (attr_destroy)
  1108. pthread_attr_destroy(attr);
  1109. return res;
  1110. }
  1111. int ast_wait_for_input(int fd, int ms)
  1112. {
  1113. struct pollfd pfd[1];
  1114. memset(pfd, 0, sizeof(pfd));
  1115. pfd[0].fd = fd;
  1116. pfd[0].events = POLLIN | POLLPRI;
  1117. return ast_poll(pfd, 1, ms);
  1118. }
  1119. int ast_wait_for_output(int fd, int ms)
  1120. {
  1121. struct pollfd pfd[1];
  1122. memset(pfd, 0, sizeof(pfd));
  1123. pfd[0].fd = fd;
  1124. pfd[0].events = POLLOUT;
  1125. return ast_poll(pfd, 1, ms);
  1126. }
  1127. static int wait_for_output(int fd, int timeoutms)
  1128. {
  1129. struct pollfd pfd = {
  1130. .fd = fd,
  1131. .events = POLLOUT,
  1132. };
  1133. int res;
  1134. struct timeval start = ast_tvnow();
  1135. int elapsed = 0;
  1136. /* poll() until the fd is writable without blocking */
  1137. while ((res = ast_poll(&pfd, 1, timeoutms - elapsed)) <= 0) {
  1138. if (res == 0) {
  1139. /* timed out. */
  1140. #ifndef STANDALONE
  1141. ast_debug(1, "Timed out trying to write\n");
  1142. #endif
  1143. return -1;
  1144. } else if (res == -1) {
  1145. /* poll() returned an error, check to see if it was fatal */
  1146. if (errno == EINTR || errno == EAGAIN) {
  1147. elapsed = ast_tvdiff_ms(ast_tvnow(), start);
  1148. if (elapsed >= timeoutms) {
  1149. return -1;
  1150. }
  1151. /* This was an acceptable error, go back into poll() */
  1152. continue;
  1153. }
  1154. /* Fatal error, bail. */
  1155. ast_log(LOG_ERROR, "poll returned error: %s\n", strerror(errno));
  1156. return -1;
  1157. }
  1158. elapsed = ast_tvdiff_ms(ast_tvnow(), start);
  1159. if (elapsed >= timeoutms) {
  1160. return -1;
  1161. }
  1162. }
  1163. return 0;
  1164. }
  1165. /*!
  1166. * Try to write string, but wait no more than ms milliseconds before timing out.
  1167. *
  1168. * \note The code assumes that the file descriptor has NONBLOCK set,
  1169. * so there is only one system call made to do a write, unless we actually
  1170. * have a need to wait. This way, we get better performance.
  1171. * If the descriptor is blocking, all assumptions on the guaranteed
  1172. * detail do not apply anymore.
  1173. */
  1174. int ast_carefulwrite(int fd, char *s, int len, int timeoutms)
  1175. {
  1176. struct timeval start = ast_tvnow();
  1177. int res = 0;
  1178. int elapsed = 0;
  1179. while (len) {
  1180. if (wait_for_output(fd, timeoutms - elapsed)) {
  1181. return -1;
  1182. }
  1183. res = write(fd, s, len);
  1184. if (res < 0 && errno != EAGAIN && errno != EINTR) {
  1185. /* fatal error from write() */
  1186. ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
  1187. return -1;
  1188. }
  1189. if (res < 0) {
  1190. /* It was an acceptable error */
  1191. res = 0;
  1192. }
  1193. /* Update how much data we have left to write */
  1194. len -= res;
  1195. s += res;
  1196. res = 0;
  1197. elapsed = ast_tvdiff_ms(ast_tvnow(), start);
  1198. if (elapsed >= timeoutms) {
  1199. /* We've taken too long to write
  1200. * This is only an error condition if we haven't finished writing. */
  1201. res = len ? -1 : 0;
  1202. break;
  1203. }
  1204. }
  1205. return res;
  1206. }
  1207. int ast_careful_fwrite(FILE *f, int fd, const char *src, size_t len, int timeoutms)
  1208. {
  1209. struct timeval start = ast_tvnow();
  1210. int n = 0;
  1211. int elapsed = 0;
  1212. while (len) {
  1213. if (wait_for_output(fd, timeoutms - elapsed)) {
  1214. /* poll returned a fatal error, so bail out immediately. */
  1215. return -1;
  1216. }
  1217. /* Clear any errors from a previous write */
  1218. clearerr(f);
  1219. n = fwrite(src, 1, len, f);
  1220. if (ferror(f) && errno != EINTR && errno != EAGAIN) {
  1221. /* fatal error from fwrite() */
  1222. if (!feof(f)) {
  1223. /* Don't spam the logs if it was just that the connection is closed. */
  1224. ast_log(LOG_ERROR, "fwrite() returned error: %s\n", strerror(errno));
  1225. }
  1226. n = -1;
  1227. break;
  1228. }
  1229. /* Update for data already written to the socket */
  1230. len -= n;
  1231. src += n;
  1232. elapsed = ast_tvdiff_ms(ast_tvnow(), start);
  1233. if (elapsed >= timeoutms) {
  1234. /* We've taken too long to write
  1235. * This is only an error condition if we haven't finished writing. */
  1236. n = len ? -1 : 0;
  1237. break;
  1238. }
  1239. }
  1240. errno = 0;
  1241. while (fflush(f)) {
  1242. if (errno == EAGAIN || errno == EINTR) {
  1243. /* fflush() does not appear to reset errno if it flushes
  1244. * and reaches EOF at the same time. It returns EOF with
  1245. * the last seen value of errno, causing a possible loop.
  1246. * Also usleep() to reduce CPU eating if it does loop */
  1247. errno = 0;
  1248. usleep(1);
  1249. continue;
  1250. }
  1251. if (errno && !feof(f)) {
  1252. /* Don't spam the logs if it was just that the connection is closed. */
  1253. ast_log(LOG_ERROR, "fflush() returned error: %s\n", strerror(errno));
  1254. }
  1255. n = -1;
  1256. break;
  1257. }
  1258. return n < 0 ? -1 : 0;
  1259. }
  1260. char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
  1261. {
  1262. char *e;
  1263. char *q;
  1264. s = ast_strip(s);
  1265. if ((q = strchr(beg_quotes, *s)) && *q != '\0') {
  1266. e = s + strlen(s) - 1;
  1267. if (*e == *(end_quotes + (q - beg_quotes))) {
  1268. s++;
  1269. *e = '\0';
  1270. }
  1271. }
  1272. return s;
  1273. }
  1274. char *ast_strsep(char **iss, const char sep, uint32_t flags)
  1275. {
  1276. char *st = *iss;
  1277. char *is;
  1278. int inquote = 0;
  1279. int found = 0;
  1280. char stack[8];
  1281. if (iss == NULL || *iss == '\0') {
  1282. return NULL;
  1283. }
  1284. memset(stack, 0, sizeof(stack));
  1285. for(is = st; *is; is++) {
  1286. if (*is == '\\') {
  1287. if (*++is != '\0') {
  1288. is++;
  1289. } else {
  1290. break;
  1291. }
  1292. }
  1293. if (*is == '\'' || *is == '"') {
  1294. if (*is == stack[inquote]) {
  1295. stack[inquote--] = '\0';
  1296. } else {
  1297. if (++inquote >= sizeof(stack)) {
  1298. return NULL;
  1299. }
  1300. stack[inquote] = *is;
  1301. }
  1302. }
  1303. if (*is == sep && !inquote) {
  1304. *is = '\0';
  1305. found = 1;
  1306. *iss = is + 1;
  1307. break;
  1308. }
  1309. }
  1310. if (!found) {
  1311. *iss = NULL;
  1312. }
  1313. if (flags & AST_STRSEP_STRIP) {
  1314. st = ast_strip_quoted(st, "'\"", "'\"");
  1315. }
  1316. if (flags & AST_STRSEP_TRIM) {
  1317. st = ast_strip(st);
  1318. }
  1319. if (flags & AST_STRSEP_UNESCAPE) {
  1320. ast_unescape_quoted(st);
  1321. }
  1322. return st;
  1323. }
  1324. char *ast_unescape_semicolon(char *s)
  1325. {
  1326. char *e;
  1327. char *work = s;
  1328. while ((e = strchr(work, ';'))) {
  1329. if ((e > work) && (*(e-1) == '\\')) {
  1330. memmove(e - 1, e, strlen(e) + 1);
  1331. work = e;
  1332. } else {
  1333. work = e + 1;
  1334. }
  1335. }
  1336. return s;
  1337. }
  1338. /* !\brief unescape some C sequences in place, return pointer to the original string.
  1339. */
  1340. char *ast_unescape_c(char *src)
  1341. {
  1342. char c, *ret, *dst;
  1343. if (src == NULL)
  1344. return NULL;
  1345. for (ret = dst = src; (c = *src++); *dst++ = c ) {
  1346. if (c != '\\')
  1347. continue; /* copy char at the end of the loop */
  1348. switch ((c = *src++)) {
  1349. case '\0': /* special, trailing '\' */
  1350. c = '\\';
  1351. break;
  1352. case 'b': /* backspace */
  1353. c = '\b';
  1354. break;
  1355. case 'f': /* form feed */
  1356. c = '\f';
  1357. break;
  1358. case 'n':
  1359. c = '\n';
  1360. break;
  1361. case 'r':
  1362. c = '\r';
  1363. break;
  1364. case 't':
  1365. c = '\t';
  1366. break;
  1367. }
  1368. /* default, use the char literally */
  1369. }
  1370. *dst = '\0';
  1371. return ret;
  1372. }
  1373. int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap)
  1374. {
  1375. int result;
  1376. if (!buffer || !*buffer || !space || !*space)
  1377. return -1;
  1378. result = vsnprintf(*buffer, *space, fmt, ap);
  1379. if (result < 0)
  1380. return -1;
  1381. else if (result > *space)
  1382. result = *space;
  1383. *buffer += result;
  1384. *space -= result;
  1385. return 0;
  1386. }
  1387. int ast_build_string(char **buffer, size_t *space, const char *fmt, ...)
  1388. {
  1389. va_list ap;
  1390. int result;
  1391. va_start(ap, fmt);
  1392. result = ast_build_string_va(buffer, space, fmt, ap);
  1393. va_end(ap);
  1394. return result;
  1395. }
  1396. int ast_regex_string_to_regex_pattern(const char *regex_string, struct ast_str **regex_pattern)
  1397. {
  1398. int regex_len = strlen(regex_string);
  1399. int ret = 3;
  1400. /* Chop off the leading / if there is one */
  1401. if ((regex_len >= 1) && (regex_string[0] == '/')) {
  1402. ast_str_set(regex_pattern, 0, "%s", regex_string + 1);
  1403. ret -= 2;
  1404. }
  1405. /* Chop off the ending / if there is one */
  1406. if ((regex_len > 1) && (regex_string[regex_len - 1] == '/')) {
  1407. ast_str_truncate(*regex_pattern, -1);
  1408. ret -= 1;
  1409. }
  1410. return ret;
  1411. }
  1412. int ast_true(const char *s)
  1413. {
  1414. if (ast_strlen_zero(s))
  1415. return 0;
  1416. /* Determine if this is a true value */
  1417. if (!strcasecmp(s, "yes") ||
  1418. !strcasecmp(s, "true") ||
  1419. !strcasecmp(s, "y") ||
  1420. !strcasecmp(s, "t") ||
  1421. !strcasecmp(s, "1") ||
  1422. !strcasecmp(s, "on"))
  1423. return -1;
  1424. return 0;
  1425. }
  1426. int ast_false(const char *s)
  1427. {
  1428. if (ast_strlen_zero(s))
  1429. return 0;
  1430. /* Determine if this is a false value */
  1431. if (!strcasecmp(s, "no") ||
  1432. !strcasecmp(s, "false") ||
  1433. !strcasecmp(s, "n") ||
  1434. !strcasecmp(s, "f") ||
  1435. !strcasecmp(s, "0") ||
  1436. !strcasecmp(s, "off"))
  1437. return -1;
  1438. return 0;
  1439. }
  1440. #define ONE_MILLION 1000000
  1441. /*
  1442. * put timeval in a valid range. usec is 0..999999
  1443. * negative values are not allowed and truncated.
  1444. */
  1445. static struct timeval tvfix(struct timeval a)
  1446. {
  1447. if (a.tv_usec >= ONE_MILLION) {
  1448. ast_log(LOG_WARNING, "warning too large timestamp %ld.%ld\n",
  1449. (long)a.tv_sec, (long int) a.tv_usec);
  1450. a.tv_sec += a.tv_usec / ONE_MILLION;
  1451. a.tv_usec %= ONE_MILLION;
  1452. } else if (a.tv_usec < 0) {
  1453. ast_log(LOG_WARNING, "warning negative timestamp %ld.%ld\n",
  1454. (long)a.tv_sec, (long int) a.tv_usec);
  1455. a.tv_usec = 0;
  1456. }
  1457. return a;
  1458. }
  1459. struct timeval ast_tvadd(struct timeval a, struct timeval b)
  1460. {
  1461. /* consistency checks to guarantee usec in 0..999999 */
  1462. a = tvfix(a);
  1463. b = tvfix(b);
  1464. a.tv_sec += b.tv_sec;
  1465. a.tv_usec += b.tv_usec;
  1466. if (a.tv_usec >= ONE_MILLION) {
  1467. a.tv_sec++;
  1468. a.tv_usec -= ONE_MILLION;
  1469. }
  1470. return a;
  1471. }
  1472. struct timeval ast_tvsub(struct timeval a, struct timeval b)
  1473. {
  1474. /* consistency checks to guarantee usec in 0..999999 */
  1475. a = tvfix(a);
  1476. b = tvfix(b);
  1477. a.tv_sec -= b.tv_sec;
  1478. a.tv_usec -= b.tv_usec;
  1479. if (a.tv_usec < 0) {
  1480. a.tv_sec-- ;
  1481. a.tv_usec += ONE_MILLION;
  1482. }
  1483. return a;
  1484. }
  1485. int ast_remaining_ms(struct timeval start, int max_ms)
  1486. {
  1487. int ms;
  1488. if (max_ms < 0) {
  1489. ms = max_ms;
  1490. } else {
  1491. ms = max_ms - ast_tvdiff_ms(ast_tvnow(), start);
  1492. if (ms < 0) {
  1493. ms = 0;
  1494. }
  1495. }
  1496. return ms;
  1497. }
  1498. void ast_format_duration_hh_mm_ss(int duration, char *buf, size_t length)
  1499. {
  1500. int durh, durm, durs;
  1501. durh = duration / 3600;
  1502. durm = (duration % 3600) / 60;
  1503. durs = duration % 60;
  1504. snprintf(buf, length, "%02d:%02d:%02d", durh, durm, durs);
  1505. }
  1506. #undef ONE_MILLION
  1507. #ifndef linux
  1508. AST_MUTEX_DEFINE_STATIC(randomlock);
  1509. #endif
  1510. long int ast_random(void)
  1511. {
  1512. long int res;
  1513. if (dev_urandom_fd >= 0) {
  1514. int read_res = read(dev_urandom_fd, &res, sizeof(res));
  1515. if (read_res > 0) {
  1516. long int rm = RAND_MAX;
  1517. res = res < 0 ? ~res : res;
  1518. rm++;
  1519. return res % rm;
  1520. }
  1521. }
  1522. /* XXX - Thread safety really depends on the libc, not the OS.
  1523. *
  1524. * But... popular Linux libc's (uClibc, glibc, eglibc), all have a
  1525. * somewhat thread safe random(3) (results are random, but not
  1526. * reproducible). The libc's for other systems (BSD, et al.), not so
  1527. * much.
  1528. */
  1529. #ifdef linux
  1530. res = random();
  1531. #else
  1532. ast_mutex_lock(&randomlock);
  1533. res = random();
  1534. ast_mutex_unlock(&randomlock);
  1535. #endif
  1536. return res;
  1537. }
  1538. void ast_replace_subargument_delimiter(char *s)
  1539. {
  1540. for (; *s; s++) {
  1541. if (*s == '^') {
  1542. *s = ',';
  1543. }
  1544. }
  1545. }
  1546. char *ast_process_quotes_and_slashes(char *start, char find, char replace_with)
  1547. {
  1548. char *dataPut = start;
  1549. int inEscape = 0;
  1550. int inQuotes = 0;
  1551. for (; *start; start++) {
  1552. if (inEscape) {
  1553. *dataPut++ = *start; /* Always goes verbatim */
  1554. inEscape = 0;
  1555. } else {
  1556. if (*start == '\\') {
  1557. inEscape = 1; /* Do not copy \ into the data */
  1558. } else if (*start == '\'') {
  1559. inQuotes = 1 - inQuotes; /* Do not copy ' into the data */
  1560. } else {
  1561. /* Replace , with |, unless in quotes */
  1562. *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
  1563. }
  1564. }
  1565. }
  1566. if (start != dataPut)
  1567. *dataPut = 0;
  1568. return dataPut;
  1569. }
  1570. void ast_join_delim(char *s, size_t len, const char * const w[], unsigned int size, char delim)
  1571. {
  1572. int x, ofs = 0;
  1573. const char *src;
  1574. /* Join words into a string */
  1575. if (!s)
  1576. return;
  1577. for (x = 0; ofs < len && x < size && w[x] ; x++) {
  1578. if (x > 0)
  1579. s[ofs++] = delim;
  1580. for (src = w[x]; *src && ofs < len; src++)
  1581. s[ofs++] = *src;
  1582. }
  1583. if (ofs == len)
  1584. ofs--;
  1585. s[ofs] = '\0';
  1586. }
  1587. char *ast_to_camel_case_delim(const char *s, const char *delim)
  1588. {
  1589. char *res = ast_strdup(s);
  1590. char *front, *back, *buf = res;
  1591. int size;
  1592. front = strtok_r(buf, delim, &back);
  1593. while (front) {
  1594. size = strlen(front);
  1595. *front = toupper(*front);
  1596. ast_copy_string(buf, front, size + 1);
  1597. buf += size;
  1598. front = strtok_r(NULL, delim, &back);
  1599. }
  1600. return res;
  1601. }
  1602. /*
  1603. * stringfields support routines.
  1604. */
  1605. /* this is a little complex... string fields are stored with their
  1606. allocated size in the bytes preceding the string; even the
  1607. constant 'empty' string has to be this way, so the code that
  1608. checks to see if there is enough room for a new string doesn't
  1609. have to have any special case checks
  1610. */
  1611. static const struct {
  1612. ast_string_field_allocation allocation;
  1613. char string[1];
  1614. } __ast_string_field_empty_buffer;
  1615. ast_string_field __ast_string_field_empty = __ast_string_field_empty_buffer.string;
  1616. #define ALLOCATOR_OVERHEAD 48
  1617. static size_t optimal_alloc_size(size_t size)
  1618. {
  1619. unsigned int count;
  1620. size += ALLOCATOR_OVERHEAD;
  1621. for (count = 1; size; size >>= 1, count++);
  1622. return (1 << count) - ALLOCATOR_OVERHEAD;
  1623. }
  1624. /*! \brief add a new block to the pool.
  1625. * We can only allocate from the topmost pool, so the
  1626. * fields in *mgr reflect the size of that only.
  1627. */
  1628. static int add_string_pool(struct ast_string_field_mgr *mgr, struct ast_string_field_pool **pool_head,
  1629. size_t size, const char *file, int lineno, const char *func)
  1630. {
  1631. struct ast_string_field_pool *pool;
  1632. size_t alloc_size = optimal_alloc_size(sizeof(*pool) + size);
  1633. #if defined(__AST_DEBUG_MALLOC)
  1634. if (!(pool = __ast_calloc(1, alloc_size, file, lineno, func))) {
  1635. return -1;
  1636. }
  1637. #else
  1638. if (!(pool = ast_calloc(1, alloc_size))) {
  1639. return -1;
  1640. }
  1641. #endif
  1642. pool->prev = *pool_head;
  1643. pool->size = alloc_size - sizeof(*pool);
  1644. *pool_head = pool;
  1645. mgr->last_alloc = NULL;
  1646. return 0;
  1647. }
  1648. /*
  1649. * This is an internal API, code should not use it directly.
  1650. * It initializes all fields as empty, then uses 'size' for 3 functions:
  1651. * size > 0 means initialize the pool list with a pool of given size.
  1652. * This must be called right after allocating the object.
  1653. * size = 0 means release all pools except the most recent one.
  1654. * If the first pool was allocated via embedding in another
  1655. * object, that pool will be preserved instead.
  1656. * This is useful to e.g. reset an object to the initial value.
  1657. * size < 0 means release all pools.
  1658. * This must be done before destroying the object.
  1659. */
  1660. int __ast_string_field_init(struct ast_string_field_mgr *mgr, struct ast_string_field_pool **pool_head,
  1661. int needed, const char *file, int lineno, const char *func)
  1662. {
  1663. const char **p = (const char **) pool_head + 1;
  1664. struct ast_string_field_pool *cur = NULL;
  1665. struct ast_string_field_pool *preserve = NULL;
  1666. /* clear fields - this is always necessary */
  1667. while ((struct ast_string_field_mgr *) p != mgr) {
  1668. *p++ = __ast_string_field_empty;
  1669. }
  1670. mgr->last_alloc = NULL;
  1671. #if defined(__AST_DEBUG_MALLOC)
  1672. mgr->owner_file = file;
  1673. mgr->owner_func = func;
  1674. mgr->owner_line = lineno;
  1675. #endif
  1676. if (needed > 0) { /* allocate the initial pool */
  1677. *pool_head = NULL;
  1678. mgr->embedded_pool = NULL;
  1679. return add_string_pool(mgr, pool_head, needed, file, lineno, func);
  1680. }
  1681. /* if there is an embedded pool, we can't actually release *all*
  1682. * pools, we must keep the embedded one. if the caller is about
  1683. * to free the structure that contains the stringfield manager
  1684. * and embedded pool anyway, it will be freed as part of that
  1685. * operation.
  1686. */
  1687. if ((needed < 0) && mgr->embedded_pool) {
  1688. needed = 0;
  1689. }
  1690. if (needed < 0) { /* reset all pools */
  1691. cur = *pool_head;
  1692. } else if (mgr->embedded_pool) { /* preserve the embedded pool */
  1693. preserve = mgr->embedded_pool;
  1694. cur = *pool_head;
  1695. } else { /* preserve the last pool */
  1696. if (*pool_head == NULL) {
  1697. ast_log(LOG_WARNING, "trying to reset empty pool\n");
  1698. return -1;
  1699. }
  1700. preserve = *pool_head;
  1701. cur = preserve->prev;
  1702. }
  1703. if (preserve) {
  1704. preserve->prev = NULL;
  1705. preserve->used = preserve->active = 0;
  1706. }
  1707. while (cur) {
  1708. struct ast_string_field_pool *prev = cur->prev;
  1709. if (cur != preserve) {
  1710. ast_free(cur);
  1711. }
  1712. cur = prev;
  1713. }
  1714. *pool_head = preserve;
  1715. return 0;
  1716. }
  1717. ast_string_field __ast_string_field_alloc_space(struct ast_string_field_mgr *mgr,
  1718. struct ast_string_field_pool **pool_head, size_t needed)
  1719. {
  1720. char *result = NULL;
  1721. size_t space = (*pool_head)->size - (*pool_head)->used;
  1722. size_t to_alloc;
  1723. /* Make room for ast_string_field_allocation and make it a multiple of that. */
  1724. to_alloc = ast_make_room_for(needed, ast_string_field_allocation);
  1725. ast_assert(to_alloc % ast_alignof(ast_string_field_allocation) == 0);
  1726. if (__builtin_expect(to_alloc > space, 0)) {
  1727. size_t new_size = (*pool_head)->size;
  1728. while (new_size < to_alloc) {
  1729. new_size *= 2;
  1730. }
  1731. #if defined(__AST_DEBUG_MALLOC)
  1732. if (add_string_pool(mgr, pool_head, new_size, mgr->owner_file, mgr->owner_line, mgr->owner_func))
  1733. return NULL;
  1734. #else
  1735. if (add_string_pool(mgr, pool_head, new_size, __FILE__, __LINE__, __FUNCTION__))
  1736. return NULL;
  1737. #endif
  1738. }
  1739. /* pool->base is always aligned (gcc aligned attribute). We ensure that
  1740. * to_alloc is also a multiple of ast_alignof(ast_string_field_allocation)
  1741. * causing result to always be aligned as well; which in turn fixes that
  1742. * AST_STRING_FIELD_ALLOCATION(result) is aligned. */
  1743. result = (*pool_head)->base + (*pool_head)->used;
  1744. (*pool_head)->used += to_alloc;
  1745. (*pool_head)->active += needed;
  1746. result += ast_alignof(ast_string_field_allocation);
  1747. AST_STRING_FIELD_ALLOCATION(result) = needed;
  1748. mgr->last_alloc = result;
  1749. return result;
  1750. }
  1751. int __ast_string_field_ptr_grow(struct ast_string_field_mgr *mgr,
  1752. struct ast_string_field_pool **pool_head, size_t needed,
  1753. const ast_string_field *ptr)
  1754. {
  1755. ssize_t grow = needed - AST_STRING_FIELD_ALLOCATION(*ptr);
  1756. size_t space = (*pool_head)->size - (*pool_head)->used;
  1757. if (*ptr != mgr->last_alloc) {
  1758. return 1;
  1759. }
  1760. if (space < grow) {
  1761. return 1;
  1762. }
  1763. (*pool_head)->used += grow;
  1764. (*pool_head)->active += grow;
  1765. AST_STRING_FIELD_ALLOCATION(*ptr) += grow;
  1766. return 0;
  1767. }
  1768. void __ast_string_field_release_active(struct ast_string_field_pool *pool_head,
  1769. const ast_string_field ptr)
  1770. {
  1771. struct ast_string_field_pool *pool, *prev;
  1772. if (ptr == __ast_string_field_empty) {
  1773. return;
  1774. }
  1775. for (pool = pool_head, prev = NULL; pool; prev = pool, pool = pool->prev) {
  1776. if ((ptr >= pool->base) && (ptr <= (pool->base + pool->size))) {
  1777. pool->active -= AST_STRING_FIELD_ALLOCATION(ptr);
  1778. if (pool->active == 0) {
  1779. if (prev) {
  1780. prev->prev = pool->prev;
  1781. ast_free(pool);
  1782. } else {
  1783. pool->used = 0;
  1784. }
  1785. }
  1786. break;
  1787. }
  1788. }
  1789. }
  1790. void __ast_string_field_ptr_build_va(struct ast_string_field_mgr *mgr,
  1791. struct ast_string_field_pool **pool_head,
  1792. ast_string_field *ptr, const char *format, va_list ap)
  1793. {
  1794. size_t needed;
  1795. size_t available;
  1796. size_t space = (*pool_head)->size - (*pool_head)->used;
  1797. int res;
  1798. ssize_t grow;
  1799. char *target;
  1800. va_list ap2;
  1801. /* if the field already has space allocated, try to reuse it;
  1802. otherwise, try to use the empty space at the end of the current
  1803. pool
  1804. */
  1805. if (*ptr != __ast_string_field_empty) {
  1806. target = (char *) *ptr;
  1807. available = AST_STRING_FIELD_ALLOCATION(*ptr);
  1808. if (*ptr == mgr->last_alloc) {
  1809. available += space;
  1810. }
  1811. } else {
  1812. /* pool->used is always a multiple of ast_alignof(ast_string_field_allocation)
  1813. * so we don't need to re-align anything here.
  1814. */
  1815. target = (*pool_head)->base + (*pool_head)->used + ast_alignof(ast_string_field_allocation);
  1816. if (space > ast_alignof(ast_string_field_allocation)) {
  1817. available = space - ast_alignof(ast_string_field_allocation);
  1818. } else {
  1819. available = 0;
  1820. }
  1821. }
  1822. va_copy(ap2, ap);
  1823. res = vsnprintf(target, available, format, ap2);
  1824. va_end(ap2);
  1825. if (res < 0) {
  1826. /* Are we out of memory? */
  1827. return;
  1828. }
  1829. if (res == 0) {
  1830. __ast_string_field_release_active(*pool_head, *ptr);
  1831. *ptr = __ast_string_field_empty;
  1832. return;
  1833. }
  1834. needed = (size_t)res + 1; /* NUL byte */
  1835. if (needed > available) {
  1836. /* the allocation could not be satisfied using the field's current allocation
  1837. (if it has one), or the space available in the pool (if it does not). allocate
  1838. space for it, adding a new string pool if necessary.
  1839. */
  1840. if (!(target = (char *) __ast_string_field_alloc_space(mgr, pool_head, needed))) {
  1841. return;
  1842. }
  1843. vsprintf(target, format, ap);
  1844. va_end(ap); /* XXX va_end without va_start? */
  1845. __ast_string_field_release_active(*pool_head, *ptr);
  1846. *ptr = target;
  1847. } else if (*ptr != target) {
  1848. /* the allocation was satisfied using available space in the pool, but not
  1849. using the space already allocated to the field
  1850. */
  1851. __ast_string_field_release_active(*pool_head, *ptr);
  1852. mgr->last_alloc = *ptr = target;
  1853. ast_assert(needed < (ast_string_field_allocation)-1);
  1854. AST_STRING_FIELD_ALLOCATION(target) = (ast_string_field_allocation)needed;
  1855. (*pool_head)->used += ast_make_room_for(needed, ast_string_field_allocation);
  1856. (*pool_head)->active += needed;
  1857. } else if ((grow = (needed - AST_STRING_FIELD_ALLOCATION(*ptr))) > 0) {
  1858. /* the allocation was satisfied by using available space in the pool *and*
  1859. the field was the last allocated field from the pool, so it grew
  1860. */
  1861. AST_STRING_FIELD_ALLOCATION(*ptr) += grow;
  1862. (*pool_head)->used += ast_align_for(grow, ast_string_field_allocation);
  1863. (*pool_head)->active += grow;
  1864. }
  1865. }
  1866. void __ast_string_field_ptr_build(struct ast_string_field_mgr *mgr,
  1867. struct ast_string_field_pool **pool_head,
  1868. ast_string_field *ptr, const char *format, ...)
  1869. {
  1870. va_list ap;
  1871. va_start(ap, format);
  1872. __ast_string_field_ptr_build_va(mgr, pool_head, ptr, format, ap);
  1873. va_end(ap);
  1874. }
  1875. void *__ast_calloc_with_stringfields(unsigned int num_structs, size_t struct_size, size_t field_mgr_offset,
  1876. size_t field_mgr_pool_offset, size_t pool_size, const char *file,
  1877. int lineno, const char *func)
  1878. {
  1879. struct ast_string_field_mgr *mgr;
  1880. struct ast_string_field_pool *pool;
  1881. struct ast_string_field_pool **pool_head;
  1882. size_t pool_size_needed = sizeof(*pool) + pool_size;
  1883. size_t size_to_alloc = optimal_alloc_size(struct_size + pool_size_needed);
  1884. void *allocation;
  1885. unsigned int x;
  1886. #if defined(__AST_DEBUG_MALLOC)
  1887. if (!(allocation = __ast_calloc(num_structs, size_to_alloc, file, lineno, func))) {
  1888. return NULL;
  1889. }
  1890. #else
  1891. if (!(allocation = ast_calloc(num_structs, size_to_alloc))) {
  1892. return NULL;
  1893. }
  1894. #endif
  1895. for (x = 0; x < num_structs; x++) {
  1896. void *base = allocation + (size_to_alloc * x);
  1897. const char **p;
  1898. mgr = base + field_mgr_offset;
  1899. pool_head = base + field_mgr_pool_offset;
  1900. pool = base + struct_size;
  1901. p = (const char **) pool_head + 1;
  1902. while ((struct ast_string_field_mgr *) p != mgr) {
  1903. *p++ = __ast_string_field_empty;
  1904. }
  1905. mgr->embedded_pool = pool;
  1906. *pool_head = pool;
  1907. pool->size = size_to_alloc - struct_size - sizeof(*pool);
  1908. #if defined(__AST_DEBUG_MALLOC)
  1909. mgr->owner_file = file;
  1910. mgr->owner_func = func;
  1911. mgr->owner_line = lineno;
  1912. #endif
  1913. }
  1914. return allocation;
  1915. }
  1916. /* end of stringfields support */
  1917. AST_MUTEX_DEFINE_STATIC(fetchadd_m); /* used for all fetc&add ops */
  1918. int ast_atomic_fetchadd_int_slow(volatile int *p, int v)
  1919. {
  1920. int ret;
  1921. ast_mutex_lock(&fetchadd_m);
  1922. ret = *p;
  1923. *p += v;
  1924. ast_mutex_unlock(&fetchadd_m);
  1925. return ret;
  1926. }
  1927. /*! \brief
  1928. * get values from config variables.
  1929. */
  1930. int ast_get_timeval(const char *src, struct timeval *dst, struct timeval _default, int *consumed)
  1931. {
  1932. long double dtv = 0.0;
  1933. int scanned;
  1934. if (dst == NULL)
  1935. return -1;
  1936. *dst = _default;
  1937. if (ast_strlen_zero(src))
  1938. return -1;
  1939. /* only integer at the moment, but one day we could accept more formats */
  1940. if (sscanf(src, "%30Lf%n", &dtv, &scanned) > 0) {
  1941. dst->tv_sec = dtv;
  1942. dst->tv_usec = (dtv - dst->tv_sec) * 1000000.0;
  1943. if (consumed)
  1944. *consumed = scanned;
  1945. return 0;
  1946. } else
  1947. return -1;
  1948. }
  1949. /*! \brief
  1950. * get values from config variables.
  1951. */
  1952. int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed)
  1953. {
  1954. long t;
  1955. int scanned;
  1956. if (dst == NULL)
  1957. return -1;
  1958. *dst = _default;
  1959. if (ast_strlen_zero(src))
  1960. return -1;
  1961. /* only integer at the moment, but one day we could accept more formats */
  1962. if (sscanf(src, "%30ld%n", &t, &scanned) == 1) {
  1963. *dst = t;
  1964. if (consumed)
  1965. *consumed = scanned;
  1966. return 0;
  1967. } else
  1968. return -1;
  1969. }
  1970. void ast_enable_packet_fragmentation(int sock)
  1971. {
  1972. #if defined(HAVE_IP_MTU_DISCOVER)
  1973. int val = IP_PMTUDISC_DONT;
  1974. if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
  1975. ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
  1976. #endif /* HAVE_IP_MTU_DISCOVER */
  1977. }
  1978. int ast_mkdir(const char *path, int mode)
  1979. {
  1980. char *ptr;
  1981. int len = strlen(path), count = 0, x, piececount = 0;
  1982. char *tmp = ast_strdupa(path);
  1983. char **pieces;
  1984. char *fullpath = ast_alloca(len + 1);
  1985. int res = 0;
  1986. for (ptr = tmp; *ptr; ptr++) {
  1987. if (*ptr == '/')
  1988. count++;
  1989. }
  1990. /* Count the components to the directory path */
  1991. pieces = ast_alloca(count * sizeof(*pieces));
  1992. for (ptr = tmp; *ptr; ptr++) {
  1993. if (*ptr == '/') {
  1994. *ptr = '\0';
  1995. pieces[piececount++] = ptr + 1;
  1996. }
  1997. }
  1998. *fullpath = '\0';
  1999. for (x = 0; x < piececount; x++) {
  2000. /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
  2001. strcat(fullpath, "/");
  2002. strcat(fullpath, pieces[x]);
  2003. res = mkdir(fullpath, mode);
  2004. if (res && errno != EEXIST)
  2005. return errno;
  2006. }
  2007. return 0;
  2008. }
  2009. static int safe_mkdir(const char *base_path, char *path, int mode)
  2010. {
  2011. RAII_VAR(char *, absolute_path, NULL, ast_std_free);
  2012. absolute_path = realpath(path, NULL);
  2013. if (absolute_path) {
  2014. /* Path exists, but is it in the right place? */
  2015. if (!ast_begins_with(absolute_path, base_path)) {
  2016. return EPERM;
  2017. }
  2018. /* It is in the right place! */
  2019. return 0;
  2020. } else {
  2021. /* Path doesn't exist. */
  2022. /* The slash terminating the subpath we're checking */
  2023. char *path_term = strchr(path, '/');
  2024. /* True indicates the parent path is within base_path */
  2025. int parent_is_safe = 0;
  2026. int res;
  2027. while (path_term) {
  2028. RAII_VAR(char *, absolute_subpath, NULL, ast_std_free);
  2029. /* Truncate the path one past the slash */
  2030. char c = *(path_term + 1);
  2031. *(path_term + 1) = '\0';
  2032. absolute_subpath = realpath(path, NULL);
  2033. if (absolute_subpath) {
  2034. /* Subpath exists, but is it safe? */
  2035. parent_is_safe = ast_begins_with(
  2036. absolute_subpath, base_path);
  2037. } else if (parent_is_safe) {
  2038. /* Subpath does not exist, but parent is safe
  2039. * Create it */
  2040. res = mkdir(path, mode);
  2041. if (res != 0) {
  2042. ast_assert(errno != EEXIST);
  2043. return errno;
  2044. }
  2045. } else {
  2046. /* Subpath did not exist, parent was not safe
  2047. * Fail! */
  2048. errno = EPERM;
  2049. return errno;
  2050. }
  2051. /* Restore the path */
  2052. *(path_term + 1) = c;
  2053. /* Move on to the next slash */
  2054. path_term = strchr(path_term + 1, '/');
  2055. }
  2056. /* Now to build the final path, but only if it's safe */
  2057. if (!parent_is_safe) {
  2058. errno = EPERM;
  2059. return errno;
  2060. }
  2061. res = mkdir(path, mode);
  2062. if (res != 0 && errno != EEXIST) {
  2063. return errno;
  2064. }
  2065. return 0;
  2066. }
  2067. }
  2068. int ast_safe_mkdir(const char *base_path, const char *path, int mode)
  2069. {
  2070. RAII_VAR(char *, absolute_base_path, NULL, ast_std_free);
  2071. RAII_VAR(char *, p, NULL, ast_free);
  2072. if (base_path == NULL || path == NULL) {
  2073. errno = EFAULT;
  2074. return errno;
  2075. }
  2076. p = ast_strdup(path);
  2077. if (p == NULL) {
  2078. errno = ENOMEM;
  2079. return errno;
  2080. }
  2081. absolute_base_path = realpath(base_path, NULL);
  2082. if (absolute_base_path == NULL) {
  2083. return errno;
  2084. }
  2085. return safe_mkdir(absolute_base_path, p, mode);
  2086. }
  2087. static void utils_shutdown(void)
  2088. {
  2089. close(dev_urandom_fd);
  2090. dev_urandom_fd = -1;
  2091. #if defined(DEBUG_THREADS) && !defined(LOW_MEMORY)
  2092. ast_cli_unregister_multiple(utils_cli, ARRAY_LEN(utils_cli));
  2093. #endif
  2094. }
  2095. int ast_utils_init(void)
  2096. {
  2097. dev_urandom_fd = open("/dev/urandom", O_RDONLY);
  2098. base64_init();
  2099. #ifdef DEBUG_THREADS
  2100. #if !defined(LOW_MEMORY)
  2101. ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
  2102. #endif
  2103. #endif
  2104. ast_register_cleanup(utils_shutdown);
  2105. return 0;
  2106. }
  2107. /*!
  2108. *\brief Parse digest authorization header.
  2109. *\return Returns -1 if we have no auth or something wrong with digest.
  2110. *\note This function may be used for Digest request and responce header.
  2111. * request arg is set to nonzero, if we parse Digest Request.
  2112. * pedantic arg can be set to nonzero if we need to do addition Digest check.
  2113. */
  2114. int ast_parse_digest(const char *digest, struct ast_http_digest *d, int request, int pedantic) {
  2115. char *c;
  2116. struct ast_str *str = ast_str_create(16);
  2117. /* table of recognised keywords, and places where they should be copied */
  2118. const struct x {
  2119. const char *key;
  2120. const ast_string_field *field;
  2121. } *i, keys[] = {
  2122. { "username=", &d->username },
  2123. { "realm=", &d->realm },
  2124. { "nonce=", &d->nonce },
  2125. { "uri=", &d->uri },
  2126. { "domain=", &d->domain },
  2127. { "response=", &d->response },
  2128. { "cnonce=", &d->cnonce },
  2129. { "opaque=", &d->opaque },
  2130. /* Special cases that cannot be directly copied */
  2131. { "algorithm=", NULL },
  2132. { "qop=", NULL },
  2133. { "nc=", NULL },
  2134. { NULL, 0 },
  2135. };
  2136. if (ast_strlen_zero(digest) || !d || !str) {
  2137. ast_free(str);
  2138. return -1;
  2139. }
  2140. ast_str_set(&str, 0, "%s", digest);
  2141. c = ast_skip_blanks(ast_str_buffer(str));
  2142. if (strncasecmp(c, "Digest ", strlen("Digest "))) {
  2143. ast_log(LOG_WARNING, "Missing Digest.\n");
  2144. ast_free(str);
  2145. return -1;
  2146. }
  2147. c += strlen("Digest ");
  2148. /* lookup for keys/value pair */
  2149. while (c && *c && *(c = ast_skip_blanks(c))) {
  2150. /* find key */
  2151. for (i = keys; i->key != NULL; i++) {
  2152. char *src, *separator;
  2153. int unescape = 0;
  2154. if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
  2155. continue;
  2156. }
  2157. /* Found. Skip keyword, take text in quotes or up to the separator. */
  2158. c += strlen(i->key);
  2159. if (*c == '"') {
  2160. src = ++c;
  2161. separator = "\"";
  2162. unescape = 1;
  2163. } else {
  2164. src = c;
  2165. separator = ",";
  2166. }
  2167. strsep(&c, separator); /* clear separator and move ptr */
  2168. if (unescape) {
  2169. ast_unescape_c(src);
  2170. }
  2171. if (i->field) {
  2172. ast_string_field_ptr_set(d, i->field, src);
  2173. } else {
  2174. /* Special cases that require additional procesing */
  2175. if (!strcasecmp(i->key, "algorithm=")) {
  2176. if (strcasecmp(src, "MD5")) {
  2177. ast_log(LOG_WARNING, "Digest algorithm: \"%s\" not supported.\n", src);
  2178. ast_free(str);
  2179. return -1;
  2180. }
  2181. } else if (!strcasecmp(i->key, "qop=") && !strcasecmp(src, "auth")) {
  2182. d->qop = 1;
  2183. } else if (!strcasecmp(i->key, "nc=")) {
  2184. unsigned long u;
  2185. if (sscanf(src, "%30lx", &u) != 1) {
  2186. ast_log(LOG_WARNING, "Incorrect Digest nc value: \"%s\".\n", src);
  2187. ast_free(str);
  2188. return -1;
  2189. }
  2190. ast_string_field_set(d, nc, src);
  2191. }
  2192. }
  2193. break;
  2194. }
  2195. if (i->key == NULL) { /* not found, try ',' */
  2196. strsep(&c, ",");
  2197. }
  2198. }
  2199. ast_free(str);
  2200. /* Digest checkout */
  2201. if (ast_strlen_zero(d->realm) || ast_strlen_zero(d->nonce)) {
  2202. /* "realm" and "nonce" MUST be always exist */
  2203. return -1;
  2204. }
  2205. if (!request) {
  2206. /* Additional check for Digest response */
  2207. if (ast_strlen_zero(d->username) || ast_strlen_zero(d->uri) || ast_strlen_zero(d->response)) {
  2208. return -1;
  2209. }
  2210. if (pedantic && d->qop && (ast_strlen_zero(d->cnonce) || ast_strlen_zero(d->nc))) {
  2211. return -1;
  2212. }
  2213. }
  2214. return 0;
  2215. }
  2216. #ifndef __AST_DEBUG_MALLOC
  2217. int _ast_asprintf(char **ret, const char *file, int lineno, const char *func, const char *fmt, ...)
  2218. {
  2219. int res;
  2220. va_list ap;
  2221. va_start(ap, fmt);
  2222. if ((res = vasprintf(ret, fmt, ap)) == -1) {
  2223. MALLOC_FAILURE_MSG;
  2224. }
  2225. va_end(ap);
  2226. return res;
  2227. }
  2228. #endif
  2229. int ast_get_tid(void)
  2230. {
  2231. int ret = -1;
  2232. #if defined (__linux) && defined(SYS_gettid)
  2233. ret = syscall(SYS_gettid); /* available since Linux 1.4.11 */
  2234. #elif defined(__sun)
  2235. ret = pthread_self();
  2236. #elif defined(__APPLE__)
  2237. ret = mach_thread_self();
  2238. mach_port_deallocate(mach_task_self(), ret);
  2239. #elif defined(__FreeBSD__) && defined(HAVE_SYS_THR_H)
  2240. long lwpid;
  2241. thr_self(&lwpid); /* available since sys/thr.h creation 2003 */
  2242. ret = lwpid;
  2243. #endif
  2244. return ret;
  2245. }
  2246. char *ast_utils_which(const char *binary, char *fullpath, size_t fullpath_size)
  2247. {
  2248. const char *envPATH = getenv("PATH");
  2249. char *tpath, *path;
  2250. struct stat unused;
  2251. if (!envPATH) {
  2252. return NULL;
  2253. }
  2254. tpath = ast_strdupa(envPATH);
  2255. while ((path = strsep(&tpath, ":"))) {
  2256. snprintf(fullpath, fullpath_size, "%s/%s", path, binary);
  2257. if (!stat(fullpath, &unused)) {
  2258. return fullpath;
  2259. }
  2260. }
  2261. return NULL;
  2262. }
  2263. void ast_do_crash(void)
  2264. {
  2265. #if defined(DO_CRASH)
  2266. abort();
  2267. /*
  2268. * Just in case abort() doesn't work or something else super
  2269. * silly, and for Qwell's amusement.
  2270. */
  2271. *((int *) 0) = 0;
  2272. #endif /* defined(DO_CRASH) */
  2273. }
  2274. #if defined(AST_DEVMODE)
  2275. void __ast_assert_failed(int condition, const char *condition_str, const char *file, int line, const char *function)
  2276. {
  2277. /*
  2278. * Attempt to put it into the logger, but hope that at least
  2279. * someone saw the message on stderr ...
  2280. */
  2281. ast_log(__LOG_ERROR, file, line, function, "FRACK!, Failed assertion %s (%d)\n",
  2282. condition_str, condition);
  2283. fprintf(stderr, "FRACK!, Failed assertion %s (%d) at line %d in %s of %s\n",
  2284. condition_str, condition, line, function, file);
  2285. /* Generate a backtrace for the assert */
  2286. ast_log_backtrace();
  2287. /*
  2288. * Give the logger a chance to get the message out, just in case
  2289. * we abort(), or Asterisk crashes due to whatever problem just
  2290. * happened after we exit ast_assert().
  2291. */
  2292. usleep(1);
  2293. ast_do_crash();
  2294. }
  2295. #endif /* defined(AST_DEVMODE) */
  2296. char *ast_eid_to_str(char *s, int maxlen, struct ast_eid *eid)
  2297. {
  2298. int x;
  2299. char *os = s;
  2300. if (maxlen < 18) {
  2301. if (s && (maxlen > 0)) {
  2302. *s = '\0';
  2303. }
  2304. } else {
  2305. for (x = 0; x < 5; x++) {
  2306. sprintf(s, "%02hhx:", eid->eid[x]);
  2307. s += 3;
  2308. }
  2309. sprintf(s, "%02hhx", eid->eid[5]);
  2310. }
  2311. return os;
  2312. }
  2313. void ast_set_default_eid(struct ast_eid *eid)
  2314. {
  2315. #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_IFRU_IFRU_HWADDR)
  2316. int s, x = 0;
  2317. char eid_str[20];
  2318. struct ifreq ifr;
  2319. static const unsigned int MAXIF = 10;
  2320. s = socket(AF_INET, SOCK_STREAM, 0);
  2321. if (s < 0) {
  2322. return;
  2323. }
  2324. for (x = 0; x < MAXIF; x++) {
  2325. static const char *prefixes[] = { "eth", "em" };
  2326. unsigned int i;
  2327. for (i = 0; i < ARRAY_LEN(prefixes); i++) {
  2328. memset(&ifr, 0, sizeof(ifr));
  2329. snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", prefixes[i], x);
  2330. if (!ioctl(s, SIOCGIFHWADDR, &ifr)) {
  2331. break;
  2332. }
  2333. }
  2334. if (i == ARRAY_LEN(prefixes)) {
  2335. /* Try pciX#[1..N] */
  2336. for (i = 0; i < MAXIF; i++) {
  2337. memset(&ifr, 0, sizeof(ifr));
  2338. snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "pci%d#%u", x, i);
  2339. if (!ioctl(s, SIOCGIFHWADDR, &ifr)) {
  2340. break;
  2341. }
  2342. }
  2343. if (i == MAXIF) {
  2344. continue;
  2345. }
  2346. }
  2347. memcpy(eid, ((unsigned char *)&ifr.ifr_hwaddr) + 2, sizeof(*eid));
  2348. ast_debug(1, "Seeding global EID '%s' from '%s' using 'siocgifhwaddr'\n", ast_eid_to_str(eid_str, sizeof(eid_str), eid), ifr.ifr_name);
  2349. close(s);
  2350. return;
  2351. }
  2352. close(s);
  2353. #else
  2354. #if defined(ifa_broadaddr) && !defined(SOLARIS)
  2355. char eid_str[20];
  2356. struct ifaddrs *ifap;
  2357. if (getifaddrs(&ifap) == 0) {
  2358. struct ifaddrs *p;
  2359. for (p = ifap; p; p = p->ifa_next) {
  2360. if ((p->ifa_addr->sa_family == AF_LINK) && !(p->ifa_flags & IFF_LOOPBACK) && (p->ifa_flags & IFF_RUNNING)) {
  2361. struct sockaddr_dl* sdp = (struct sockaddr_dl*) p->ifa_addr;
  2362. memcpy(&(eid->eid), sdp->sdl_data + sdp->sdl_nlen, 6);
  2363. ast_debug(1, "Seeding global EID '%s' from '%s' using 'getifaddrs'\n", ast_eid_to_str(eid_str, sizeof(eid_str), eid), p->ifa_name);
  2364. freeifaddrs(ifap);
  2365. return;
  2366. }
  2367. }
  2368. freeifaddrs(ifap);
  2369. }
  2370. #endif
  2371. #endif
  2372. ast_debug(1, "No ethernet interface found for seeding global EID. You will have to set it manually.\n");
  2373. }
  2374. int ast_str_to_eid(struct ast_eid *eid, const char *s)
  2375. {
  2376. unsigned int eid_int[6];
  2377. int x;
  2378. if (sscanf(s, "%2x:%2x:%2x:%2x:%2x:%2x", &eid_int[0], &eid_int[1], &eid_int[2],
  2379. &eid_int[3], &eid_int[4], &eid_int[5]) != 6) {
  2380. return -1;
  2381. }
  2382. for (x = 0; x < 6; x++) {
  2383. eid->eid[x] = eid_int[x];
  2384. }
  2385. return 0;
  2386. }
  2387. int ast_eid_cmp(const struct ast_eid *eid1, const struct ast_eid *eid2)
  2388. {
  2389. return memcmp(eid1, eid2, sizeof(*eid1));
  2390. }