func_strings.c 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008
  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. ast_log(LOG_ERROR, "List variable '%s' not found\n", args.listname);
  585. if (chan) {
  586. ast_channel_unlock(chan);
  587. }
  588. return -1;
  589. }
  590. /* If the string isn't there, just copy out the string and be done with it. */
  591. if (!strstr(ast_str_buffer(orig_list), args.fieldvalue)) {
  592. if (buf) {
  593. ast_copy_string(buf, ast_str_buffer(orig_list), len);
  594. } else {
  595. ast_str_set(result_ptr, len, "%s", ast_str_buffer(orig_list));
  596. }
  597. if (chan) {
  598. ast_channel_unlock(chan);
  599. }
  600. return 0;
  601. }
  602. dlen = strlen(args.delimiter);
  603. delim = ast_alloca(dlen + 1);
  604. ast_get_encoded_str(args.delimiter, delim, dlen + 1);
  605. if ((dlen = strlen(delim)) == 0) {
  606. delim = ",";
  607. dlen = 1;
  608. }
  609. flen = strlen(args.fieldvalue);
  610. ast_str_reset(*result_ptr);
  611. /* Enough space for any result */
  612. if (len > -1) {
  613. ast_str_make_space(result_ptr, len ? len : ast_str_strlen(orig_list) + 1);
  614. }
  615. begin = ast_str_buffer(orig_list);
  616. next = strstr(begin, delim);
  617. do {
  618. /* Find next boundary */
  619. if (next) {
  620. cur = next;
  621. next = strstr(cur + dlen, delim);
  622. } else {
  623. cur = strchr(begin + dlen, '\0');
  624. }
  625. if (flen == cur - begin && !strncmp(begin, args.fieldvalue, flen)) {
  626. /* Skip field */
  627. begin += flen + dlen;
  628. } else {
  629. /* Copy field to output */
  630. if (!first) {
  631. ast_str_append(result_ptr, len, "%s", delim);
  632. }
  633. ast_str_append_substr(result_ptr, len, begin, cur - begin);
  634. first = 0;
  635. begin = cur + dlen;
  636. }
  637. } while (*cur != '\0');
  638. if (chan) {
  639. ast_channel_unlock(chan);
  640. }
  641. if (buf) {
  642. ast_copy_string(buf, ast_str_buffer(result), len);
  643. }
  644. return 0;
  645. }
  646. static int listfilter_read(struct ast_channel *chan, const char *cmd, char *parse, char *buf, size_t len)
  647. {
  648. return listfilter(chan, cmd, parse, buf, NULL, len);
  649. }
  650. static int listfilter_read2(struct ast_channel *chan, const char *cmd, char *parse, struct ast_str **buf, ssize_t len)
  651. {
  652. return listfilter(chan, cmd, parse, NULL, buf, len);
  653. }
  654. static struct ast_custom_function listfilter_function = {
  655. .name = "LISTFILTER",
  656. .read = listfilter_read,
  657. .read2 = listfilter_read2,
  658. };
  659. static int filter(struct ast_channel *chan, const char *cmd, char *parse, char *buf,
  660. size_t len)
  661. {
  662. AST_DECLARE_APP_ARGS(args,
  663. AST_APP_ARG(allowed);
  664. AST_APP_ARG(string);
  665. );
  666. char *outbuf = buf;
  667. unsigned char ac;
  668. char allowed[256] = "";
  669. size_t allowedlen = 0;
  670. int32_t bitfield[8] = { 0, }; /* 256 bits */
  671. AST_STANDARD_RAW_ARGS(args, parse);
  672. if (!args.string) {
  673. ast_log(LOG_ERROR, "Usage: FILTER(<allowed-chars>,<string>)\n");
  674. return -1;
  675. }
  676. if (args.allowed[0] == '"' && !ast_opt_dont_warn) {
  677. ast_log(LOG_WARNING, "FILTER allowed characters includes the quote (\") character. This may not be what you want.\n");
  678. }
  679. /* Expand ranges */
  680. for (; *(args.allowed);) {
  681. char c1 = 0, c2 = 0;
  682. size_t consumed = 0;
  683. if (ast_get_encoded_char(args.allowed, &c1, &consumed))
  684. return -1;
  685. args.allowed += consumed;
  686. if (*(args.allowed) == '-') {
  687. if (ast_get_encoded_char(args.allowed + 1, &c2, &consumed))
  688. c2 = c1;
  689. args.allowed += consumed + 1;
  690. if ((unsigned char) c2 < (unsigned char) c1 && !ast_opt_dont_warn) {
  691. ast_log(LOG_WARNING, "Range wrapping in FILTER(%s,%s). This may not be what you want.\n", parse, args.string);
  692. }
  693. /*!\note
  694. * Looks a little strange, until you realize that we can overflow
  695. * the size of a char.
  696. */
  697. for (ac = (unsigned char) c1; ac != (unsigned char) c2; ac++) {
  698. bitfield[ac / 32] |= 1 << (ac % 32);
  699. }
  700. bitfield[ac / 32] |= 1 << (ac % 32);
  701. ast_debug(4, "c1=%d, c2=%d\n", c1, c2);
  702. } else {
  703. ac = (unsigned char) c1;
  704. ast_debug(4, "c1=%d, consumed=%d, args.allowed=%s\n", c1, (int) consumed, args.allowed - consumed);
  705. bitfield[ac / 32] |= 1 << (ac % 32);
  706. }
  707. }
  708. for (ac = 1; ac != 0; ac++) {
  709. if (bitfield[ac / 32] & (1 << (ac % 32))) {
  710. allowed[allowedlen++] = ac;
  711. }
  712. }
  713. ast_debug(1, "Allowed: %s\n", allowed);
  714. for (; *(args.string) && (buf + len - 1 > outbuf); (args.string)++) {
  715. if (strchr(allowed, *(args.string)))
  716. *outbuf++ = *(args.string);
  717. }
  718. *outbuf = '\0';
  719. return 0;
  720. }
  721. static struct ast_custom_function filter_function = {
  722. .name = "FILTER",
  723. .read = filter,
  724. };
  725. static int replace(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
  726. {
  727. AST_DECLARE_APP_ARGS(args,
  728. AST_APP_ARG(varname);
  729. AST_APP_ARG(find);
  730. AST_APP_ARG(replace);
  731. );
  732. char *strptr, *varsubst;
  733. RAII_VAR(struct ast_str *, str, ast_str_create(16), ast_free);
  734. char find[256]; /* Only 256 characters possible */
  735. char replace[2] = "";
  736. size_t unused;
  737. AST_STANDARD_APP_ARGS(args, data);
  738. if (!str) {
  739. return -1;
  740. }
  741. if (args.argc < 2) {
  742. ast_log(LOG_ERROR, "Usage: %s(<varname>,<search-chars>[,<replace-char>])\n", cmd);
  743. return -1;
  744. }
  745. /* Decode escapes */
  746. ast_get_encoded_str(args.find, find, sizeof(find));
  747. ast_get_encoded_char(args.replace, replace, &unused);
  748. if (ast_strlen_zero(find) || ast_strlen_zero(args.varname)) {
  749. ast_log(LOG_ERROR, "The characters to search for and the variable name must not be empty.\n");
  750. return -1;
  751. }
  752. varsubst = ast_alloca(strlen(args.varname) + 4);
  753. sprintf(varsubst, "${%s}", args.varname);
  754. ast_str_substitute_variables(&str, 0, chan, varsubst);
  755. if (!ast_str_strlen(str)) {
  756. /* Blank, nothing to replace */
  757. return -1;
  758. }
  759. ast_debug(3, "String to search: (%s)\n", ast_str_buffer(str));
  760. ast_debug(3, "Characters to find: (%s)\n", find);
  761. ast_debug(3, "Character to replace with: (%s)\n", replace);
  762. for (strptr = ast_str_buffer(str); *strptr; strptr++) {
  763. /* buf is already a mutable buffer, so we construct the result
  764. * directly there */
  765. if (strchr(find, *strptr)) {
  766. if (ast_strlen_zero(replace)) {
  767. memmove(strptr, strptr + 1, strlen(strptr + 1) + 1);
  768. strptr--;
  769. } else {
  770. /* Replace character */
  771. *strptr = *replace;
  772. }
  773. }
  774. }
  775. ast_str_set(buf, len, "%s", ast_str_buffer(str));
  776. return 0;
  777. }
  778. static struct ast_custom_function replace_function = {
  779. .name = "REPLACE",
  780. .read2 = replace,
  781. };
  782. static int strreplace(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
  783. {
  784. char *varsubstr; /* substring for input var */
  785. char *start; /* Starting pos of substring search. */
  786. char *end; /* Ending pos of substring search. */
  787. int find_size; /* length of given find-string */
  788. unsigned max_matches; /* number of matches we find before terminating search */
  789. unsigned count; /* loop counter */
  790. struct ast_str *str = ast_str_thread_get(&result_buf, 16); /* Holds the data obtained from varname */
  791. AST_DECLARE_APP_ARGS(args,
  792. AST_APP_ARG(varname);
  793. AST_APP_ARG(find_string);
  794. AST_APP_ARG(replace_string);
  795. AST_APP_ARG(max_replacements);
  796. AST_APP_ARG(other); /* Any remining unused arguments */
  797. );
  798. /* Guarantee output string is empty to start with. */
  799. ast_str_reset(*buf);
  800. if (!str) {
  801. /* We failed to allocate str, forget it. We failed. */
  802. return -1;
  803. }
  804. /* Parse the arguments. */
  805. AST_STANDARD_APP_ARGS(args, data);
  806. if (args.argc < 2) {
  807. /* Didn't receive enough arguments to do anything */
  808. ast_log(LOG_ERROR,
  809. "Usage: %s(<varname>,<find-string>[,<replace-string>,[<max-replacements>]])\n",
  810. cmd);
  811. return -1;
  812. }
  813. /* No var name specified. Return failure, string is already empty. */
  814. if (ast_strlen_zero(args.varname)) {
  815. return -1;
  816. }
  817. /* Zero length find strings are a no-no. Kill the function if we run into one. */
  818. if (ast_strlen_zero(args.find_string)) {
  819. ast_log(LOG_ERROR, "No <find-string> specified\n");
  820. return -1;
  821. }
  822. find_size = strlen(args.find_string);
  823. /* set varsubstr to the matching variable */
  824. varsubstr = ast_alloca(strlen(args.varname) + 4);
  825. sprintf(varsubstr, "${%s}", args.varname);
  826. ast_str_substitute_variables(&str, 0, chan, varsubstr);
  827. /* Determine how many replacements are allowed. */
  828. if (!args.max_replacements
  829. || (max_matches = atoi(args.max_replacements)) <= 0) {
  830. /* Unlimited replacements are allowed. */
  831. max_matches = -1;
  832. }
  833. /* Generate the search and replaced string. */
  834. start = ast_str_buffer(str);
  835. for (count = 0; count < max_matches; ++count) {
  836. end = strstr(start, args.find_string);
  837. if (!end) {
  838. /* Did not find a matching substring in the remainder. */
  839. break;
  840. }
  841. /* Replace the found substring. */
  842. *end = '\0';
  843. ast_str_append(buf, len, "%s", start);
  844. if (args.replace_string) {
  845. /* Append the replacement string */
  846. ast_str_append(buf, len, "%s", args.replace_string);
  847. }
  848. start = end + find_size;
  849. }
  850. ast_str_append(buf, len, "%s", start);
  851. return 0;
  852. }
  853. static struct ast_custom_function strreplace_function = {
  854. .name = "STRREPLACE",
  855. .read2 = strreplace,
  856. };
  857. static int regex(struct ast_channel *chan, const char *cmd, char *parse, char *buf,
  858. size_t len)
  859. {
  860. AST_DECLARE_APP_ARGS(args,
  861. AST_APP_ARG(null);
  862. AST_APP_ARG(reg);
  863. AST_APP_ARG(str);
  864. );
  865. int errcode;
  866. regex_t regexbuf;
  867. buf[0] = '\0';
  868. AST_NONSTANDARD_APP_ARGS(args, parse, '"');
  869. if (args.argc != 3) {
  870. ast_log(LOG_ERROR, "Unexpected arguments: should have been in the form '\"<regex>\" <string>'\n");
  871. return -1;
  872. }
  873. if ((*args.str == ' ') || (*args.str == '\t'))
  874. args.str++;
  875. ast_debug(1, "FUNCTION REGEX (%s)(%s)\n", args.reg, args.str);
  876. if ((errcode = regcomp(&regexbuf, args.reg, REG_EXTENDED | REG_NOSUB))) {
  877. regerror(errcode, &regexbuf, buf, len);
  878. ast_log(LOG_WARNING, "Malformed input %s(%s): %s\n", cmd, parse, buf);
  879. return -1;
  880. }
  881. strcpy(buf, regexec(&regexbuf, args.str, 0, NULL, 0) ? "0" : "1");
  882. regfree(&regexbuf);
  883. return 0;
  884. }
  885. static struct ast_custom_function regex_function = {
  886. .name = "REGEX",
  887. .read = regex,
  888. };
  889. #define HASH_PREFIX "~HASH~%s~"
  890. #define HASH_FORMAT HASH_PREFIX "%s~"
  891. static char *app_clearhash = "ClearHash";
  892. /* This function probably should migrate to main/pbx.c, as pbx_builtin_clearvar_prefix() */
  893. static void clearvar_prefix(struct ast_channel *chan, const char *prefix)
  894. {
  895. struct ast_var_t *var;
  896. int len = strlen(prefix);
  897. AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_varshead(chan), var, entries) {
  898. if (strncmp(prefix, ast_var_name(var), len) == 0) {
  899. AST_LIST_REMOVE_CURRENT(entries);
  900. ast_free(var);
  901. }
  902. }
  903. AST_LIST_TRAVERSE_SAFE_END
  904. }
  905. static int exec_clearhash(struct ast_channel *chan, const char *data)
  906. {
  907. char prefix[80];
  908. snprintf(prefix, sizeof(prefix), HASH_PREFIX, data ? (char *)data : "null");
  909. clearvar_prefix(chan, prefix);
  910. return 0;
  911. }
  912. static int array(struct ast_channel *chan, const char *cmd, char *var,
  913. const char *value)
  914. {
  915. AST_DECLARE_APP_ARGS(arg1,
  916. AST_APP_ARG(var)[100];
  917. );
  918. AST_DECLARE_APP_ARGS(arg2,
  919. AST_APP_ARG(val)[100];
  920. );
  921. char *origvar = "", *value2, varname[256];
  922. int i, ishash = 0;
  923. if (!var) {
  924. return -1;
  925. }
  926. value2 = ast_strdupa(value);
  927. if (!strcmp(cmd, "HASH")) {
  928. const char *var2 = pbx_builtin_getvar_helper(chan, "~ODBCFIELDS~");
  929. origvar = var;
  930. if (var2)
  931. var = ast_strdupa(var2);
  932. else {
  933. if (chan)
  934. ast_autoservice_stop(chan);
  935. return -1;
  936. }
  937. ishash = 1;
  938. }
  939. /* The functions this will generally be used with are SORT and ODBC_*, which
  940. * both return comma-delimited lists. However, if somebody uses literal lists,
  941. * their commas will be translated to vertical bars by the load, and I don't
  942. * want them to be surprised by the result. Hence, we prefer commas as the
  943. * delimiter, but we'll fall back to vertical bars if commas aren't found.
  944. */
  945. ast_debug(1, "array (%s=%s)\n", var, S_OR(value2, ""));
  946. AST_STANDARD_APP_ARGS(arg1, var);
  947. AST_STANDARD_APP_ARGS(arg2, value2);
  948. for (i = 0; i < arg1.argc; i++) {
  949. ast_debug(1, "array set value (%s=%s)\n", arg1.var[i],
  950. S_OR(arg2.val[i], ""));
  951. if (i < arg2.argc) {
  952. if (ishash) {
  953. if (origvar[0] == '_') {
  954. if (origvar[1] == '_') {
  955. snprintf(varname, sizeof(varname), "__" HASH_FORMAT, origvar + 2, arg1.var[i]);
  956. } else {
  957. snprintf(varname, sizeof(varname), "_" HASH_FORMAT, origvar + 1, arg1.var[i]);
  958. }
  959. } else {
  960. snprintf(varname, sizeof(varname), HASH_FORMAT, origvar, arg1.var[i]);
  961. }
  962. pbx_builtin_setvar_helper(chan, varname, arg2.val[i]);
  963. } else {
  964. pbx_builtin_setvar_helper(chan, arg1.var[i], arg2.val[i]);
  965. }
  966. } else {
  967. /* We could unset the variable, by passing a NULL, but due to
  968. * pushvar semantics, that could create some undesired behavior. */
  969. if (ishash) {
  970. snprintf(varname, sizeof(varname), HASH_FORMAT, origvar, arg1.var[i]);
  971. pbx_builtin_setvar_helper(chan, varname, "");
  972. } else {
  973. pbx_builtin_setvar_helper(chan, arg1.var[i], "");
  974. }
  975. }
  976. }
  977. return 0;
  978. }
  979. static int hashkeys_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  980. {
  981. struct ast_var_t *newvar;
  982. struct ast_str *prefix = ast_str_alloca(80);
  983. if (!chan) {
  984. ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
  985. return -1;
  986. }
  987. ast_str_set(&prefix, -1, HASH_PREFIX, data);
  988. memset(buf, 0, len);
  989. AST_LIST_TRAVERSE(ast_channel_varshead(chan), newvar, entries) {
  990. if (strncmp(ast_str_buffer(prefix), ast_var_name(newvar), ast_str_strlen(prefix)) == 0) {
  991. /* Copy everything after the prefix */
  992. strncat(buf, ast_var_name(newvar) + ast_str_strlen(prefix), len - strlen(buf) - 1);
  993. /* Trim the trailing ~ */
  994. buf[strlen(buf) - 1] = ',';
  995. }
  996. }
  997. /* Trim the trailing comma */
  998. buf[strlen(buf) - 1] = '\0';
  999. return 0;
  1000. }
  1001. static int hashkeys_read2(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
  1002. {
  1003. struct ast_var_t *newvar;
  1004. struct ast_str *prefix = ast_str_alloca(80);
  1005. char *tmp;
  1006. if (!chan) {
  1007. ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
  1008. return -1;
  1009. }
  1010. ast_str_set(&prefix, -1, HASH_PREFIX, data);
  1011. AST_LIST_TRAVERSE(ast_channel_varshead(chan), newvar, entries) {
  1012. if (strncmp(ast_str_buffer(prefix), ast_var_name(newvar), ast_str_strlen(prefix)) == 0) {
  1013. /* Copy everything after the prefix */
  1014. ast_str_append(buf, len, "%s", ast_var_name(newvar) + ast_str_strlen(prefix));
  1015. /* Trim the trailing ~ */
  1016. tmp = ast_str_buffer(*buf);
  1017. tmp[ast_str_strlen(*buf) - 1] = ',';
  1018. }
  1019. }
  1020. /* Trim the trailing comma */
  1021. tmp = ast_str_buffer(*buf);
  1022. tmp[ast_str_strlen(*buf) - 1] = '\0';
  1023. return 0;
  1024. }
  1025. static int hash_write(struct ast_channel *chan, const char *cmd, char *var, const char *value)
  1026. {
  1027. char varname[256];
  1028. AST_DECLARE_APP_ARGS(arg,
  1029. AST_APP_ARG(hashname);
  1030. AST_APP_ARG(hashkey);
  1031. );
  1032. if (!strchr(var, ',')) {
  1033. /* Single argument version */
  1034. return array(chan, "HASH", var, value);
  1035. }
  1036. AST_STANDARD_APP_ARGS(arg, var);
  1037. if (arg.hashname[0] == '_') {
  1038. if (arg.hashname[1] == '_') {
  1039. snprintf(varname, sizeof(varname), "__" HASH_FORMAT, arg.hashname + 2, arg.hashkey);
  1040. } else {
  1041. snprintf(varname, sizeof(varname), "_" HASH_FORMAT, arg.hashname + 1, arg.hashkey);
  1042. }
  1043. } else {
  1044. snprintf(varname, sizeof(varname), HASH_FORMAT, arg.hashname, arg.hashkey);
  1045. }
  1046. pbx_builtin_setvar_helper(chan, varname, value);
  1047. return 0;
  1048. }
  1049. static int hash_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  1050. {
  1051. char varname[256];
  1052. const char *varvalue;
  1053. AST_DECLARE_APP_ARGS(arg,
  1054. AST_APP_ARG(hashname);
  1055. AST_APP_ARG(hashkey);
  1056. );
  1057. AST_STANDARD_APP_ARGS(arg, data);
  1058. if (arg.argc == 2) {
  1059. snprintf(varname, sizeof(varname), HASH_FORMAT, arg.hashname, arg.hashkey);
  1060. varvalue = pbx_builtin_getvar_helper(chan, varname);
  1061. if (varvalue)
  1062. ast_copy_string(buf, varvalue, len);
  1063. else
  1064. *buf = '\0';
  1065. } else if (arg.argc == 1) {
  1066. char colnames[4096];
  1067. int i;
  1068. AST_DECLARE_APP_ARGS(arg2,
  1069. AST_APP_ARG(col)[100];
  1070. );
  1071. if (!chan) {
  1072. ast_log(LOG_WARNING, "No channel and only 1 parameter was provided to %s function.\n", cmd);
  1073. return -1;
  1074. }
  1075. /* Get column names, in no particular order */
  1076. hashkeys_read(chan, "HASHKEYS", arg.hashname, colnames, sizeof(colnames));
  1077. pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", colnames);
  1078. AST_STANDARD_APP_ARGS(arg2, colnames);
  1079. *buf = '\0';
  1080. /* Now get the corresponding column values, in exactly the same order */
  1081. for (i = 0; i < arg2.argc; i++) {
  1082. snprintf(varname, sizeof(varname), HASH_FORMAT, arg.hashname, arg2.col[i]);
  1083. varvalue = pbx_builtin_getvar_helper(chan, varname);
  1084. strncat(buf, varvalue, len - strlen(buf) - 1);
  1085. strncat(buf, ",", len - strlen(buf) - 1);
  1086. }
  1087. /* Strip trailing comma */
  1088. buf[strlen(buf) - 1] = '\0';
  1089. }
  1090. return 0;
  1091. }
  1092. static struct ast_custom_function hash_function = {
  1093. .name = "HASH",
  1094. .write = hash_write,
  1095. .read = hash_read,
  1096. };
  1097. static struct ast_custom_function hashkeys_function = {
  1098. .name = "HASHKEYS",
  1099. .read = hashkeys_read,
  1100. .read2 = hashkeys_read2,
  1101. };
  1102. static struct ast_custom_function array_function = {
  1103. .name = "ARRAY",
  1104. .write = array,
  1105. };
  1106. static int quote(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  1107. {
  1108. char *bufptr = buf, *dataptr = data;
  1109. if (len < 3){ /* at least two for quotes and one for binary zero */
  1110. ast_log(LOG_ERROR, "Not enough buffer\n");
  1111. return -1;
  1112. }
  1113. if (ast_strlen_zero(data)) {
  1114. ast_log(LOG_WARNING, "No argument specified!\n");
  1115. ast_copy_string(buf, "\"\"", len);
  1116. return 0;
  1117. }
  1118. *bufptr++ = '"';
  1119. for (; bufptr < buf + len - 3; dataptr++) {
  1120. if (*dataptr == '\\') {
  1121. *bufptr++ = '\\';
  1122. *bufptr++ = '\\';
  1123. } else if (*dataptr == '"') {
  1124. *bufptr++ = '\\';
  1125. *bufptr++ = '"';
  1126. } else if (*dataptr == '\0') {
  1127. break;
  1128. } else {
  1129. *bufptr++ = *dataptr;
  1130. }
  1131. }
  1132. *bufptr++ = '"';
  1133. *bufptr = '\0';
  1134. return 0;
  1135. }
  1136. static struct ast_custom_function quote_function = {
  1137. .name = "QUOTE",
  1138. .read = quote,
  1139. };
  1140. static int csv_quote(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  1141. {
  1142. char *bufptr = buf, *dataptr = data;
  1143. if (len < 3) { /* at least two for quotes and one for binary zero */
  1144. ast_log(LOG_ERROR, "Not enough buffer\n");
  1145. return -1;
  1146. }
  1147. if (ast_strlen_zero(data)) {
  1148. ast_copy_string(buf, "\"\"", len);
  1149. return 0;
  1150. }
  1151. *bufptr++ = '"';
  1152. for (; bufptr < buf + len - 3; dataptr++){
  1153. if (*dataptr == '"') {
  1154. *bufptr++ = '"';
  1155. *bufptr++ = '"';
  1156. } else if (*dataptr == '\0') {
  1157. break;
  1158. } else {
  1159. *bufptr++ = *dataptr;
  1160. }
  1161. }
  1162. *bufptr++ = '"';
  1163. *bufptr='\0';
  1164. return 0;
  1165. }
  1166. static struct ast_custom_function csv_quote_function = {
  1167. .name = "CSV_QUOTE",
  1168. .read = csv_quote,
  1169. };
  1170. static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
  1171. {
  1172. int length = 0;
  1173. if (data)
  1174. length = strlen(data);
  1175. snprintf(buf, buflen, "%d", length);
  1176. return 0;
  1177. }
  1178. static struct ast_custom_function len_function = {
  1179. .name = "LEN",
  1180. .read = len,
  1181. .read_max = 12,
  1182. };
  1183. static int acf_strftime(struct ast_channel *chan, const char *cmd, char *parse,
  1184. char *buf, size_t buflen)
  1185. {
  1186. AST_DECLARE_APP_ARGS(args,
  1187. AST_APP_ARG(epoch);
  1188. AST_APP_ARG(timezone);
  1189. AST_APP_ARG(format);
  1190. );
  1191. struct timeval when;
  1192. struct ast_tm tm;
  1193. buf[0] = '\0';
  1194. AST_STANDARD_APP_ARGS(args, parse);
  1195. ast_get_timeval(args.epoch, &when, ast_tvnow(), NULL);
  1196. ast_localtime(&when, &tm, args.timezone);
  1197. if (!args.format)
  1198. args.format = "%c";
  1199. if (ast_strftime(buf, buflen, args.format, &tm) <= 0)
  1200. ast_log(LOG_WARNING, "C function strftime() output nothing?!!\n");
  1201. buf[buflen - 1] = '\0';
  1202. return 0;
  1203. }
  1204. static struct ast_custom_function strftime_function = {
  1205. .name = "STRFTIME",
  1206. .read = acf_strftime,
  1207. };
  1208. static int acf_strptime(struct ast_channel *chan, const char *cmd, char *data,
  1209. char *buf, size_t buflen)
  1210. {
  1211. AST_DECLARE_APP_ARGS(args,
  1212. AST_APP_ARG(timestring);
  1213. AST_APP_ARG(timezone);
  1214. AST_APP_ARG(format);
  1215. );
  1216. struct ast_tm tm;
  1217. buf[0] = '\0';
  1218. if (!data) {
  1219. ast_log(LOG_ERROR,
  1220. "Asterisk function STRPTIME() requires an argument.\n");
  1221. return -1;
  1222. }
  1223. AST_STANDARD_APP_ARGS(args, data);
  1224. if (ast_strlen_zero(args.format)) {
  1225. ast_log(LOG_ERROR,
  1226. "No format supplied to STRPTIME(<timestring>,<timezone>,<format>)");
  1227. return -1;
  1228. }
  1229. if (!ast_strptime(args.timestring, args.format, &tm)) {
  1230. ast_log(LOG_WARNING, "STRPTIME() found no time specified within the string\n");
  1231. } else {
  1232. struct timeval when;
  1233. when = ast_mktime(&tm, args.timezone);
  1234. snprintf(buf, buflen, "%d", (int) when.tv_sec);
  1235. }
  1236. return 0;
  1237. }
  1238. static struct ast_custom_function strptime_function = {
  1239. .name = "STRPTIME",
  1240. .read = acf_strptime,
  1241. };
  1242. static int function_eval(struct ast_channel *chan, const char *cmd, char *data,
  1243. char *buf, size_t buflen)
  1244. {
  1245. if (ast_strlen_zero(data)) {
  1246. ast_log(LOG_WARNING, "EVAL requires an argument: EVAL(<string>)\n");
  1247. return -1;
  1248. }
  1249. pbx_substitute_variables_helper(chan, data, buf, buflen - 1);
  1250. return 0;
  1251. }
  1252. static int function_eval2(struct ast_channel *chan, const char *cmd, char *data,
  1253. struct ast_str **buf, ssize_t buflen)
  1254. {
  1255. if (ast_strlen_zero(data)) {
  1256. ast_log(LOG_WARNING, "EVAL requires an argument: EVAL(<string>)\n");
  1257. return -1;
  1258. }
  1259. ast_str_substitute_variables(buf, buflen, chan, data);
  1260. return 0;
  1261. }
  1262. static struct ast_custom_function eval_function = {
  1263. .name = "EVAL",
  1264. .read = function_eval,
  1265. .read2 = function_eval2,
  1266. };
  1267. static int keypadhash(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
  1268. {
  1269. char *bufptr, *dataptr;
  1270. for (bufptr = buf, dataptr = data; bufptr < buf + buflen - 1; dataptr++) {
  1271. if (*dataptr == '\0') {
  1272. *bufptr++ = '\0';
  1273. break;
  1274. } else if (*dataptr == '1') {
  1275. *bufptr++ = '1';
  1276. } else if (strchr("AaBbCc2", *dataptr)) {
  1277. *bufptr++ = '2';
  1278. } else if (strchr("DdEeFf3", *dataptr)) {
  1279. *bufptr++ = '3';
  1280. } else if (strchr("GgHhIi4", *dataptr)) {
  1281. *bufptr++ = '4';
  1282. } else if (strchr("JjKkLl5", *dataptr)) {
  1283. *bufptr++ = '5';
  1284. } else if (strchr("MmNnOo6", *dataptr)) {
  1285. *bufptr++ = '6';
  1286. } else if (strchr("PpQqRrSs7", *dataptr)) {
  1287. *bufptr++ = '7';
  1288. } else if (strchr("TtUuVv8", *dataptr)) {
  1289. *bufptr++ = '8';
  1290. } else if (strchr("WwXxYyZz9", *dataptr)) {
  1291. *bufptr++ = '9';
  1292. } else if (*dataptr == '0') {
  1293. *bufptr++ = '0';
  1294. }
  1295. }
  1296. buf[buflen - 1] = '\0';
  1297. return 0;
  1298. }
  1299. static struct ast_custom_function keypadhash_function = {
  1300. .name = "KEYPADHASH",
  1301. .read = keypadhash,
  1302. };
  1303. static int string_toupper(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
  1304. {
  1305. char *bufptr = buf, *dataptr = data;
  1306. while ((bufptr < buf + buflen - 1) && (*bufptr++ = toupper(*dataptr++)));
  1307. return 0;
  1308. }
  1309. static int string_toupper2(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t buflen)
  1310. {
  1311. char *bufptr, *dataptr = data;
  1312. if (buflen > -1) {
  1313. ast_str_make_space(buf, buflen > 0 ? buflen : strlen(data) + 1);
  1314. }
  1315. bufptr = ast_str_buffer(*buf);
  1316. while ((bufptr < ast_str_buffer(*buf) + ast_str_size(*buf) - 1) && (*bufptr++ = toupper(*dataptr++)));
  1317. ast_str_update(*buf);
  1318. return 0;
  1319. }
  1320. static struct ast_custom_function toupper_function = {
  1321. .name = "TOUPPER",
  1322. .read = string_toupper,
  1323. .read2 = string_toupper2,
  1324. };
  1325. static int string_tolower(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
  1326. {
  1327. char *bufptr = buf, *dataptr = data;
  1328. while ((bufptr < buf + buflen - 1) && (*bufptr++ = tolower(*dataptr++)));
  1329. return 0;
  1330. }
  1331. static int string_tolower2(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t buflen)
  1332. {
  1333. char *bufptr, *dataptr = data;
  1334. if (buflen > -1) {
  1335. ast_str_make_space(buf, buflen > 0 ? buflen : strlen(data) + 1);
  1336. }
  1337. bufptr = ast_str_buffer(*buf);
  1338. while ((bufptr < ast_str_buffer(*buf) + ast_str_size(*buf) - 1) && (*bufptr++ = tolower(*dataptr++)));
  1339. ast_str_update(*buf);
  1340. return 0;
  1341. }
  1342. static struct ast_custom_function tolower_function = {
  1343. .name = "TOLOWER",
  1344. .read = string_tolower,
  1345. .read2 = string_tolower2,
  1346. };
  1347. static int shift_pop(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
  1348. {
  1349. #define beginning (cmd[0] == 'S') /* SHIFT */
  1350. char *after, delimiter[2] = ",", *varsubst;
  1351. size_t unused;
  1352. struct ast_str *before = ast_str_thread_get(&result_buf, 16);
  1353. char *(*search_func)(const char *s, int c) = (beginning ? strchr : strrchr);
  1354. AST_DECLARE_APP_ARGS(args,
  1355. AST_APP_ARG(var);
  1356. AST_APP_ARG(delimiter);
  1357. );
  1358. if (!before) {
  1359. return -1;
  1360. }
  1361. AST_STANDARD_APP_ARGS(args, data);
  1362. if (ast_strlen_zero(args.var)) {
  1363. ast_log(LOG_WARNING, "%s requires a variable name\n", cmd);
  1364. return -1;
  1365. }
  1366. varsubst = ast_alloca(strlen(args.var) + 4);
  1367. sprintf(varsubst, "${%s}", args.var);
  1368. ast_str_substitute_variables(&before, 0, chan, varsubst);
  1369. if (args.argc > 1 && !ast_strlen_zero(args.delimiter)) {
  1370. ast_get_encoded_char(args.delimiter, delimiter, &unused);
  1371. }
  1372. if (!ast_str_strlen(before)) {
  1373. /* Nothing to pop */
  1374. return -1;
  1375. }
  1376. if (!(after = search_func(ast_str_buffer(before), delimiter[0]))) {
  1377. /* Only one entry in array */
  1378. ast_str_set(buf, len, "%s", ast_str_buffer(before));
  1379. pbx_builtin_setvar_helper(chan, args.var, "");
  1380. } else {
  1381. *after++ = '\0';
  1382. ast_str_set(buf, len, "%s", beginning ? ast_str_buffer(before) : after);
  1383. pbx_builtin_setvar_helper(chan, args.var, beginning ? after : ast_str_buffer(before));
  1384. }
  1385. return 0;
  1386. #undef beginning
  1387. }
  1388. static struct ast_custom_function shift_function = {
  1389. .name = "SHIFT",
  1390. .read2 = shift_pop,
  1391. };
  1392. static struct ast_custom_function pop_function = {
  1393. .name = "POP",
  1394. .read2 = shift_pop,
  1395. };
  1396. static int unshift_push(struct ast_channel *chan, const char *cmd, char *data, const char *new_value)
  1397. {
  1398. #define beginning (cmd[0] == 'U') /* UNSHIFT */
  1399. char delimiter[2] = ",", *varsubst;
  1400. size_t unused;
  1401. struct ast_str *buf, *previous_value;
  1402. AST_DECLARE_APP_ARGS(args,
  1403. AST_APP_ARG(var);
  1404. AST_APP_ARG(delimiter);
  1405. );
  1406. const char *stripped_var;
  1407. if (!(buf = ast_str_thread_get(&result_buf, 16)) ||
  1408. !(previous_value = ast_str_thread_get(&tmp_buf, 16))) {
  1409. return -1;
  1410. }
  1411. AST_STANDARD_APP_ARGS(args, data);
  1412. if (ast_strlen_zero(args.var)) {
  1413. ast_log(LOG_WARNING, "%s requires a variable name\n", cmd);
  1414. return -1;
  1415. }
  1416. if (args.argc > 1 && !ast_strlen_zero(args.delimiter)) {
  1417. ast_get_encoded_char(args.delimiter, delimiter, &unused);
  1418. }
  1419. /* UNSHIFT and PUSH act as ways of setting a variable, so we need to be
  1420. * sure to skip leading underscores if they appear. However, we only want
  1421. * to skip up to two since that is the maximum number that can be used to
  1422. * indicate variable inheritance. Any further underscores are part of the
  1423. * variable name.
  1424. */
  1425. stripped_var = args.var + MIN(strspn(args.var, "_"), 2);
  1426. varsubst = ast_alloca(strlen(stripped_var) + 4);
  1427. sprintf(varsubst, "${%s}", stripped_var);
  1428. ast_str_substitute_variables(&previous_value, 0, chan, varsubst);
  1429. if (!ast_str_strlen(previous_value)) {
  1430. ast_str_set(&buf, 0, "%s", new_value);
  1431. } else {
  1432. ast_str_set(&buf, 0, "%s%c%s",
  1433. beginning ? new_value : ast_str_buffer(previous_value),
  1434. delimiter[0],
  1435. beginning ? ast_str_buffer(previous_value) : new_value);
  1436. }
  1437. pbx_builtin_setvar_helper(chan, args.var, ast_str_buffer(buf));
  1438. return 0;
  1439. #undef beginning
  1440. }
  1441. static struct ast_custom_function push_function = {
  1442. .name = "PUSH",
  1443. .write = unshift_push,
  1444. };
  1445. static struct ast_custom_function unshift_function = {
  1446. .name = "UNSHIFT",
  1447. .write = unshift_push,
  1448. };
  1449. static int passthru(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
  1450. {
  1451. ast_str_set(buf, len, "%s", data);
  1452. return 0;
  1453. }
  1454. static struct ast_custom_function passthru_function = {
  1455. .name = "PASSTHRU",
  1456. .read2 = passthru,
  1457. };
  1458. #ifdef TEST_FRAMEWORK
  1459. AST_TEST_DEFINE(test_FIELDNUM)
  1460. {
  1461. int i, res = AST_TEST_PASS;
  1462. struct ast_channel *chan;
  1463. struct ast_str *str;
  1464. char expression[256];
  1465. struct {
  1466. const char *fields;
  1467. const char *delim;
  1468. const char *field;
  1469. const char *expected;
  1470. } test_args[] = {
  1471. {"abc,def,ghi,jkl", "\\,", "ghi", "3"},
  1472. {"abc def ghi jkl", " ", "abc", "1"},
  1473. {"abc/def/ghi/jkl", "\\\\x2f", "def", "2"},
  1474. {"abc$def$ghi$jkl", "", "ghi", "0"},
  1475. {"abc,def,ghi,jkl", "-", "", "0"},
  1476. {"abc-def-ghi-jkl", "-", "mno", "0"}
  1477. };
  1478. switch (cmd) {
  1479. case TEST_INIT:
  1480. info->name = "func_FIELDNUM_test";
  1481. info->category = "/funcs/func_strings/";
  1482. info->summary = "Test FIELDNUM function";
  1483. info->description = "Verify FIELDNUM behavior";
  1484. return AST_TEST_NOT_RUN;
  1485. case TEST_EXECUTE:
  1486. break;
  1487. }
  1488. if (!(chan = ast_dummy_channel_alloc())) {
  1489. ast_test_status_update(test, "Unable to allocate dummy channel\n");
  1490. return AST_TEST_FAIL;
  1491. }
  1492. if (!(str = ast_str_create(16))) {
  1493. ast_test_status_update(test, "Unable to allocate dynamic string buffer\n");
  1494. ast_channel_release(chan);
  1495. return AST_TEST_FAIL;
  1496. }
  1497. for (i = 0; i < ARRAY_LEN(test_args); i++) {
  1498. struct ast_var_t *var = ast_var_assign("FIELDS", test_args[i].fields);
  1499. if (!var) {
  1500. ast_test_status_update(test, "Out of memory\n");
  1501. res = AST_TEST_FAIL;
  1502. break;
  1503. }
  1504. AST_LIST_INSERT_HEAD(ast_channel_varshead(chan), var, entries);
  1505. snprintf(expression, sizeof(expression), "${FIELDNUM(%s,%s,%s)}", var->name, test_args[i].delim, test_args[i].field);
  1506. ast_str_substitute_variables(&str, 0, chan, expression);
  1507. AST_LIST_REMOVE(ast_channel_varshead(chan), var, entries);
  1508. ast_var_delete(var);
  1509. if (strcasecmp(ast_str_buffer(str), test_args[i].expected)) {
  1510. ast_test_status_update(test, "Evaluation of '%s' returned '%s' instead of the expected value '%s'\n",
  1511. expression, ast_str_buffer(str), test_args[i].expected);
  1512. res = AST_TEST_FAIL;
  1513. break;
  1514. }
  1515. }
  1516. ast_free(str);
  1517. ast_channel_release(chan);
  1518. return res;
  1519. }
  1520. AST_TEST_DEFINE(test_REPLACE)
  1521. {
  1522. int i, res = AST_TEST_PASS;
  1523. struct ast_channel *chan;
  1524. struct ast_str *str;
  1525. char expression[256];
  1526. struct {
  1527. const char *test_string;
  1528. const char *find_chars;
  1529. const char *replace_char;
  1530. const char *expected;
  1531. } test_args[] = {
  1532. {"abc,def", "\\,", "-", "abc-def"},
  1533. {"abc,abc", "bc", "a", "aaa,aaa"},
  1534. {"abc,def", "x", "?", "abc,def"},
  1535. {"abc,def", "\\,", "", "abcdef"}
  1536. };
  1537. switch (cmd) {
  1538. case TEST_INIT:
  1539. info->name = "func_REPLACE_test";
  1540. info->category = "/funcs/func_strings/";
  1541. info->summary = "Test REPLACE function";
  1542. info->description = "Verify REPLACE behavior";
  1543. return AST_TEST_NOT_RUN;
  1544. case TEST_EXECUTE:
  1545. break;
  1546. }
  1547. if (!(chan = ast_dummy_channel_alloc())) {
  1548. ast_test_status_update(test, "Unable to allocate dummy channel\n");
  1549. return AST_TEST_FAIL;
  1550. }
  1551. if (!(str = ast_str_create(16))) {
  1552. ast_test_status_update(test, "Unable to allocate dynamic string buffer\n");
  1553. ast_channel_release(chan);
  1554. return AST_TEST_FAIL;
  1555. }
  1556. for (i = 0; i < ARRAY_LEN(test_args); i++) {
  1557. struct ast_var_t *var = ast_var_assign("TEST_STRING", test_args[i].test_string);
  1558. if (!var) {
  1559. ast_test_status_update(test, "Out of memory\n");
  1560. res = AST_TEST_FAIL;
  1561. break;
  1562. }
  1563. AST_LIST_INSERT_HEAD(ast_channel_varshead(chan), var, entries);
  1564. snprintf(expression, sizeof(expression), "${REPLACE(%s,%s,%s)}", var->name, test_args[i].find_chars, test_args[i].replace_char);
  1565. ast_str_substitute_variables(&str, 0, chan, expression);
  1566. AST_LIST_REMOVE(ast_channel_varshead(chan), var, entries);
  1567. ast_var_delete(var);
  1568. if (strcasecmp(ast_str_buffer(str), test_args[i].expected)) {
  1569. ast_test_status_update(test, "Evaluation of '%s' returned '%s' instead of the expected value '%s'\n",
  1570. expression, ast_str_buffer(str), test_args[i].expected);
  1571. res = AST_TEST_FAIL;
  1572. break;
  1573. }
  1574. }
  1575. ast_free(str);
  1576. ast_channel_release(chan);
  1577. return res;
  1578. }
  1579. AST_TEST_DEFINE(test_FILTER)
  1580. {
  1581. int i, res = AST_TEST_PASS;
  1582. const char *test_strings[][2] = {
  1583. {"A-R", "DAHDI"},
  1584. {"A\\-R", "A"},
  1585. {"\\x41-R", "DAHDI"},
  1586. {"0-9A-Ca-c", "0042133333A12212"},
  1587. {"0-9a-cA-C_+\\-", "0042133333A12212"},
  1588. {NULL, NULL},
  1589. };
  1590. switch (cmd) {
  1591. case TEST_INIT:
  1592. info->name = "func_FILTER_test";
  1593. info->category = "/funcs/func_strings/";
  1594. info->summary = "Test FILTER function";
  1595. info->description = "Verify FILTER behavior";
  1596. return AST_TEST_NOT_RUN;
  1597. case TEST_EXECUTE:
  1598. break;
  1599. }
  1600. for (i = 0; test_strings[i][0]; i++) {
  1601. char tmp[256], tmp2[256] = "";
  1602. snprintf(tmp, sizeof(tmp), "${FILTER(%s,0042133333&DAHDI/g1/2212)}", test_strings[i][0]);
  1603. pbx_substitute_variables_helper(NULL, tmp, tmp2, sizeof(tmp2) - 1);
  1604. if (strcmp(test_strings[i][1], tmp2)) {
  1605. ast_test_status_update(test, "Format string '%s' substituted to '%s'. Expected '%s'.\n", test_strings[i][0], tmp2, test_strings[i][1]);
  1606. res = AST_TEST_FAIL;
  1607. }
  1608. }
  1609. return res;
  1610. }
  1611. AST_TEST_DEFINE(test_STRREPLACE)
  1612. {
  1613. int i, res = AST_TEST_PASS;
  1614. struct ast_channel *chan; /* dummy channel */
  1615. struct ast_str *str; /* fancy string for holding comparing value */
  1616. const char *test_strings[][5] = {
  1617. {"Weasels have eaten my telephone system", "have eaten my", "are eating our", "", "Weasels are eating our telephone system"}, /*Test normal conditions */
  1618. {"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 */
  1619. {"foofoofoofoofoofoofoo", "foofoo", "bar", NULL, "barbarbarfoo"}, /* Found string within previous match */
  1620. {"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."},
  1621. {"One and one and one is three", "and", "plus", "1", "One plus one and one is three"}, /* Test <max-replacements> = 1*/
  1622. {"", "fhqwagads", "spelunker", NULL, ""}, /* Empty primary string */
  1623. {"Part of this string is missing.", "missing", NULL, NULL, "Part of this string is ."}, /* Empty replace string */
  1624. {"'Accidentally' left off a bunch of stuff.", NULL, NULL, NULL, ""}, /* Deliberate error test from too few args */
  1625. {"This test will also error.", "", "", "", ""}, /* Deliberate error test from blank find string */
  1626. {"This is an \"escape character\" test.", "\\\"escape character\\\"", "evil", NULL, "This is an evil test."}
  1627. };
  1628. switch (cmd) {
  1629. case TEST_INIT:
  1630. info->name = "func_STRREPLACE_test";
  1631. info->category = "/funcs/func_strings/";
  1632. info->summary = "Test STRREPLACE function";
  1633. info->description = "Verify STRREPLACE behavior";
  1634. return AST_TEST_NOT_RUN;
  1635. case TEST_EXECUTE:
  1636. break;
  1637. }
  1638. if (!(chan = ast_dummy_channel_alloc())) {
  1639. ast_test_status_update(test, "Unable to allocate dummy channel\n");
  1640. return AST_TEST_FAIL;
  1641. }
  1642. if (!(str = ast_str_create(64))) {
  1643. ast_test_status_update(test, "Unable to allocate dynamic string buffer\n");
  1644. ast_channel_release(chan);
  1645. return AST_TEST_FAIL;
  1646. }
  1647. for (i = 0; i < ARRAY_LEN(test_strings); i++) {
  1648. char tmp[512], tmp2[512] = "";
  1649. struct ast_var_t *var = ast_var_assign("test_string", test_strings[i][0]);
  1650. if (!var) {
  1651. ast_test_status_update(test, "Unable to allocate variable\n");
  1652. ast_free(str);
  1653. ast_channel_release(chan);
  1654. return AST_TEST_FAIL;
  1655. }
  1656. AST_LIST_INSERT_HEAD(ast_channel_varshead(chan), var, entries);
  1657. if (test_strings[i][3]) {
  1658. snprintf(tmp, sizeof(tmp), "${STRREPLACE(%s,%s,%s,%s)}", "test_string", test_strings[i][1], test_strings[i][2], test_strings[i][3]);
  1659. } else if (test_strings[i][2]) {
  1660. snprintf(tmp, sizeof(tmp), "${STRREPLACE(%s,%s,%s)}", "test_string", test_strings[i][1], test_strings[i][2]);
  1661. } else if (test_strings[i][1]) {
  1662. snprintf(tmp, sizeof(tmp), "${STRREPLACE(%s,%s)}", "test_string", test_strings[i][1]);
  1663. } else {
  1664. snprintf(tmp, sizeof(tmp), "${STRREPLACE(%s)}", "test_string");
  1665. }
  1666. ast_str_substitute_variables(&str, 0, chan, tmp);
  1667. if (strcmp(test_strings[i][4], ast_str_buffer(str))) {
  1668. ast_test_status_update(test, "Format string '%s' substituted to '%s'. Expected '%s'.\n", test_strings[i][0], tmp2, test_strings[i][4]);
  1669. res = AST_TEST_FAIL;
  1670. }
  1671. }
  1672. ast_free(str);
  1673. ast_channel_release(chan);
  1674. return res;
  1675. }
  1676. #endif
  1677. static int unload_module(void)
  1678. {
  1679. int res = 0;
  1680. AST_TEST_UNREGISTER(test_FIELDNUM);
  1681. AST_TEST_UNREGISTER(test_REPLACE);
  1682. AST_TEST_UNREGISTER(test_FILTER);
  1683. AST_TEST_UNREGISTER(test_STRREPLACE);
  1684. res |= ast_custom_function_unregister(&fieldqty_function);
  1685. res |= ast_custom_function_unregister(&fieldnum_function);
  1686. res |= ast_custom_function_unregister(&filter_function);
  1687. res |= ast_custom_function_unregister(&replace_function);
  1688. res |= ast_custom_function_unregister(&strreplace_function);
  1689. res |= ast_custom_function_unregister(&listfilter_function);
  1690. res |= ast_custom_function_unregister(&regex_function);
  1691. res |= ast_custom_function_unregister(&array_function);
  1692. res |= ast_custom_function_unregister(&quote_function);
  1693. res |= ast_custom_function_unregister(&csv_quote_function);
  1694. res |= ast_custom_function_unregister(&len_function);
  1695. res |= ast_custom_function_unregister(&strftime_function);
  1696. res |= ast_custom_function_unregister(&strptime_function);
  1697. res |= ast_custom_function_unregister(&eval_function);
  1698. res |= ast_custom_function_unregister(&keypadhash_function);
  1699. res |= ast_custom_function_unregister(&hashkeys_function);
  1700. res |= ast_custom_function_unregister(&hash_function);
  1701. res |= ast_unregister_application(app_clearhash);
  1702. res |= ast_custom_function_unregister(&toupper_function);
  1703. res |= ast_custom_function_unregister(&tolower_function);
  1704. res |= ast_custom_function_unregister(&shift_function);
  1705. res |= ast_custom_function_unregister(&pop_function);
  1706. res |= ast_custom_function_unregister(&push_function);
  1707. res |= ast_custom_function_unregister(&unshift_function);
  1708. res |= ast_custom_function_unregister(&passthru_function);
  1709. return res;
  1710. }
  1711. static int load_module(void)
  1712. {
  1713. int res = 0;
  1714. AST_TEST_REGISTER(test_FIELDNUM);
  1715. AST_TEST_REGISTER(test_REPLACE);
  1716. AST_TEST_REGISTER(test_FILTER);
  1717. AST_TEST_REGISTER(test_STRREPLACE);
  1718. res |= ast_custom_function_register(&fieldqty_function);
  1719. res |= ast_custom_function_register(&fieldnum_function);
  1720. res |= ast_custom_function_register(&filter_function);
  1721. res |= ast_custom_function_register(&replace_function);
  1722. res |= ast_custom_function_register(&strreplace_function);
  1723. res |= ast_custom_function_register(&listfilter_function);
  1724. res |= ast_custom_function_register(&regex_function);
  1725. res |= ast_custom_function_register(&array_function);
  1726. res |= ast_custom_function_register(&quote_function);
  1727. res |= ast_custom_function_register(&csv_quote_function);
  1728. res |= ast_custom_function_register(&len_function);
  1729. res |= ast_custom_function_register(&strftime_function);
  1730. res |= ast_custom_function_register(&strptime_function);
  1731. res |= ast_custom_function_register(&eval_function);
  1732. res |= ast_custom_function_register(&keypadhash_function);
  1733. res |= ast_custom_function_register(&hashkeys_function);
  1734. res |= ast_custom_function_register(&hash_function);
  1735. res |= ast_register_application_xml(app_clearhash, exec_clearhash);
  1736. res |= ast_custom_function_register(&toupper_function);
  1737. res |= ast_custom_function_register(&tolower_function);
  1738. res |= ast_custom_function_register(&shift_function);
  1739. res |= ast_custom_function_register(&pop_function);
  1740. res |= ast_custom_function_register(&push_function);
  1741. res |= ast_custom_function_register(&unshift_function);
  1742. res |= ast_custom_function_register(&passthru_function);
  1743. return res;
  1744. }
  1745. AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "String handling dialplan functions");