utils.c 69 KB

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