utils.c 77 KB

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