func_strings.c 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2005-2006, Digium, Inc.
  5. * Portions Copyright (C) 2005, Tilghman Lesher. All rights reserved.
  6. * Portions Copyright (C) 2005, Anthony Minessale II
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*! \file
  19. *
  20. * \brief String manipulation dialplan functions
  21. *
  22. * \author Tilghman Lesher
  23. * \author Anothony Minessale II
  24. * \ingroup functions
  25. */
  26. /*** MODULEINFO
  27. <support_level>core</support_level>
  28. ***/
  29. #include "asterisk.h"
  30. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  31. #include <regex.h>
  32. #include <ctype.h>
  33. #include "asterisk/module.h"
  34. #include "asterisk/channel.h"
  35. #include "asterisk/pbx.h"
  36. #include "asterisk/utils.h"
  37. #include "asterisk/app.h"
  38. #include "asterisk/localtime.h"
  39. #include "asterisk/test.h"
  40. AST_THREADSTORAGE(result_buf);
  41. AST_THREADSTORAGE(tmp_buf);
  42. /*** DOCUMENTATION
  43. <function name="FIELDQTY" language="en_US">
  44. <synopsis>
  45. Count the fields with an arbitrary delimiter
  46. </synopsis>
  47. <syntax>
  48. <parameter name="varname" required="true" />
  49. <parameter name="delim" required="true" />
  50. </syntax>
  51. <description>
  52. <para>The delimiter may be specified as a special or extended ASCII character, by encoding it. The characters
  53. <literal>\n</literal>, <literal>\r</literal>, and <literal>\t</literal> are all recognized as the newline,
  54. carriage return, and tab characters, respectively. Also, octal and hexadecimal specifications are recognized
  55. by the patterns <literal>\0nnn</literal> and <literal>\xHH</literal>, respectively. For example, if you wanted
  56. to encode a comma as the delimiter, you could use either <literal>\054</literal> or <literal>\x2C</literal>.</para>
  57. <para>Example: If ${example} contains <literal>ex-amp-le</literal>, then ${FIELDQTY(example,-)} returns 3.</para>
  58. </description>
  59. </function>
  60. <function name="FIELDNUM" language="en_US">
  61. <synopsis>
  62. Return the 1-based offset of a field in a list
  63. </synopsis>
  64. <syntax>
  65. <parameter name="varname" required="true" />
  66. <parameter name="delim" required="true" />
  67. <parameter name="value" required="true" />
  68. </syntax>
  69. <description>
  70. <para>Search the variable named <replaceable>varname</replaceable> for the string <replaceable>value</replaceable>
  71. delimited by <replaceable>delim</replaceable> and return a 1-based offset as to its location. If not found
  72. or an error occured, return <literal>0</literal>.</para>
  73. <para>The delimiter may be specified as a special or extended ASCII character, by encoding it. The characters
  74. <literal>\n</literal>, <literal>\r</literal>, and <literal>\t</literal> are all recognized as the newline,
  75. carriage return, and tab characters, respectively. Also, octal and hexadecimal specifications are recognized
  76. by the patterns <literal>\0nnn</literal> and <literal>\xHH</literal>, respectively. For example, if you wanted
  77. to encode a comma as the delimiter, you could use either <literal>\054</literal> or <literal>\x2C</literal>.</para>
  78. <para>Example: If ${example} contains <literal>ex-amp-le</literal>, then ${FIELDNUM(example,-,amp)} returns 2.</para>
  79. </description>
  80. </function>
  81. <function name="LISTFILTER" language="en_US">
  82. <synopsis>Remove an item from a list, by name.</synopsis>
  83. <syntax>
  84. <parameter name="varname" required="true" />
  85. <parameter name="delim" required="true" default="," />
  86. <parameter name="value" required="true" />
  87. </syntax>
  88. <description>
  89. <para>Remove <replaceable>value</replaceable> from the list contained in the <replaceable>varname</replaceable>
  90. variable, where the list delimiter is specified by the <replaceable>delim</replaceable> parameter. This is
  91. very useful for removing a single channel name from a list of channels, for example.</para>
  92. </description>
  93. </function>
  94. <function name="FILTER" language="en_US">
  95. <synopsis>
  96. Filter the string to include only the allowed characters
  97. </synopsis>
  98. <syntax>
  99. <parameter name="allowed-chars" required="true" />
  100. <parameter name="string" required="true" />
  101. </syntax>
  102. <description>
  103. <para>Permits all characters listed in <replaceable>allowed-chars</replaceable>,
  104. filtering all others outs. In addition to literally listing the characters,
  105. you may also use ranges of characters (delimited by a <literal>-</literal></para>
  106. <para>Hexadecimal characters started with a <literal>\x</literal>(i.e. \x20)</para>
  107. <para>Octal characters started with a <literal>\0</literal> (i.e. \040)</para>
  108. <para>Also <literal>\t</literal>,<literal>\n</literal> and <literal>\r</literal> are recognized.</para>
  109. <note><para>If you want the <literal>-</literal> character it needs to be prefixed with a
  110. <literal>\</literal></para></note>
  111. </description>
  112. </function>
  113. <function name="REPLACE" language="en_US">
  114. <synopsis>
  115. Replace a set of characters in a given string with another character.
  116. </synopsis>
  117. <syntax>
  118. <parameter name="varname" required="true" />
  119. <parameter name="find-chars" required="true" />
  120. <parameter name="replace-char" required="false" />
  121. </syntax>
  122. <description>
  123. <para>Iterates through a string replacing all the <replaceable>find-chars</replaceable> with
  124. <replaceable>replace-char</replaceable>. <replaceable>replace-char</replaceable> may be either
  125. empty or contain one character. If empty, all <replaceable>find-chars</replaceable> will be
  126. deleted from the output.</para>
  127. <note><para>The replacement only occurs in the output. The original variable is not
  128. altered.</para></note>
  129. </description>
  130. </function>
  131. <function name="STRREPLACE" language="en_US">
  132. <synopsis>
  133. Replace instances of a substring within a string with another string.
  134. </synopsis>
  135. <syntax>
  136. <parameter name="varname" required="true" />
  137. <parameter name="find-string" required="true" />
  138. <parameter name="replace-string" required="false" />
  139. <parameter name="max-replacements" required="false" />
  140. </syntax>
  141. <description>
  142. <para>Searches for all instances of the <replaceable>find-string</replaceable> in provided variable and
  143. replaces them with <replaceable>replace-string</replaceable>. If <replaceable>replace-string</replaceable>
  144. is an empty string, this will effecively delete that substring. If <replaceable>max-replacements</replaceable>
  145. is specified, this function will stop after performing replacements <replaceable>max-replacements</replaceable> times.</para>
  146. <note><para>The replacement only occurs in the output. The original variable is not altered.</para></note>
  147. </description>
  148. </function>
  149. <function name="PASSTHRU" language="en_US">
  150. <synopsis>
  151. Pass the given argument back as a value.
  152. </synopsis>
  153. <syntax>
  154. <parameter name="string" required="false" />
  155. </syntax>
  156. <description>
  157. <para>Literally returns the given <replaceable>string</replaceable>. The intent is to permit
  158. other dialplan functions which take a variable name as an argument to be able to take a literal
  159. string, instead.</para>
  160. <note><para>The functions which take a variable name need to be passed var and not
  161. ${var}. Similarly, use PASSTHRU() and not ${PASSTHRU()}.</para></note>
  162. <para>Example: ${CHANNEL} contains SIP/321-1</para>
  163. <para> ${CUT(PASSTHRU(${CUT(CHANNEL,-,1)}),/,2)}) will return 321</para>
  164. </description>
  165. </function>
  166. <function name="REGEX" language="en_US">
  167. <synopsis>
  168. Check string against a regular expression.
  169. </synopsis>
  170. <syntax argsep=" ">
  171. <parameter name="&quot;regular expression&quot;" required="true" />
  172. <parameter name="string" required="true" />
  173. </syntax>
  174. <description>
  175. <para>Return <literal>1</literal> on regular expression match or <literal>0</literal> otherwise</para>
  176. <para>Please note that the space following the double quotes separating the
  177. regex from the data is optional and if present, is skipped. If a space is
  178. desired at the beginning of the data, then put two spaces there; the second
  179. will not be skipped.</para>
  180. </description>
  181. </function>
  182. <application name="ClearHash" language="en_US">
  183. <synopsis>
  184. Clear the keys from a specified hashname.
  185. </synopsis>
  186. <syntax>
  187. <parameter name="hashname" required="true" />
  188. </syntax>
  189. <description>
  190. <para>Clears all keys out of the specified <replaceable>hashname</replaceable>.</para>
  191. </description>
  192. </application>
  193. <function name="HASH" language="en_US">
  194. <synopsis>
  195. Implementation of a dialplan associative array
  196. </synopsis>
  197. <syntax>
  198. <parameter name="hashname" required="true" />
  199. <parameter name="hashkey" />
  200. </syntax>
  201. <description>
  202. <para>In two arguments mode, gets and sets values to corresponding keys within
  203. a named associative array. The single-argument mode will only work when assigned
  204. to from a function defined by func_odbc</para>
  205. </description>
  206. </function>
  207. <function name="HASHKEYS" language="en_US">
  208. <synopsis>
  209. Retrieve the keys of the HASH() function.
  210. </synopsis>
  211. <syntax>
  212. <parameter name="hashname" required="true" />
  213. </syntax>
  214. <description>
  215. <para>Returns a comma-delimited list of the current keys of the associative array
  216. defined by the HASH() function. Note that if you iterate over the keys of
  217. the result, adding keys during iteration will cause the result of the HASHKEYS()
  218. function to change.</para>
  219. </description>
  220. </function>
  221. <function name="KEYPADHASH" language="en_US">
  222. <synopsis>
  223. Hash the letters in string into equivalent keypad numbers.
  224. </synopsis>
  225. <syntax>
  226. <parameter name="string" required="true" />
  227. </syntax>
  228. <description>
  229. <para>Example: ${KEYPADHASH(Les)} returns "537"</para>
  230. </description>
  231. </function>
  232. <function name="ARRAY" language="en_US">
  233. <synopsis>
  234. Allows setting multiple variables at once.
  235. </synopsis>
  236. <syntax>
  237. <parameter name="var1" required="true" />
  238. <parameter name="var2" required="false" multiple="true" />
  239. <parameter name="varN" required="false" />
  240. </syntax>
  241. <description>
  242. <para>The comma-delimited list passed as a value to which the function is set will
  243. be interpreted as a set of values to which the comma-delimited list of
  244. variable names in the argument should be set.</para>
  245. <para>Example: Set(ARRAY(var1,var2)=1,2) will set var1 to 1 and var2 to 2</para>
  246. </description>
  247. </function>
  248. <function name="STRPTIME" language="en_US">
  249. <synopsis>
  250. Returns the epoch of the arbitrary date/time string structured as described by the format.
  251. </synopsis>
  252. <syntax>
  253. <parameter name="datetime" required="true" />
  254. <parameter name="timezone" required="true" />
  255. <parameter name="format" required="true" />
  256. </syntax>
  257. <description>
  258. <para>This is useful for converting a date into <literal>EPOCH</literal> time,
  259. possibly to pass to an application like SayUnixTime or to calculate the difference
  260. between the two date strings</para>
  261. <para>Example: ${STRPTIME(2006-03-01 07:30:35,America/Chicago,%Y-%m-%d %H:%M:%S)} returns 1141219835</para>
  262. </description>
  263. </function>
  264. <function name="STRFTIME" language="en_US">
  265. <synopsis>
  266. Returns the current date/time in the specified format.
  267. </synopsis>
  268. <syntax>
  269. <parameter name="epoch" />
  270. <parameter name="timezone" />
  271. <parameter name="format" />
  272. </syntax>
  273. <description>
  274. <para>STRFTIME supports all of the same formats as the underlying C function
  275. <emphasis>strftime(3)</emphasis>.
  276. It also supports the following format: <literal>%[n]q</literal> - fractions of a second,
  277. with leading zeros.</para>
  278. <para>Example: <literal>%3q</literal> will give milliseconds and <literal>%1q</literal>
  279. will give tenths of a second. The default is set at milliseconds (n=3).
  280. The common case is to use it in combination with %S, as in <literal>%S.%3q</literal>.</para>
  281. </description>
  282. <see-also>
  283. <ref type="manpage">strftime(3)</ref>
  284. </see-also>
  285. </function>
  286. <function name="EVAL" language="en_US">
  287. <synopsis>
  288. Evaluate stored variables
  289. </synopsis>
  290. <syntax>
  291. <parameter name="variable" required="true" />
  292. </syntax>
  293. <description>
  294. <para>Using EVAL basically causes a string to be evaluated twice.
  295. When a variable or expression is in the dialplan, it will be
  296. evaluated at runtime. However, if the results of the evaluation
  297. is in fact another variable or expression, using EVAL will have it
  298. evaluated a second time.</para>
  299. <para>Example: If the <variable>MYVAR</variable> contains
  300. <variable>OTHERVAR</variable>, then the result of ${EVAL(
  301. <variable>MYVAR</variable>)} in the dialplan will be the
  302. contents of <variable>OTHERVAR</variable>. Normally just
  303. putting <variable>MYVAR</variable> in the dialplan the result
  304. would be <variable>OTHERVAR</variable>.</para>
  305. </description>
  306. </function>
  307. <function name="TOUPPER" language="en_US">
  308. <synopsis>
  309. Convert string to all uppercase letters.
  310. </synopsis>
  311. <syntax>
  312. <parameter name="string" required="true" />
  313. </syntax>
  314. <description>
  315. <para>Example: ${TOUPPER(Example)} returns "EXAMPLE"</para>
  316. </description>
  317. </function>
  318. <function name="TOLOWER" language="en_US">
  319. <synopsis>
  320. Convert string to all lowercase letters.
  321. </synopsis>
  322. <syntax>
  323. <parameter name="string" required="true" />
  324. </syntax>
  325. <description>
  326. <para>Example: ${TOLOWER(Example)} returns "example"</para>
  327. </description>
  328. </function>
  329. <function name="LEN" language="en_US">
  330. <synopsis>
  331. Return the length of the string given.
  332. </synopsis>
  333. <syntax>
  334. <parameter name="string" required="true" />
  335. </syntax>
  336. <description>
  337. <para>Example: ${LEN(example)} returns 7</para>
  338. </description>
  339. </function>
  340. <function name="QUOTE" language="en_US">
  341. <synopsis>
  342. Quotes a given string, escaping embedded quotes as necessary
  343. </synopsis>
  344. <syntax>
  345. <parameter name="string" required="true" />
  346. </syntax>
  347. <description>
  348. <para>Example: ${QUOTE(ab"c"de)} will return ""ab\"c\"de""</para>
  349. </description>
  350. </function>
  351. <function name="CSV_QUOTE" language="en_US">
  352. <synopsis>
  353. Quotes a given string for use in a CSV file, escaping embedded quotes as necessary
  354. </synopsis>
  355. <syntax>
  356. <parameter name="string" required="true" />
  357. </syntax>
  358. <description>
  359. <para>Example: ${CSV_QUOTE("a,b" 123)} will return """a,b"" 123"</para>
  360. </description>
  361. </function>
  362. <function name="SHIFT" language="en_US">
  363. <synopsis>
  364. Removes and returns the first item off of a variable containing delimited text
  365. </synopsis>
  366. <syntax>
  367. <parameter name="varname" required="true" />
  368. <parameter name="delimiter" required="false" default="," />
  369. </syntax>
  370. <description>
  371. <para>Example:</para>
  372. <para>exten => s,1,Set(array=one,two,three)</para>
  373. <para>exten => s,n,While($["${SET(var=${SHIFT(array)})}" != ""])</para>
  374. <para>exten => s,n,NoOp(var is ${var})</para>
  375. <para>exten => s,n,EndWhile</para>
  376. <para>This would iterate over each value in array, left to right, and
  377. would result in NoOp(var is one), NoOp(var is two), and
  378. NoOp(var is three) being executed.
  379. </para>
  380. </description>
  381. </function>
  382. <function name="POP" language="en_US">
  383. <synopsis>
  384. Removes and returns the last item off of a variable containing delimited text
  385. </synopsis>
  386. <syntax>
  387. <parameter name="varname" required="true" />
  388. <parameter name="delimiter" required="false" default="," />
  389. </syntax>
  390. <description>
  391. <para>Example:</para>
  392. <para>exten => s,1,Set(array=one,two,three)</para>
  393. <para>exten => s,n,While($["${SET(var=${POP(array)})}" != ""])</para>
  394. <para>exten => s,n,NoOp(var is ${var})</para>
  395. <para>exten => s,n,EndWhile</para>
  396. <para>This would iterate over each value in array, right to left, and
  397. would result in NoOp(var is three), NoOp(var is two), and
  398. NoOp(var is one) being executed.
  399. </para>
  400. </description>
  401. </function>
  402. <function name="PUSH" language="en_US">
  403. <synopsis>
  404. Appends one or more values to the end of a variable containing delimited text
  405. </synopsis>
  406. <syntax>
  407. <parameter name="varname" required="true" />
  408. <parameter name="delimiter" required="false" default="," />
  409. </syntax>
  410. <description>
  411. <para>Example: Set(PUSH(array)=one,two,three) would append one,
  412. two, and three to the end of the values stored in the variable
  413. "array".
  414. </para>
  415. </description>
  416. </function>
  417. <function name="UNSHIFT" language="en_US">
  418. <synopsis>
  419. Inserts one or more values to the beginning of a variable containing delimited text
  420. </synopsis>
  421. <syntax>
  422. <parameter name="varname" required="true" />
  423. <parameter name="delimiter" required="false" default="," />
  424. </syntax>
  425. <description>
  426. <para>Example: Set(UNSHIFT(array)=one,two,three) would insert one,
  427. two, and three before the values stored in the variable
  428. "array".
  429. </para>
  430. </description>
  431. </function>
  432. ***/
  433. static int function_fieldqty_helper(struct ast_channel *chan, const char *cmd,
  434. char *parse, char *buf, struct ast_str **sbuf, ssize_t len)
  435. {
  436. char *varsubst;
  437. struct ast_str *str = ast_str_thread_get(&result_buf, 16);
  438. int fieldcount = 0;
  439. AST_DECLARE_APP_ARGS(args,
  440. AST_APP_ARG(varname);
  441. AST_APP_ARG(delim);
  442. );
  443. char delim[2] = "";
  444. size_t delim_used;
  445. if (!str) {
  446. return -1;
  447. }
  448. AST_STANDARD_APP_ARGS(args, parse);
  449. if (args.delim) {
  450. ast_get_encoded_char(args.delim, delim, &delim_used);
  451. varsubst = ast_alloca(strlen(args.varname) + 4);
  452. sprintf(varsubst, "${%s}", args.varname);
  453. ast_str_substitute_variables(&str, 0, chan, varsubst);
  454. if (ast_str_strlen(str) == 0) {
  455. fieldcount = 0;
  456. } else {
  457. char *varval = ast_str_buffer(str);
  458. while (strsep(&varval, delim)) {
  459. fieldcount++;
  460. }
  461. }
  462. } else {
  463. fieldcount = 1;
  464. }
  465. if (sbuf) {
  466. ast_str_set(sbuf, len, "%d", fieldcount);
  467. } else {
  468. snprintf(buf, len, "%d", fieldcount);
  469. }
  470. return 0;
  471. }
  472. static int function_fieldqty(struct ast_channel *chan, const char *cmd,
  473. char *parse, char *buf, size_t len)
  474. {
  475. return function_fieldqty_helper(chan, cmd, parse, buf, NULL, len);
  476. }
  477. static int function_fieldqty_str(struct ast_channel *chan, const char *cmd,
  478. char *parse, struct ast_str **buf, ssize_t len)
  479. {
  480. return function_fieldqty_helper(chan, cmd, parse, NULL, buf, len);
  481. }
  482. static struct ast_custom_function fieldqty_function = {
  483. .name = "FIELDQTY",
  484. .read = function_fieldqty,
  485. .read2 = function_fieldqty_str,
  486. };
  487. static int function_fieldnum_helper(struct ast_channel *chan, const char *cmd,
  488. char *parse, char *buf, struct ast_str **sbuf, ssize_t len)
  489. {
  490. char *varsubst, *field;
  491. struct ast_str *str = ast_str_thread_get(&result_buf, 16);
  492. int fieldindex = 0, res = 0;
  493. AST_DECLARE_APP_ARGS(args,
  494. AST_APP_ARG(varname);
  495. AST_APP_ARG(delim);
  496. AST_APP_ARG(field);
  497. );
  498. char delim[2] = "";
  499. size_t delim_used;
  500. if (!str) {
  501. return -1;
  502. }
  503. AST_STANDARD_APP_ARGS(args, parse);
  504. if (args.argc < 3) {
  505. ast_log(LOG_ERROR, "Usage: FIELDNUM(<listname>,<delimiter>,<fieldvalue>)\n");
  506. res = -1;
  507. } else {
  508. varsubst = ast_alloca(strlen(args.varname) + 4);
  509. sprintf(varsubst, "${%s}", args.varname);
  510. ast_str_substitute_variables(&str, 0, chan, varsubst);
  511. if (ast_str_strlen(str) == 0 || ast_strlen_zero(args.delim)) {
  512. fieldindex = 0;
  513. } else if (ast_get_encoded_char(args.delim, delim, &delim_used) == -1) {
  514. res = -1;
  515. } else {
  516. char *varval = ast_str_buffer(str);
  517. while ((field = strsep(&varval, delim)) != NULL) {
  518. fieldindex++;
  519. if (!strcasecmp(field, args.field)) {
  520. break;
  521. }
  522. }
  523. if (!field) {
  524. fieldindex = 0;
  525. }
  526. res = 0;
  527. }
  528. }
  529. if (sbuf) {
  530. ast_str_set(sbuf, len, "%d", fieldindex);
  531. } else {
  532. snprintf(buf, len, "%d", fieldindex);
  533. }
  534. return res;
  535. }
  536. static int function_fieldnum(struct ast_channel *chan, const char *cmd,
  537. char *parse, char *buf, size_t len)
  538. {
  539. return function_fieldnum_helper(chan, cmd, parse, buf, NULL, len);
  540. }
  541. static int function_fieldnum_str(struct ast_channel *chan, const char *cmd,
  542. char *parse, struct ast_str **buf, ssize_t len)
  543. {
  544. return function_fieldnum_helper(chan, cmd, parse, NULL, buf, len);
  545. }
  546. static struct ast_custom_function fieldnum_function = {
  547. .name = "FIELDNUM",
  548. .read = function_fieldnum,
  549. .read2 = function_fieldnum_str,
  550. };
  551. static int listfilter(struct ast_channel *chan, const char *cmd, char *parse, char *buf, struct ast_str **bufstr, ssize_t len)
  552. {
  553. AST_DECLARE_APP_ARGS(args,
  554. AST_APP_ARG(listname);
  555. AST_APP_ARG(delimiter);
  556. AST_APP_ARG(fieldvalue);
  557. );
  558. struct ast_str *orig_list = ast_str_thread_get(&tmp_buf, 16);
  559. const char *begin, *cur, *next;
  560. int dlen, flen, first = 1;
  561. struct ast_str *result, **result_ptr = &result;
  562. char *delim, *varsubst;
  563. AST_STANDARD_APP_ARGS(args, parse);
  564. if (buf) {
  565. if (!(result = ast_str_thread_get(&result_buf, 16))) {
  566. return -1;
  567. }
  568. } else {
  569. /* Place the result directly into the output buffer */
  570. result_ptr = bufstr;
  571. }
  572. if (args.argc < 3) {
  573. ast_log(LOG_ERROR, "Usage: LISTFILTER(<listname>,<delimiter>,<fieldvalue>)\n");
  574. return -1;
  575. }
  576. varsubst = ast_alloca(strlen(args.listname) + 4);
  577. sprintf(varsubst, "${%s}", args.listname);
  578. /* If we don't lock the channel, the variable could disappear out from underneath us. */
  579. if (chan) {
  580. ast_channel_lock(chan);
  581. }
  582. ast_str_substitute_variables(&orig_list, 0, chan, varsubst);
  583. if (!ast_str_strlen(orig_list)) {
  584. if (chan) {
  585. ast_channel_unlock(chan);
  586. }
  587. return -1;
  588. }
  589. /* If the string isn't there, just copy out the string and be done with it. */
  590. if (!strstr(ast_str_buffer(orig_list), args.fieldvalue)) {
  591. if (buf) {
  592. ast_copy_string(buf, ast_str_buffer(orig_list), len);
  593. } else {
  594. ast_str_set(result_ptr, len, "%s", ast_str_buffer(orig_list));
  595. }
  596. if (chan) {
  597. ast_channel_unlock(chan);
  598. }
  599. return 0;
  600. }
  601. dlen = strlen(args.delimiter);
  602. delim = ast_alloca(dlen + 1);
  603. ast_get_encoded_str(args.delimiter, delim, dlen + 1);
  604. if ((dlen = strlen(delim)) == 0) {
  605. delim = ",";
  606. dlen = 1;
  607. }
  608. flen = strlen(args.fieldvalue);
  609. ast_str_reset(*result_ptr);
  610. /* Enough space for any result */
  611. if (len > -1) {
  612. ast_str_make_space(result_ptr, len ? len : ast_str_strlen(orig_list) + 1);
  613. }
  614. begin = ast_str_buffer(orig_list);
  615. next = strstr(begin, delim);
  616. do {
  617. /* Find next boundary */
  618. if (next) {
  619. cur = next;
  620. next = strstr(cur + dlen, delim);
  621. } else {
  622. cur = strchr(begin + dlen, '\0');
  623. }
  624. if (flen == cur - begin && !strncmp(begin, args.fieldvalue, flen)) {
  625. /* Skip field */
  626. begin += flen + dlen;
  627. } else {
  628. /* Copy field to output */
  629. if (!first) {
  630. ast_str_append(result_ptr, len, "%s", delim);
  631. }
  632. ast_str_append_substr(result_ptr, len, begin, cur - begin);
  633. first = 0;
  634. begin = cur + dlen;
  635. }
  636. } while (*cur != '\0');
  637. if (chan) {
  638. ast_channel_unlock(chan);
  639. }
  640. if (buf) {
  641. ast_copy_string(buf, ast_str_buffer(result), len);
  642. }
  643. return 0;
  644. }
  645. static int listfilter_read(struct ast_channel *chan, const char *cmd, char *parse, char *buf, size_t len)
  646. {
  647. return listfilter(chan, cmd, parse, buf, NULL, len);
  648. }
  649. static int listfilter_read2(struct ast_channel *chan, const char *cmd, char *parse, struct ast_str **buf, ssize_t len)
  650. {
  651. return listfilter(chan, cmd, parse, NULL, buf, len);
  652. }
  653. static struct ast_custom_function listfilter_function = {
  654. .name = "LISTFILTER",
  655. .read = listfilter_read,
  656. .read2 = listfilter_read2,
  657. };
  658. static int filter(struct ast_channel *chan, const char *cmd, char *parse, char *buf,
  659. size_t len)
  660. {
  661. AST_DECLARE_APP_ARGS(args,
  662. AST_APP_ARG(allowed);
  663. AST_APP_ARG(string);
  664. );
  665. char *outbuf = buf;
  666. unsigned char ac;
  667. char allowed[256] = "";
  668. size_t allowedlen = 0;
  669. int32_t bitfield[8] = { 0, }; /* 256 bits */
  670. AST_STANDARD_RAW_ARGS(args, parse);
  671. if (!args.string) {
  672. ast_log(LOG_ERROR, "Usage: FILTER(<allowed-chars>,<string>)\n");
  673. return -1;
  674. }
  675. if (args.allowed[0] == '"' && !ast_opt_dont_warn) {
  676. ast_log(LOG_WARNING, "FILTER allowed characters includes the quote (\") character. This may not be what you want.\n");
  677. }
  678. /* Expand ranges */
  679. for (; *(args.allowed);) {
  680. char c1 = 0, c2 = 0;
  681. size_t consumed = 0;
  682. if (ast_get_encoded_char(args.allowed, &c1, &consumed))
  683. return -1;
  684. args.allowed += consumed;
  685. if (*(args.allowed) == '-') {
  686. if (ast_get_encoded_char(args.allowed + 1, &c2, &consumed))
  687. c2 = c1;
  688. args.allowed += consumed + 1;
  689. if ((unsigned char) c2 < (unsigned char) c1 && !ast_opt_dont_warn) {
  690. ast_log(LOG_WARNING, "Range wrapping in FILTER(%s,%s). This may not be what you want.\n", parse, args.string);
  691. }
  692. /*!\note
  693. * Looks a little strange, until you realize that we can overflow
  694. * the size of a char.
  695. */
  696. for (ac = (unsigned char) c1; ac != (unsigned char) c2; ac++) {
  697. bitfield[ac / 32] |= 1 << (ac % 32);
  698. }
  699. bitfield[ac / 32] |= 1 << (ac % 32);
  700. ast_debug(4, "c1=%d, c2=%d\n", c1, c2);
  701. } else {
  702. ac = (unsigned char) c1;
  703. ast_debug(4, "c1=%d, consumed=%d, args.allowed=%s\n", c1, (int) consumed, args.allowed - consumed);
  704. bitfield[ac / 32] |= 1 << (ac % 32);
  705. }
  706. }
  707. for (ac = 1; ac != 0; ac++) {
  708. if (bitfield[ac / 32] & (1 << (ac % 32))) {
  709. allowed[allowedlen++] = ac;
  710. }
  711. }
  712. ast_debug(1, "Allowed: %s\n", allowed);
  713. for (; *(args.string) && (buf + len - 1 > outbuf); (args.string)++) {
  714. if (strchr(allowed, *(args.string)))
  715. *outbuf++ = *(args.string);
  716. }
  717. *outbuf = '\0';
  718. return 0;
  719. }
  720. static struct ast_custom_function filter_function = {
  721. .name = "FILTER",
  722. .read = filter,
  723. };
  724. static int replace(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
  725. {
  726. AST_DECLARE_APP_ARGS(args,
  727. AST_APP_ARG(varname);
  728. AST_APP_ARG(find);
  729. AST_APP_ARG(replace);
  730. );
  731. char *strptr, *varsubst;
  732. RAII_VAR(struct ast_str *, str, ast_str_create(16), ast_free);
  733. char find[256]; /* Only 256 characters possible */
  734. char replace[2] = "";
  735. size_t unused;
  736. AST_STANDARD_APP_ARGS(args, data);
  737. if (!str) {
  738. return -1;
  739. }
  740. if (args.argc < 2) {
  741. ast_log(LOG_ERROR, "Usage: %s(<varname>,<search-chars>[,<replace-char>])\n", cmd);
  742. return -1;
  743. }
  744. /* Decode escapes */
  745. ast_get_encoded_str(args.find, find, sizeof(find));
  746. ast_get_encoded_char(args.replace, replace, &unused);
  747. if (ast_strlen_zero(find) || ast_strlen_zero(args.varname)) {
  748. ast_log(LOG_ERROR, "The characters to search for and the variable name must not be empty.\n");
  749. return -1;
  750. }
  751. varsubst = ast_alloca(strlen(args.varname) + 4);
  752. sprintf(varsubst, "${%s}", args.varname);
  753. ast_str_substitute_variables(&str, 0, chan, varsubst);
  754. if (!ast_str_strlen(str)) {
  755. /* Blank, nothing to replace */
  756. return -1;
  757. }
  758. ast_debug(3, "String to search: (%s)\n", ast_str_buffer(str));
  759. ast_debug(3, "Characters to find: (%s)\n", find);
  760. ast_debug(3, "Character to replace with: (%s)\n", replace);
  761. for (strptr = ast_str_buffer(str); *strptr; strptr++) {
  762. /* buf is already a mutable buffer, so we construct the result
  763. * directly there */
  764. if (strchr(find, *strptr)) {
  765. if (ast_strlen_zero(replace)) {
  766. memmove(strptr, strptr + 1, strlen(strptr + 1) + 1);
  767. strptr--;
  768. } else {
  769. /* Replace character */
  770. *strptr = *replace;
  771. }
  772. }
  773. }
  774. ast_str_set(buf, len, "%s", ast_str_buffer(str));
  775. return 0;
  776. }
  777. static struct ast_custom_function replace_function = {
  778. .name = "REPLACE",
  779. .read2 = replace,
  780. };
  781. static int strreplace(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
  782. {
  783. char *varsubstr; /* substring for input var */
  784. char *start; /* Starting pos of substring search. */
  785. char *end; /* Ending pos of substring search. */
  786. int find_size; /* length of given find-string */
  787. unsigned max_matches; /* number of matches we find before terminating search */
  788. unsigned count; /* loop counter */
  789. struct ast_str *str = ast_str_thread_get(&result_buf, 16); /* Holds the data obtained from varname */
  790. AST_DECLARE_APP_ARGS(args,
  791. AST_APP_ARG(varname);
  792. AST_APP_ARG(find_string);
  793. AST_APP_ARG(replace_string);
  794. AST_APP_ARG(max_replacements);
  795. AST_APP_ARG(other); /* Any remining unused arguments */
  796. );
  797. /* Guarantee output string is empty to start with. */
  798. ast_str_reset(*buf);
  799. if (!str) {
  800. /* We failed to allocate str, forget it. We failed. */
  801. return -1;
  802. }
  803. /* Parse the arguments. */
  804. AST_STANDARD_APP_ARGS(args, data);
  805. if (args.argc < 2) {
  806. /* Didn't receive enough arguments to do anything */
  807. ast_log(LOG_ERROR,
  808. "Usage: %s(<varname>,<find-string>[,<replace-string>,[<max-replacements>]])\n",
  809. cmd);
  810. return -1;
  811. }
  812. /* No var name specified. Return failure, string is already empty. */
  813. if (ast_strlen_zero(args.varname)) {
  814. return -1;
  815. }
  816. /* Zero length find strings are a no-no. Kill the function if we run into one. */
  817. if (ast_strlen_zero(args.find_string)) {
  818. ast_log(LOG_ERROR, "No <find-string> specified\n");
  819. return -1;
  820. }
  821. find_size = strlen(args.find_string);
  822. /* set varsubstr to the matching variable */
  823. varsubstr = ast_alloca(strlen(args.varname) + 4);
  824. sprintf(varsubstr, "${%s}", args.varname);
  825. ast_str_substitute_variables(&str, 0, chan, varsubstr);
  826. /* Determine how many replacements are allowed. */
  827. if (!args.max_replacements
  828. || (max_matches = atoi(args.max_replacements)) <= 0) {
  829. /* Unlimited replacements are allowed. */
  830. max_matches = -1;
  831. }
  832. /* Generate the search and replaced string. */
  833. start = ast_str_buffer(str);
  834. for (count = 0; count < max_matches; ++count) {
  835. end = strstr(start, args.find_string);
  836. if (!end) {
  837. /* Did not find a matching substring in the remainder. */
  838. break;
  839. }
  840. /* Replace the found substring. */
  841. *end = '\0';
  842. ast_str_append(buf, len, "%s", start);
  843. if (args.replace_string) {
  844. /* Append the replacement string */
  845. ast_str_append(buf, len, "%s", args.replace_string);
  846. }
  847. start = end + find_size;
  848. }
  849. ast_str_append(buf, len, "%s", start);
  850. return 0;
  851. }
  852. static struct ast_custom_function strreplace_function = {
  853. .name = "STRREPLACE",
  854. .read2 = strreplace,
  855. };
  856. static int regex(struct ast_channel *chan, const char *cmd, char *parse, char *buf,
  857. size_t len)
  858. {
  859. AST_DECLARE_APP_ARGS(args,
  860. AST_APP_ARG(null);
  861. AST_APP_ARG(reg);
  862. AST_APP_ARG(str);
  863. );
  864. int errcode;
  865. regex_t regexbuf;
  866. buf[0] = '\0';
  867. AST_NONSTANDARD_APP_ARGS(args, parse, '"');
  868. if (args.argc != 3) {
  869. ast_log(LOG_ERROR, "Unexpected arguments: should have been in the form '\"<regex>\" <string>'\n");
  870. return -1;
  871. }
  872. if ((*args.str == ' ') || (*args.str == '\t'))
  873. args.str++;
  874. ast_debug(1, "FUNCTION REGEX (%s)(%s)\n", args.reg, args.str);
  875. if ((errcode = regcomp(&regexbuf, args.reg, REG_EXTENDED | REG_NOSUB))) {
  876. regerror(errcode, &regexbuf, buf, len);
  877. ast_log(LOG_WARNING, "Malformed input %s(%s): %s\n", cmd, parse, buf);
  878. return -1;
  879. }
  880. strcpy(buf, regexec(&regexbuf, args.str, 0, NULL, 0) ? "0" : "1");
  881. regfree(&regexbuf);
  882. return 0;
  883. }
  884. static struct ast_custom_function regex_function = {
  885. .name = "REGEX",
  886. .read = regex,
  887. };
  888. #define HASH_PREFIX "~HASH~%s~"
  889. #define HASH_FORMAT HASH_PREFIX "%s~"
  890. static char *app_clearhash = "ClearHash";
  891. /* This function probably should migrate to main/pbx.c, as pbx_builtin_clearvar_prefix() */
  892. static void clearvar_prefix(struct ast_channel *chan, const char *prefix)
  893. {
  894. struct ast_var_t *var;
  895. int len = strlen(prefix);
  896. AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_varshead(chan), var, entries) {
  897. if (strncmp(prefix, ast_var_name(var), len) == 0) {
  898. AST_LIST_REMOVE_CURRENT(entries);
  899. ast_free(var);
  900. }
  901. }
  902. AST_LIST_TRAVERSE_SAFE_END
  903. }
  904. static int exec_clearhash(struct ast_channel *chan, const char *data)
  905. {
  906. char prefix[80];
  907. snprintf(prefix, sizeof(prefix), HASH_PREFIX, data ? (char *)data : "null");
  908. clearvar_prefix(chan, prefix);
  909. return 0;
  910. }
  911. static int array(struct ast_channel *chan, const char *cmd, char *var,
  912. const char *value)
  913. {
  914. AST_DECLARE_APP_ARGS(arg1,
  915. AST_APP_ARG(var)[100];
  916. );
  917. AST_DECLARE_APP_ARGS(arg2,
  918. AST_APP_ARG(val)[100];
  919. );
  920. char *origvar = "", *value2, varname[256];
  921. int i, ishash = 0;
  922. if (!var) {
  923. return -1;
  924. }
  925. value2 = ast_strdupa(value);
  926. if (!strcmp(cmd, "HASH")) {
  927. const char *var2 = pbx_builtin_getvar_helper(chan, "~ODBCFIELDS~");
  928. origvar = var;
  929. if (var2)
  930. var = ast_strdupa(var2);
  931. else {
  932. if (chan)
  933. ast_autoservice_stop(chan);
  934. return -1;
  935. }
  936. ishash = 1;
  937. }
  938. /* The functions this will generally be used with are SORT and ODBC_*, which
  939. * both return comma-delimited lists. However, if somebody uses literal lists,
  940. * their commas will be translated to vertical bars by the load, and I don't
  941. * want them to be surprised by the result. Hence, we prefer commas as the
  942. * delimiter, but we'll fall back to vertical bars if commas aren't found.
  943. */
  944. ast_debug(1, "array (%s=%s)\n", var, S_OR(value2, ""));
  945. AST_STANDARD_APP_ARGS(arg1, var);
  946. AST_STANDARD_APP_ARGS(arg2, value2);
  947. for (i = 0; i < arg1.argc; i++) {
  948. ast_debug(1, "array set value (%s=%s)\n", arg1.var[i],
  949. S_OR(arg2.val[i], ""));
  950. if (i < arg2.argc) {
  951. if (ishash) {
  952. if (origvar[0] == '_') {
  953. if (origvar[1] == '_') {
  954. snprintf(varname, sizeof(varname), "__" HASH_FORMAT, origvar + 2, arg1.var[i]);
  955. } else {
  956. snprintf(varname, sizeof(varname), "_" HASH_FORMAT, origvar + 1, arg1.var[i]);
  957. }
  958. } else {
  959. snprintf(varname, sizeof(varname), HASH_FORMAT, origvar, arg1.var[i]);
  960. }
  961. pbx_builtin_setvar_helper(chan, varname, arg2.val[i]);
  962. } else {
  963. pbx_builtin_setvar_helper(chan, arg1.var[i], arg2.val[i]);
  964. }
  965. } else {
  966. /* We could unset the variable, by passing a NULL, but due to
  967. * pushvar semantics, that could create some undesired behavior. */
  968. if (ishash) {
  969. snprintf(varname, sizeof(varname), HASH_FORMAT, origvar, arg1.var[i]);
  970. pbx_builtin_setvar_helper(chan, varname, "");
  971. } else {
  972. pbx_builtin_setvar_helper(chan, arg1.var[i], "");
  973. }
  974. }
  975. }
  976. return 0;
  977. }
  978. static const char *get_key(const struct ast_str *prefix, const struct ast_var_t *var)
  979. {
  980. const char *prefix_name = ast_str_buffer(prefix);
  981. const char *var_name = ast_var_name(var);
  982. int prefix_len;
  983. int var_len;
  984. if (ast_strlen_zero(var_name)) {
  985. return NULL;
  986. }
  987. prefix_len = ast_str_strlen(prefix);
  988. var_len = strlen(var_name);
  989. /*
  990. * Make sure we only match on non-empty, hash function created keys. If valid
  991. * then return a pointer to the variable that's just after the prefix.
  992. */
  993. return var_len > (prefix_len + 1) && var_name[var_len - 1] == '~' &&
  994. strncmp(prefix_name, var_name, prefix_len) == 0 ? var_name + prefix_len : NULL;
  995. }
  996. static int hashkeys_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  997. {
  998. struct ast_var_t *newvar;
  999. struct ast_str *prefix = ast_str_alloca(80);
  1000. size_t buf_len;
  1001. if (!chan) {
  1002. ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
  1003. return -1;
  1004. }
  1005. ast_str_set(&prefix, -1, HASH_PREFIX, data);
  1006. memset(buf, 0, len);
  1007. AST_LIST_TRAVERSE(ast_channel_varshead(chan), newvar, entries) {
  1008. const char *key = get_key(prefix, newvar);
  1009. if (key) {
  1010. strncat(buf, key, len - strlen(buf) - 1);
  1011. /* Replace the trailing ~ */
  1012. buf[strlen(buf) - 1] = ',';
  1013. }
  1014. }
  1015. /* Trim the trailing comma */
  1016. buf_len = strlen(buf);
  1017. if (buf_len) {
  1018. buf[buf_len - 1] = '\0';
  1019. }
  1020. return 0;
  1021. }
  1022. static int hashkeys_read2(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
  1023. {
  1024. struct ast_var_t *newvar;
  1025. struct ast_str *prefix = ast_str_alloca(80);
  1026. if (!chan) {
  1027. ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
  1028. return -1;
  1029. }
  1030. ast_str_set(&prefix, -1, HASH_PREFIX, data);
  1031. AST_LIST_TRAVERSE(ast_channel_varshead(chan), newvar, entries) {
  1032. const char *key = get_key(prefix, newvar);
  1033. if (key) {
  1034. char *tmp;
  1035. ast_str_append(buf, len, "%s", key);
  1036. /* Replace the trailing ~ */
  1037. tmp = ast_str_buffer(*buf);
  1038. tmp[ast_str_strlen(*buf) - 1] = ',';
  1039. }
  1040. }
  1041. ast_str_truncate(*buf, -1);
  1042. return 0;
  1043. }
  1044. static int hash_write(struct ast_channel *chan, const char *cmd, char *var, const char *value)
  1045. {
  1046. char varname[256];
  1047. AST_DECLARE_APP_ARGS(arg,
  1048. AST_APP_ARG(hashname);
  1049. AST_APP_ARG(hashkey);
  1050. );
  1051. if (!strchr(var, ',')) {
  1052. /* Single argument version */
  1053. return array(chan, "HASH", var, value);
  1054. }
  1055. AST_STANDARD_APP_ARGS(arg, var);
  1056. if (arg.hashname[0] == '_') {
  1057. if (arg.hashname[1] == '_') {
  1058. snprintf(varname, sizeof(varname), "__" HASH_FORMAT, arg.hashname + 2, arg.hashkey);
  1059. } else {
  1060. snprintf(varname, sizeof(varname), "_" HASH_FORMAT, arg.hashname + 1, arg.hashkey);
  1061. }
  1062. } else {
  1063. snprintf(varname, sizeof(varname), HASH_FORMAT, arg.hashname, arg.hashkey);
  1064. }
  1065. pbx_builtin_setvar_helper(chan, varname, value);
  1066. return 0;
  1067. }
  1068. static int hash_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  1069. {
  1070. char varname[256];
  1071. const char *varvalue;
  1072. AST_DECLARE_APP_ARGS(arg,
  1073. AST_APP_ARG(hashname);
  1074. AST_APP_ARG(hashkey);
  1075. );
  1076. AST_STANDARD_APP_ARGS(arg, data);
  1077. if (arg.argc == 2) {
  1078. snprintf(varname, sizeof(varname), HASH_FORMAT, arg.hashname, arg.hashkey);
  1079. varvalue = pbx_builtin_getvar_helper(chan, varname);
  1080. if (varvalue)
  1081. ast_copy_string(buf, varvalue, len);
  1082. else
  1083. *buf = '\0';
  1084. } else if (arg.argc == 1) {
  1085. char colnames[4096];
  1086. int i;
  1087. AST_DECLARE_APP_ARGS(arg2,
  1088. AST_APP_ARG(col)[100];
  1089. );
  1090. if (!chan) {
  1091. ast_log(LOG_WARNING, "No channel and only 1 parameter was provided to %s function.\n", cmd);
  1092. return -1;
  1093. }
  1094. /* Get column names, in no particular order */
  1095. hashkeys_read(chan, "HASHKEYS", arg.hashname, colnames, sizeof(colnames));
  1096. pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", colnames);
  1097. AST_STANDARD_APP_ARGS(arg2, colnames);
  1098. *buf = '\0';
  1099. /* Now get the corresponding column values, in exactly the same order */
  1100. for (i = 0; i < arg2.argc; i++) {
  1101. snprintf(varname, sizeof(varname), HASH_FORMAT, arg.hashname, arg2.col[i]);
  1102. varvalue = pbx_builtin_getvar_helper(chan, varname);
  1103. strncat(buf, varvalue, len - strlen(buf) - 1);
  1104. strncat(buf, ",", len - strlen(buf) - 1);
  1105. }
  1106. /* Strip trailing comma */
  1107. buf[strlen(buf) - 1] = '\0';
  1108. }
  1109. return 0;
  1110. }
  1111. static struct ast_custom_function hash_function = {
  1112. .name = "HASH",
  1113. .write = hash_write,
  1114. .read = hash_read,
  1115. };
  1116. static struct ast_custom_function hashkeys_function = {
  1117. .name = "HASHKEYS",
  1118. .read = hashkeys_read,
  1119. .read2 = hashkeys_read2,
  1120. };
  1121. static struct ast_custom_function array_function = {
  1122. .name = "ARRAY",
  1123. .write = array,
  1124. };
  1125. static int quote(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  1126. {
  1127. char *bufptr = buf, *dataptr = data;
  1128. if (len < 3){ /* at least two for quotes and one for binary zero */
  1129. ast_log(LOG_ERROR, "Not enough buffer\n");
  1130. return -1;
  1131. }
  1132. if (ast_strlen_zero(data)) {
  1133. ast_log(LOG_WARNING, "No argument specified!\n");
  1134. ast_copy_string(buf, "\"\"", len);
  1135. return 0;
  1136. }
  1137. *bufptr++ = '"';
  1138. for (; bufptr < buf + len - 3; dataptr++) {
  1139. if (*dataptr == '\\') {
  1140. *bufptr++ = '\\';
  1141. *bufptr++ = '\\';
  1142. } else if (*dataptr == '"') {
  1143. *bufptr++ = '\\';
  1144. *bufptr++ = '"';
  1145. } else if (*dataptr == '\0') {
  1146. break;
  1147. } else {
  1148. *bufptr++ = *dataptr;
  1149. }
  1150. }
  1151. *bufptr++ = '"';
  1152. *bufptr = '\0';
  1153. return 0;
  1154. }
  1155. static struct ast_custom_function quote_function = {
  1156. .name = "QUOTE",
  1157. .read = quote,
  1158. };
  1159. static int csv_quote(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  1160. {
  1161. char *bufptr = buf, *dataptr = data;
  1162. if (len < 3) { /* at least two for quotes and one for binary zero */
  1163. ast_log(LOG_ERROR, "Not enough buffer\n");
  1164. return -1;
  1165. }
  1166. if (ast_strlen_zero(data)) {
  1167. ast_copy_string(buf, "\"\"", len);
  1168. return 0;
  1169. }
  1170. *bufptr++ = '"';
  1171. for (; bufptr < buf + len - 3; dataptr++){
  1172. if (*dataptr == '"') {
  1173. *bufptr++ = '"';
  1174. *bufptr++ = '"';
  1175. } else if (*dataptr == '\0') {
  1176. break;
  1177. } else {
  1178. *bufptr++ = *dataptr;
  1179. }
  1180. }
  1181. *bufptr++ = '"';
  1182. *bufptr='\0';
  1183. return 0;
  1184. }
  1185. static struct ast_custom_function csv_quote_function = {
  1186. .name = "CSV_QUOTE",
  1187. .read = csv_quote,
  1188. };
  1189. static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
  1190. {
  1191. int length = 0;
  1192. if (data)
  1193. length = strlen(data);
  1194. snprintf(buf, buflen, "%d", length);
  1195. return 0;
  1196. }
  1197. static struct ast_custom_function len_function = {
  1198. .name = "LEN",
  1199. .read = len,
  1200. .read_max = 12,
  1201. };
  1202. static int acf_strftime(struct ast_channel *chan, const char *cmd, char *parse,
  1203. char *buf, size_t buflen)
  1204. {
  1205. AST_DECLARE_APP_ARGS(args,
  1206. AST_APP_ARG(epoch);
  1207. AST_APP_ARG(timezone);
  1208. AST_APP_ARG(format);
  1209. );
  1210. struct timeval when;
  1211. struct ast_tm tm;
  1212. buf[0] = '\0';
  1213. AST_STANDARD_APP_ARGS(args, parse);
  1214. ast_get_timeval(args.epoch, &when, ast_tvnow(), NULL);
  1215. ast_localtime(&when, &tm, args.timezone);
  1216. if (!args.format)
  1217. args.format = "%c";
  1218. if (ast_strftime(buf, buflen, args.format, &tm) <= 0)
  1219. ast_log(LOG_WARNING, "C function strftime() output nothing?!!\n");
  1220. buf[buflen - 1] = '\0';
  1221. return 0;
  1222. }
  1223. static struct ast_custom_function strftime_function = {
  1224. .name = "STRFTIME",
  1225. .read = acf_strftime,
  1226. };
  1227. static int acf_strptime(struct ast_channel *chan, const char *cmd, char *data,
  1228. char *buf, size_t buflen)
  1229. {
  1230. AST_DECLARE_APP_ARGS(args,
  1231. AST_APP_ARG(timestring);
  1232. AST_APP_ARG(timezone);
  1233. AST_APP_ARG(format);
  1234. );
  1235. struct ast_tm tm;
  1236. buf[0] = '\0';
  1237. if (!data) {
  1238. ast_log(LOG_ERROR,
  1239. "Asterisk function STRPTIME() requires an argument.\n");
  1240. return -1;
  1241. }
  1242. AST_STANDARD_APP_ARGS(args, data);
  1243. if (ast_strlen_zero(args.format)) {
  1244. ast_log(LOG_ERROR,
  1245. "No format supplied to STRPTIME(<timestring>,<timezone>,<format>)");
  1246. return -1;
  1247. }
  1248. if (!ast_strptime(args.timestring, args.format, &tm)) {
  1249. ast_log(LOG_WARNING, "STRPTIME() found no time specified within the string\n");
  1250. } else {
  1251. struct timeval when;
  1252. when = ast_mktime(&tm, args.timezone);
  1253. snprintf(buf, buflen, "%d", (int) when.tv_sec);
  1254. }
  1255. return 0;
  1256. }
  1257. static struct ast_custom_function strptime_function = {
  1258. .name = "STRPTIME",
  1259. .read = acf_strptime,
  1260. };
  1261. static int function_eval(struct ast_channel *chan, const char *cmd, char *data,
  1262. char *buf, size_t buflen)
  1263. {
  1264. if (ast_strlen_zero(data)) {
  1265. ast_log(LOG_WARNING, "EVAL requires an argument: EVAL(<string>)\n");
  1266. return -1;
  1267. }
  1268. pbx_substitute_variables_helper(chan, data, buf, buflen - 1);
  1269. return 0;
  1270. }
  1271. static int function_eval2(struct ast_channel *chan, const char *cmd, char *data,
  1272. struct ast_str **buf, ssize_t buflen)
  1273. {
  1274. if (ast_strlen_zero(data)) {
  1275. ast_log(LOG_WARNING, "EVAL requires an argument: EVAL(<string>)\n");
  1276. return -1;
  1277. }
  1278. ast_str_substitute_variables(buf, buflen, chan, data);
  1279. return 0;
  1280. }
  1281. static struct ast_custom_function eval_function = {
  1282. .name = "EVAL",
  1283. .read = function_eval,
  1284. .read2 = function_eval2,
  1285. };
  1286. static int keypadhash(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
  1287. {
  1288. char *bufptr, *dataptr;
  1289. for (bufptr = buf, dataptr = data; bufptr < buf + buflen - 1; dataptr++) {
  1290. if (*dataptr == '\0') {
  1291. *bufptr++ = '\0';
  1292. break;
  1293. } else if (*dataptr == '1') {
  1294. *bufptr++ = '1';
  1295. } else if (strchr("AaBbCc2", *dataptr)) {
  1296. *bufptr++ = '2';
  1297. } else if (strchr("DdEeFf3", *dataptr)) {
  1298. *bufptr++ = '3';
  1299. } else if (strchr("GgHhIi4", *dataptr)) {
  1300. *bufptr++ = '4';
  1301. } else if (strchr("JjKkLl5", *dataptr)) {
  1302. *bufptr++ = '5';
  1303. } else if (strchr("MmNnOo6", *dataptr)) {
  1304. *bufptr++ = '6';
  1305. } else if (strchr("PpQqRrSs7", *dataptr)) {
  1306. *bufptr++ = '7';
  1307. } else if (strchr("TtUuVv8", *dataptr)) {
  1308. *bufptr++ = '8';
  1309. } else if (strchr("WwXxYyZz9", *dataptr)) {
  1310. *bufptr++ = '9';
  1311. } else if (*dataptr == '0') {
  1312. *bufptr++ = '0';
  1313. }
  1314. }
  1315. buf[buflen - 1] = '\0';
  1316. return 0;
  1317. }
  1318. static struct ast_custom_function keypadhash_function = {
  1319. .name = "KEYPADHASH",
  1320. .read = keypadhash,
  1321. };
  1322. static int string_toupper(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
  1323. {
  1324. char *bufptr = buf, *dataptr = data;
  1325. while ((bufptr < buf + buflen - 1) && (*bufptr++ = toupper(*dataptr++)));
  1326. return 0;
  1327. }
  1328. static int string_toupper2(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t buflen)
  1329. {
  1330. char *bufptr, *dataptr = data;
  1331. if (buflen > -1) {
  1332. ast_str_make_space(buf, buflen > 0 ? buflen : strlen(data) + 1);
  1333. }
  1334. bufptr = ast_str_buffer(*buf);
  1335. while ((bufptr < ast_str_buffer(*buf) + ast_str_size(*buf) - 1) && (*bufptr++ = toupper(*dataptr++)));
  1336. ast_str_update(*buf);
  1337. return 0;
  1338. }
  1339. static struct ast_custom_function toupper_function = {
  1340. .name = "TOUPPER",
  1341. .read = string_toupper,
  1342. .read2 = string_toupper2,
  1343. };
  1344. static int string_tolower(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
  1345. {
  1346. char *bufptr = buf, *dataptr = data;
  1347. while ((bufptr < buf + buflen - 1) && (*bufptr++ = tolower(*dataptr++)));
  1348. return 0;
  1349. }
  1350. static int string_tolower2(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t buflen)
  1351. {
  1352. char *bufptr, *dataptr = data;
  1353. if (buflen > -1) {
  1354. ast_str_make_space(buf, buflen > 0 ? buflen : strlen(data) + 1);
  1355. }
  1356. bufptr = ast_str_buffer(*buf);
  1357. while ((bufptr < ast_str_buffer(*buf) + ast_str_size(*buf) - 1) && (*bufptr++ = tolower(*dataptr++)));
  1358. ast_str_update(*buf);
  1359. return 0;
  1360. }
  1361. static struct ast_custom_function tolower_function = {
  1362. .name = "TOLOWER",
  1363. .read = string_tolower,
  1364. .read2 = string_tolower2,
  1365. };
  1366. static int shift_pop(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
  1367. {
  1368. #define beginning (cmd[0] == 'S') /* SHIFT */
  1369. char *after, delimiter[2] = ",", *varsubst;
  1370. size_t unused;
  1371. struct ast_str *before = ast_str_thread_get(&result_buf, 16);
  1372. char *(*search_func)(const char *s, int c) = (beginning ? strchr : strrchr);
  1373. AST_DECLARE_APP_ARGS(args,
  1374. AST_APP_ARG(var);
  1375. AST_APP_ARG(delimiter);
  1376. );
  1377. if (!before) {
  1378. return -1;
  1379. }
  1380. AST_STANDARD_APP_ARGS(args, data);
  1381. if (ast_strlen_zero(args.var)) {
  1382. ast_log(LOG_WARNING, "%s requires a variable name\n", cmd);
  1383. return -1;
  1384. }
  1385. varsubst = ast_alloca(strlen(args.var) + 4);
  1386. sprintf(varsubst, "${%s}", args.var);
  1387. ast_str_substitute_variables(&before, 0, chan, varsubst);
  1388. if (args.argc > 1 && !ast_strlen_zero(args.delimiter)) {
  1389. ast_get_encoded_char(args.delimiter, delimiter, &unused);
  1390. }
  1391. if (!ast_str_strlen(before)) {
  1392. /* Nothing to pop */
  1393. return -1;
  1394. }
  1395. if (!(after = search_func(ast_str_buffer(before), delimiter[0]))) {
  1396. /* Only one entry in array */
  1397. ast_str_set(buf, len, "%s", ast_str_buffer(before));
  1398. pbx_builtin_setvar_helper(chan, args.var, "");
  1399. } else {
  1400. *after++ = '\0';
  1401. ast_str_set(buf, len, "%s", beginning ? ast_str_buffer(before) : after);
  1402. pbx_builtin_setvar_helper(chan, args.var, beginning ? after : ast_str_buffer(before));
  1403. }
  1404. return 0;
  1405. #undef beginning
  1406. }
  1407. static struct ast_custom_function shift_function = {
  1408. .name = "SHIFT",
  1409. .read2 = shift_pop,
  1410. };
  1411. static struct ast_custom_function pop_function = {
  1412. .name = "POP",
  1413. .read2 = shift_pop,
  1414. };
  1415. static int unshift_push(struct ast_channel *chan, const char *cmd, char *data, const char *new_value)
  1416. {
  1417. #define beginning (cmd[0] == 'U') /* UNSHIFT */
  1418. char delimiter[2] = ",", *varsubst;
  1419. size_t unused;
  1420. struct ast_str *buf, *previous_value;
  1421. AST_DECLARE_APP_ARGS(args,
  1422. AST_APP_ARG(var);
  1423. AST_APP_ARG(delimiter);
  1424. );
  1425. const char *stripped_var;
  1426. if (!(buf = ast_str_thread_get(&result_buf, 16)) ||
  1427. !(previous_value = ast_str_thread_get(&tmp_buf, 16))) {
  1428. return -1;
  1429. }
  1430. AST_STANDARD_APP_ARGS(args, data);
  1431. if (ast_strlen_zero(args.var)) {
  1432. ast_log(LOG_WARNING, "%s requires a variable name\n", cmd);
  1433. return -1;
  1434. }
  1435. if (args.argc > 1 && !ast_strlen_zero(args.delimiter)) {
  1436. ast_get_encoded_char(args.delimiter, delimiter, &unused);
  1437. }
  1438. /* UNSHIFT and PUSH act as ways of setting a variable, so we need to be
  1439. * sure to skip leading underscores if they appear. However, we only want
  1440. * to skip up to two since that is the maximum number that can be used to
  1441. * indicate variable inheritance. Any further underscores are part of the
  1442. * variable name.
  1443. */
  1444. stripped_var = args.var + MIN(strspn(args.var, "_"), 2);
  1445. varsubst = ast_alloca(strlen(stripped_var) + 4);
  1446. sprintf(varsubst, "${%s}", stripped_var);
  1447. ast_str_substitute_variables(&previous_value, 0, chan, varsubst);
  1448. if (!ast_str_strlen(previous_value)) {
  1449. ast_str_set(&buf, 0, "%s", new_value);
  1450. } else {
  1451. ast_str_set(&buf, 0, "%s%c%s",
  1452. beginning ? new_value : ast_str_buffer(previous_value),
  1453. delimiter[0],
  1454. beginning ? ast_str_buffer(previous_value) : new_value);
  1455. }
  1456. pbx_builtin_setvar_helper(chan, args.var, ast_str_buffer(buf));
  1457. return 0;
  1458. #undef beginning
  1459. }
  1460. static struct ast_custom_function push_function = {
  1461. .name = "PUSH",
  1462. .write = unshift_push,
  1463. };
  1464. static struct ast_custom_function unshift_function = {
  1465. .name = "UNSHIFT",
  1466. .write = unshift_push,
  1467. };
  1468. static int passthru(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
  1469. {
  1470. ast_str_set(buf, len, "%s", data);
  1471. return 0;
  1472. }
  1473. static struct ast_custom_function passthru_function = {
  1474. .name = "PASSTHRU",
  1475. .read2 = passthru,
  1476. };
  1477. #ifdef TEST_FRAMEWORK
  1478. AST_TEST_DEFINE(test_FIELDNUM)
  1479. {
  1480. int i, res = AST_TEST_PASS;
  1481. struct ast_channel *chan;
  1482. struct ast_str *str;
  1483. char expression[256];
  1484. struct {
  1485. const char *fields;
  1486. const char *delim;
  1487. const char *field;
  1488. const char *expected;
  1489. } test_args[] = {
  1490. {"abc,def,ghi,jkl", "\\,", "ghi", "3"},
  1491. {"abc def ghi jkl", " ", "abc", "1"},
  1492. {"abc/def/ghi/jkl", "\\\\x2f", "def", "2"},
  1493. {"abc$def$ghi$jkl", "", "ghi", "0"},
  1494. {"abc,def,ghi,jkl", "-", "", "0"},
  1495. {"abc-def-ghi-jkl", "-", "mno", "0"}
  1496. };
  1497. switch (cmd) {
  1498. case TEST_INIT:
  1499. info->name = "func_FIELDNUM_test";
  1500. info->category = "/funcs/func_strings/";
  1501. info->summary = "Test FIELDNUM function";
  1502. info->description = "Verify FIELDNUM behavior";
  1503. return AST_TEST_NOT_RUN;
  1504. case TEST_EXECUTE:
  1505. break;
  1506. }
  1507. if (!(chan = ast_dummy_channel_alloc())) {
  1508. ast_test_status_update(test, "Unable to allocate dummy channel\n");
  1509. return AST_TEST_FAIL;
  1510. }
  1511. if (!(str = ast_str_create(16))) {
  1512. ast_test_status_update(test, "Unable to allocate dynamic string buffer\n");
  1513. ast_channel_release(chan);
  1514. return AST_TEST_FAIL;
  1515. }
  1516. for (i = 0; i < ARRAY_LEN(test_args); i++) {
  1517. struct ast_var_t *var = ast_var_assign("FIELDS", test_args[i].fields);
  1518. if (!var) {
  1519. ast_test_status_update(test, "Out of memory\n");
  1520. res = AST_TEST_FAIL;
  1521. break;
  1522. }
  1523. AST_LIST_INSERT_HEAD(ast_channel_varshead(chan), var, entries);
  1524. snprintf(expression, sizeof(expression), "${FIELDNUM(%s,%s,%s)}", var->name, test_args[i].delim, test_args[i].field);
  1525. ast_str_substitute_variables(&str, 0, chan, expression);
  1526. AST_LIST_REMOVE(ast_channel_varshead(chan), var, entries);
  1527. ast_var_delete(var);
  1528. if (strcasecmp(ast_str_buffer(str), test_args[i].expected)) {
  1529. ast_test_status_update(test, "Evaluation of '%s' returned '%s' instead of the expected value '%s'\n",
  1530. expression, ast_str_buffer(str), test_args[i].expected);
  1531. res = AST_TEST_FAIL;
  1532. break;
  1533. }
  1534. }
  1535. ast_free(str);
  1536. ast_channel_release(chan);
  1537. return res;
  1538. }
  1539. AST_TEST_DEFINE(test_REPLACE)
  1540. {
  1541. int i, res = AST_TEST_PASS;
  1542. struct ast_channel *chan;
  1543. struct ast_str *str;
  1544. char expression[256];
  1545. struct {
  1546. const char *test_string;
  1547. const char *find_chars;
  1548. const char *replace_char;
  1549. const char *expected;
  1550. } test_args[] = {
  1551. {"abc,def", "\\,", "-", "abc-def"},
  1552. {"abc,abc", "bc", "a", "aaa,aaa"},
  1553. {"abc,def", "x", "?", "abc,def"},
  1554. {"abc,def", "\\,", "", "abcdef"}
  1555. };
  1556. switch (cmd) {
  1557. case TEST_INIT:
  1558. info->name = "func_REPLACE_test";
  1559. info->category = "/funcs/func_strings/";
  1560. info->summary = "Test REPLACE function";
  1561. info->description = "Verify REPLACE behavior";
  1562. return AST_TEST_NOT_RUN;
  1563. case TEST_EXECUTE:
  1564. break;
  1565. }
  1566. if (!(chan = ast_dummy_channel_alloc())) {
  1567. ast_test_status_update(test, "Unable to allocate dummy channel\n");
  1568. return AST_TEST_FAIL;
  1569. }
  1570. if (!(str = ast_str_create(16))) {
  1571. ast_test_status_update(test, "Unable to allocate dynamic string buffer\n");
  1572. ast_channel_release(chan);
  1573. return AST_TEST_FAIL;
  1574. }
  1575. for (i = 0; i < ARRAY_LEN(test_args); i++) {
  1576. struct ast_var_t *var = ast_var_assign("TEST_STRING", test_args[i].test_string);
  1577. if (!var) {
  1578. ast_test_status_update(test, "Out of memory\n");
  1579. res = AST_TEST_FAIL;
  1580. break;
  1581. }
  1582. AST_LIST_INSERT_HEAD(ast_channel_varshead(chan), var, entries);
  1583. snprintf(expression, sizeof(expression), "${REPLACE(%s,%s,%s)}", var->name, test_args[i].find_chars, test_args[i].replace_char);
  1584. ast_str_substitute_variables(&str, 0, chan, expression);
  1585. AST_LIST_REMOVE(ast_channel_varshead(chan), var, entries);
  1586. ast_var_delete(var);
  1587. if (strcasecmp(ast_str_buffer(str), test_args[i].expected)) {
  1588. ast_test_status_update(test, "Evaluation of '%s' returned '%s' instead of the expected value '%s'\n",
  1589. expression, ast_str_buffer(str), test_args[i].expected);
  1590. res = AST_TEST_FAIL;
  1591. break;
  1592. }
  1593. }
  1594. ast_free(str);
  1595. ast_channel_release(chan);
  1596. return res;
  1597. }
  1598. AST_TEST_DEFINE(test_FILTER)
  1599. {
  1600. int i, res = AST_TEST_PASS;
  1601. const char *test_strings[][2] = {
  1602. {"A-R", "DAHDI"},
  1603. {"A\\-R", "A"},
  1604. {"\\x41-R", "DAHDI"},
  1605. {"0-9A-Ca-c", "0042133333A12212"},
  1606. {"0-9a-cA-C_+\\-", "0042133333A12212"},
  1607. {NULL, NULL},
  1608. };
  1609. switch (cmd) {
  1610. case TEST_INIT:
  1611. info->name = "func_FILTER_test";
  1612. info->category = "/funcs/func_strings/";
  1613. info->summary = "Test FILTER function";
  1614. info->description = "Verify FILTER behavior";
  1615. return AST_TEST_NOT_RUN;
  1616. case TEST_EXECUTE:
  1617. break;
  1618. }
  1619. for (i = 0; test_strings[i][0]; i++) {
  1620. char tmp[256], tmp2[256] = "";
  1621. snprintf(tmp, sizeof(tmp), "${FILTER(%s,0042133333&DAHDI/g1/2212)}", test_strings[i][0]);
  1622. pbx_substitute_variables_helper(NULL, tmp, tmp2, sizeof(tmp2) - 1);
  1623. if (strcmp(test_strings[i][1], tmp2)) {
  1624. ast_test_status_update(test, "Format string '%s' substituted to '%s'. Expected '%s'.\n", test_strings[i][0], tmp2, test_strings[i][1]);
  1625. res = AST_TEST_FAIL;
  1626. }
  1627. }
  1628. return res;
  1629. }
  1630. AST_TEST_DEFINE(test_STRREPLACE)
  1631. {
  1632. int i, res = AST_TEST_PASS;
  1633. struct ast_channel *chan; /* dummy channel */
  1634. struct ast_str *str; /* fancy string for holding comparing value */
  1635. const char *test_strings[][5] = {
  1636. {"Weasels have eaten my telephone system", "have eaten my", "are eating our", "", "Weasels are eating our telephone system"}, /*Test normal conditions */
  1637. {"Did you know twenty plus two is twenty-two?", "twenty", "thirty", NULL, "Did you know thirty plus two is thirty-two?"}, /* Test no third comma */
  1638. {"foofoofoofoofoofoofoo", "foofoo", "bar", NULL, "barbarbarfoo"}, /* Found string within previous match */
  1639. {"My pet dog once ate a dog who sat on a dog while eating a corndog.", "dog", "cat", "3", "My pet cat once ate a cat who sat on a cat while eating a corndog."},
  1640. {"One and one and one is three", "and", "plus", "1", "One plus one and one is three"}, /* Test <max-replacements> = 1*/
  1641. {"", "fhqwagads", "spelunker", NULL, ""}, /* Empty primary string */
  1642. {"Part of this string is missing.", "missing", NULL, NULL, "Part of this string is ."}, /* Empty replace string */
  1643. {"'Accidentally' left off a bunch of stuff.", NULL, NULL, NULL, ""}, /* Deliberate error test from too few args */
  1644. {"This test will also error.", "", "", "", ""}, /* Deliberate error test from blank find string */
  1645. {"This is an \"escape character\" test.", "\\\"escape character\\\"", "evil", NULL, "This is an evil test."}
  1646. };
  1647. switch (cmd) {
  1648. case TEST_INIT:
  1649. info->name = "func_STRREPLACE_test";
  1650. info->category = "/funcs/func_strings/";
  1651. info->summary = "Test STRREPLACE function";
  1652. info->description = "Verify STRREPLACE behavior";
  1653. return AST_TEST_NOT_RUN;
  1654. case TEST_EXECUTE:
  1655. break;
  1656. }
  1657. if (!(chan = ast_dummy_channel_alloc())) {
  1658. ast_test_status_update(test, "Unable to allocate dummy channel\n");
  1659. return AST_TEST_FAIL;
  1660. }
  1661. if (!(str = ast_str_create(64))) {
  1662. ast_test_status_update(test, "Unable to allocate dynamic string buffer\n");
  1663. ast_channel_release(chan);
  1664. return AST_TEST_FAIL;
  1665. }
  1666. for (i = 0; i < ARRAY_LEN(test_strings); i++) {
  1667. char tmp[512], tmp2[512] = "";
  1668. struct ast_var_t *var = ast_var_assign("test_string", test_strings[i][0]);
  1669. if (!var) {
  1670. ast_test_status_update(test, "Unable to allocate variable\n");
  1671. ast_free(str);
  1672. ast_channel_release(chan);
  1673. return AST_TEST_FAIL;
  1674. }
  1675. AST_LIST_INSERT_HEAD(ast_channel_varshead(chan), var, entries);
  1676. if (test_strings[i][3]) {
  1677. snprintf(tmp, sizeof(tmp), "${STRREPLACE(%s,%s,%s,%s)}", "test_string", test_strings[i][1], test_strings[i][2], test_strings[i][3]);
  1678. } else if (test_strings[i][2]) {
  1679. snprintf(tmp, sizeof(tmp), "${STRREPLACE(%s,%s,%s)}", "test_string", test_strings[i][1], test_strings[i][2]);
  1680. } else if (test_strings[i][1]) {
  1681. snprintf(tmp, sizeof(tmp), "${STRREPLACE(%s,%s)}", "test_string", test_strings[i][1]);
  1682. } else {
  1683. snprintf(tmp, sizeof(tmp), "${STRREPLACE(%s)}", "test_string");
  1684. }
  1685. ast_str_substitute_variables(&str, 0, chan, tmp);
  1686. if (strcmp(test_strings[i][4], ast_str_buffer(str))) {
  1687. ast_test_status_update(test, "Format string '%s' substituted to '%s'. Expected '%s'.\n", test_strings[i][0], tmp2, test_strings[i][4]);
  1688. res = AST_TEST_FAIL;
  1689. }
  1690. }
  1691. ast_free(str);
  1692. ast_channel_release(chan);
  1693. return res;
  1694. }
  1695. #endif
  1696. static int unload_module(void)
  1697. {
  1698. int res = 0;
  1699. AST_TEST_UNREGISTER(test_FIELDNUM);
  1700. AST_TEST_UNREGISTER(test_REPLACE);
  1701. AST_TEST_UNREGISTER(test_FILTER);
  1702. AST_TEST_UNREGISTER(test_STRREPLACE);
  1703. res |= ast_custom_function_unregister(&fieldqty_function);
  1704. res |= ast_custom_function_unregister(&fieldnum_function);
  1705. res |= ast_custom_function_unregister(&filter_function);
  1706. res |= ast_custom_function_unregister(&replace_function);
  1707. res |= ast_custom_function_unregister(&strreplace_function);
  1708. res |= ast_custom_function_unregister(&listfilter_function);
  1709. res |= ast_custom_function_unregister(&regex_function);
  1710. res |= ast_custom_function_unregister(&array_function);
  1711. res |= ast_custom_function_unregister(&quote_function);
  1712. res |= ast_custom_function_unregister(&csv_quote_function);
  1713. res |= ast_custom_function_unregister(&len_function);
  1714. res |= ast_custom_function_unregister(&strftime_function);
  1715. res |= ast_custom_function_unregister(&strptime_function);
  1716. res |= ast_custom_function_unregister(&eval_function);
  1717. res |= ast_custom_function_unregister(&keypadhash_function);
  1718. res |= ast_custom_function_unregister(&hashkeys_function);
  1719. res |= ast_custom_function_unregister(&hash_function);
  1720. res |= ast_unregister_application(app_clearhash);
  1721. res |= ast_custom_function_unregister(&toupper_function);
  1722. res |= ast_custom_function_unregister(&tolower_function);
  1723. res |= ast_custom_function_unregister(&shift_function);
  1724. res |= ast_custom_function_unregister(&pop_function);
  1725. res |= ast_custom_function_unregister(&push_function);
  1726. res |= ast_custom_function_unregister(&unshift_function);
  1727. res |= ast_custom_function_unregister(&passthru_function);
  1728. return res;
  1729. }
  1730. static int load_module(void)
  1731. {
  1732. int res = 0;
  1733. AST_TEST_REGISTER(test_FIELDNUM);
  1734. AST_TEST_REGISTER(test_REPLACE);
  1735. AST_TEST_REGISTER(test_FILTER);
  1736. AST_TEST_REGISTER(test_STRREPLACE);
  1737. res |= ast_custom_function_register(&fieldqty_function);
  1738. res |= ast_custom_function_register(&fieldnum_function);
  1739. res |= ast_custom_function_register(&filter_function);
  1740. res |= ast_custom_function_register(&replace_function);
  1741. res |= ast_custom_function_register(&strreplace_function);
  1742. res |= ast_custom_function_register(&listfilter_function);
  1743. res |= ast_custom_function_register(&regex_function);
  1744. res |= ast_custom_function_register(&array_function);
  1745. res |= ast_custom_function_register(&quote_function);
  1746. res |= ast_custom_function_register(&csv_quote_function);
  1747. res |= ast_custom_function_register(&len_function);
  1748. res |= ast_custom_function_register(&strftime_function);
  1749. res |= ast_custom_function_register(&strptime_function);
  1750. res |= ast_custom_function_register(&eval_function);
  1751. res |= ast_custom_function_register(&keypadhash_function);
  1752. res |= ast_custom_function_register(&hashkeys_function);
  1753. res |= ast_custom_function_register(&hash_function);
  1754. res |= ast_register_application_xml(app_clearhash, exec_clearhash);
  1755. res |= ast_custom_function_register(&toupper_function);
  1756. res |= ast_custom_function_register(&tolower_function);
  1757. res |= ast_custom_function_register(&shift_function);
  1758. res |= ast_custom_function_register(&pop_function);
  1759. res |= ast_custom_function_register(&push_function);
  1760. res |= ast_custom_function_register(&unshift_function);
  1761. res |= ast_custom_function_register(&passthru_function);
  1762. return res;
  1763. }
  1764. AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "String handling dialplan functions");