res_agi.c 130 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2006, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  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 AGI - the Asterisk Gateway Interface
  21. *
  22. * \author Mark Spencer <markster@digium.com>
  23. *
  24. * \todo Convert the rest of the AGI commands over to XML documentation
  25. */
  26. /*** MODULEINFO
  27. <support_level>core</support_level>
  28. ***/
  29. #include "asterisk.h"
  30. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  31. #include <math.h>
  32. #include <signal.h>
  33. #include <sys/time.h>
  34. #include <sys/wait.h>
  35. #include <sys/stat.h>
  36. #include <pthread.h>
  37. #include "asterisk/paths.h" /* use many ast_config_AST_*_DIR */
  38. #include "asterisk/network.h"
  39. #include "asterisk/file.h"
  40. #include "asterisk/channel.h"
  41. #include "asterisk/pbx.h"
  42. #include "asterisk/module.h"
  43. #include "asterisk/astdb.h"
  44. #include "asterisk/callerid.h"
  45. #include "asterisk/cli.h"
  46. #include "asterisk/image.h"
  47. #include "asterisk/say.h"
  48. #include "asterisk/app.h"
  49. #include "asterisk/dsp.h"
  50. #include "asterisk/musiconhold.h"
  51. #include "asterisk/utils.h"
  52. #include "asterisk/lock.h"
  53. #include "asterisk/strings.h"
  54. #include "asterisk/manager.h"
  55. #include "asterisk/ast_version.h"
  56. #include "asterisk/speech.h"
  57. #include "asterisk/manager.h"
  58. #include "asterisk/term.h"
  59. #include "asterisk/xmldoc.h"
  60. #include "asterisk/srv.h"
  61. #include "asterisk/test.h"
  62. #include "asterisk/netsock2.h"
  63. #include "asterisk/stasis_channels.h"
  64. #include "asterisk/stasis_message_router.h"
  65. #include "asterisk/format_cache.h"
  66. #define AST_API_MODULE
  67. #include "asterisk/agi.h"
  68. /*** DOCUMENTATION
  69. <agi name="answer" language="en_US">
  70. <synopsis>
  71. Answer channel
  72. </synopsis>
  73. <syntax />
  74. <description>
  75. <para>Answers channel if not already in answer state. Returns <literal>-1</literal> on
  76. channel failure, or <literal>0</literal> if successful.</para>
  77. </description>
  78. <see-also>
  79. <ref type="agi">hangup</ref>
  80. </see-also>
  81. </agi>
  82. <agi name="asyncagi break" language="en_US">
  83. <synopsis>
  84. Interrupts Async AGI
  85. </synopsis>
  86. <syntax />
  87. <description>
  88. <para>Interrupts expected flow of Async AGI commands and returns control to previous source
  89. (typically, the PBX dialplan).</para>
  90. </description>
  91. <see-also>
  92. <ref type="agi">hangup</ref>
  93. </see-also>
  94. </agi>
  95. <agi name="channel status" language="en_US">
  96. <synopsis>
  97. Returns status of the connected channel.
  98. </synopsis>
  99. <syntax>
  100. <parameter name="channelname" />
  101. </syntax>
  102. <description>
  103. <para>Returns the status of the specified <replaceable>channelname</replaceable>.
  104. If no channel name is given then returns the status of the current channel.</para>
  105. <para>Return values:</para>
  106. <enumlist>
  107. <enum name="0">
  108. <para>Channel is down and available.</para>
  109. </enum>
  110. <enum name="1">
  111. <para>Channel is down, but reserved.</para>
  112. </enum>
  113. <enum name="2">
  114. <para>Channel is off hook.</para>
  115. </enum>
  116. <enum name="3">
  117. <para>Digits (or equivalent) have been dialed.</para>
  118. </enum>
  119. <enum name="4">
  120. <para>Line is ringing.</para>
  121. </enum>
  122. <enum name="5">
  123. <para>Remote end is ringing.</para>
  124. </enum>
  125. <enum name="6">
  126. <para>Line is up.</para>
  127. </enum>
  128. <enum name="7">
  129. <para>Line is busy.</para>
  130. </enum>
  131. </enumlist>
  132. </description>
  133. </agi>
  134. <agi name="control stream file" language="en_US">
  135. <synopsis>
  136. Sends audio file on channel and allows the listener to control the stream.
  137. </synopsis>
  138. <syntax>
  139. <parameter name="filename" required="true">
  140. <para>The file extension must not be included in the filename.</para>
  141. </parameter>
  142. <parameter name="escape_digits" required="true" />
  143. <parameter name="skipms" />
  144. <parameter name="ffchar">
  145. <para>Defaults to <literal>*</literal></para>
  146. </parameter>
  147. <parameter name="rewchr">
  148. <para>Defaults to <literal>#</literal></para>
  149. </parameter>
  150. <parameter name="pausechr" />
  151. <parameter name="offsetms">
  152. <para>Offset, in milliseconds, to start the audio playback</para>
  153. </parameter>
  154. </syntax>
  155. <description>
  156. <para>Send the given file, allowing playback to be controlled by the given
  157. digits, if any. Use double quotes for the digits if you wish none to be
  158. permitted. If offsetms is provided then the audio will seek to offsetms
  159. before play starts. Returns <literal>0</literal> if playback completes without a digit
  160. being pressed, or the ASCII numerical value of the digit if one was pressed,
  161. or <literal>-1</literal> on error or if the channel was disconnected. Returns the
  162. position where playback was terminated as endpos.</para>
  163. <para>It sets the following channel variables upon completion:</para>
  164. <variablelist>
  165. <variable name="CPLAYBACKSTATUS">
  166. <para>Contains the status of the attempt as a text string</para>
  167. <value name="SUCCESS" />
  168. <value name="USERSTOPPED" />
  169. <value name="REMOTESTOPPED" />
  170. <value name="ERROR" />
  171. </variable>
  172. <variable name="CPLAYBACKOFFSET">
  173. <para>Contains the offset in ms into the file where playback
  174. was at when it stopped. <literal>-1</literal> is end of file.</para>
  175. </variable>
  176. <variable name="CPLAYBACKSTOPKEY">
  177. <para>If the playback is stopped by the user this variable contains
  178. the key that was pressed.</para>
  179. </variable>
  180. </variablelist>
  181. </description>
  182. </agi>
  183. <agi name="database del" language="en_US">
  184. <synopsis>
  185. Removes database key/value
  186. </synopsis>
  187. <syntax>
  188. <parameter name="family" required="true" />
  189. <parameter name="key" required="true" />
  190. </syntax>
  191. <description>
  192. <para>Deletes an entry in the Asterisk database for a given
  193. <replaceable>family</replaceable> and <replaceable>key</replaceable>.</para>
  194. <para>Returns <literal>1</literal> if successful, <literal>0</literal>
  195. otherwise.</para>
  196. </description>
  197. </agi>
  198. <agi name="database deltree" language="en_US">
  199. <synopsis>
  200. Removes database keytree/value
  201. </synopsis>
  202. <syntax>
  203. <parameter name="family" required="true" />
  204. <parameter name="keytree" />
  205. </syntax>
  206. <description>
  207. <para>Deletes a <replaceable>family</replaceable> or specific <replaceable>keytree</replaceable>
  208. within a <replaceable>family</replaceable> in the Asterisk database.</para>
  209. <para>Returns <literal>1</literal> if successful, <literal>0</literal> otherwise.</para>
  210. </description>
  211. </agi>
  212. <agi name="database get" language="en_US">
  213. <synopsis>
  214. Gets database value
  215. </synopsis>
  216. <syntax>
  217. <parameter name="family" required="true" />
  218. <parameter name="key" required="true" />
  219. </syntax>
  220. <description>
  221. <para>Retrieves an entry in the Asterisk database for a given <replaceable>family</replaceable>
  222. and <replaceable>key</replaceable>.</para>
  223. <para>Returns <literal>0</literal> if <replaceable>key</replaceable> is not set.
  224. Returns <literal>1</literal> if <replaceable>key</replaceable> is set and returns the variable
  225. in parenthesis.</para>
  226. <para>Example return code: 200 result=1 (testvariable)</para>
  227. </description>
  228. </agi>
  229. <agi name="database put" language="en_US">
  230. <synopsis>
  231. Adds/updates database value
  232. </synopsis>
  233. <syntax>
  234. <parameter name="family" required="true" />
  235. <parameter name="key" required="true" />
  236. <parameter name="value" required="true" />
  237. </syntax>
  238. <description>
  239. <para>Adds or updates an entry in the Asterisk database for a given
  240. <replaceable>family</replaceable>, <replaceable>key</replaceable>, and
  241. <replaceable>value</replaceable>.</para>
  242. <para>Returns <literal>1</literal> if successful, <literal>0</literal> otherwise.</para>
  243. </description>
  244. </agi>
  245. <agi name="exec" language="en_US">
  246. <synopsis>
  247. Executes a given Application
  248. </synopsis>
  249. <syntax>
  250. <parameter name="application" required="true" />
  251. <parameter name="options" required="true" />
  252. </syntax>
  253. <description>
  254. <para>Executes <replaceable>application</replaceable> with given
  255. <replaceable>options</replaceable>.</para>
  256. <para>Returns whatever the <replaceable>application</replaceable> returns, or
  257. <literal>-2</literal> on failure to find <replaceable>application</replaceable>.</para>
  258. </description>
  259. </agi>
  260. <agi name="get data" language="en_US">
  261. <synopsis>
  262. Prompts for DTMF on a channel
  263. </synopsis>
  264. <syntax>
  265. <parameter name="file" required="true" />
  266. <parameter name="timeout" />
  267. <parameter name="maxdigits" />
  268. </syntax>
  269. <description>
  270. <para>Stream the given <replaceable>file</replaceable>, and receive DTMF data.</para>
  271. <para>Returns the digits received from the channel at the other end.</para>
  272. </description>
  273. </agi>
  274. <agi name="get full variable" language="en_US">
  275. <synopsis>
  276. Evaluates a channel expression
  277. </synopsis>
  278. <syntax>
  279. <parameter name="variablename" required="true" />
  280. <parameter name="channel name" />
  281. </syntax>
  282. <description>
  283. <para>Returns <literal>0</literal> if <replaceable>variablename</replaceable> is not set
  284. or channel does not exist. Returns <literal>1</literal> if <replaceable>variablename</replaceable>
  285. is set and returns the variable in parenthesis. Understands complex variable names and builtin
  286. variables, unlike GET VARIABLE.</para>
  287. <para>Example return code: 200 result=1 (testvariable)</para>
  288. </description>
  289. </agi>
  290. <agi name="get option" language="en_US">
  291. <synopsis>
  292. Stream file, prompt for DTMF, with timeout.
  293. </synopsis>
  294. <syntax>
  295. <parameter name="filename" required="true" />
  296. <parameter name="escape_digits" required="true" />
  297. <parameter name="timeout" />
  298. </syntax>
  299. <description>
  300. <para>Behaves similar to STREAM FILE but used with a timeout option.</para>
  301. </description>
  302. <see-also>
  303. <ref type="agi">stream file</ref>
  304. </see-also>
  305. </agi>
  306. <agi name="get variable" language="en_US">
  307. <synopsis>
  308. Gets a channel variable.
  309. </synopsis>
  310. <syntax>
  311. <parameter name="variablename" required="true" />
  312. </syntax>
  313. <description>
  314. <para>Returns <literal>0</literal> if <replaceable>variablename</replaceable> is not set.
  315. Returns <literal>1</literal> if <replaceable>variablename</replaceable> is set and returns
  316. the variable in parentheses.</para>
  317. <para>Example return code: 200 result=1 (testvariable)</para>
  318. </description>
  319. </agi>
  320. <agi name="hangup" language="en_US">
  321. <synopsis>
  322. Hangup a channel.
  323. </synopsis>
  324. <syntax>
  325. <parameter name="channelname" />
  326. </syntax>
  327. <description>
  328. <para>Hangs up the specified channel. If no channel name is given, hangs
  329. up the current channel</para>
  330. </description>
  331. </agi>
  332. <agi name="noop" language="en_US">
  333. <synopsis>
  334. Does nothing.
  335. </synopsis>
  336. <syntax />
  337. <description>
  338. <para>Does nothing.</para>
  339. </description>
  340. </agi>
  341. <agi name="receive char" language="en_US">
  342. <synopsis>
  343. Receives one character from channels supporting it.
  344. </synopsis>
  345. <syntax>
  346. <parameter name="timeout" required="true">
  347. <para>The maximum time to wait for input in milliseconds, or <literal>0</literal>
  348. for infinite. Most channels</para>
  349. </parameter>
  350. </syntax>
  351. <description>
  352. <para>Receives a character of text on a channel. Most channels do not support
  353. the reception of text. Returns the decimal value of the character
  354. if one is received, or <literal>0</literal> if the channel does not support
  355. text reception. Returns <literal>-1</literal> only on error/hangup.</para>
  356. </description>
  357. </agi>
  358. <agi name="receive text" language="en_US">
  359. <synopsis>
  360. Receives text from channels supporting it.
  361. </synopsis>
  362. <syntax>
  363. <parameter name="timeout" required="true">
  364. <para>The timeout to be the maximum time to wait for input in
  365. milliseconds, or <literal>0</literal> for infinite.</para>
  366. </parameter>
  367. </syntax>
  368. <description>
  369. <para>Receives a string of text on a channel. Most channels
  370. do not support the reception of text. Returns <literal>-1</literal> for failure
  371. or <literal>1</literal> for success, and the string in parenthesis.</para>
  372. </description>
  373. </agi>
  374. <agi name="record file" language="en_US">
  375. <synopsis>
  376. Records to a given file.
  377. </synopsis>
  378. <syntax>
  379. <parameter name="filename" required="true" />
  380. <parameter name="format" required="true" />
  381. <parameter name="escape_digits" required="true" />
  382. <parameter name="timeout" required="true" />
  383. <parameter name="offset samples" />
  384. <parameter name="BEEP" />
  385. <parameter name="s=silence" />
  386. </syntax>
  387. <description>
  388. <para>Record to a file until a given dtmf digit in the sequence is received.
  389. Returns <literal>-1</literal> on hangup or error. The format will specify what kind of file
  390. will be recorded. The <replaceable>timeout</replaceable> is the maximum record time in
  391. milliseconds, or <literal>-1</literal> for no <replaceable>timeout</replaceable>.
  392. <replaceable>offset samples</replaceable> is optional, and, if provided, will seek
  393. to the offset without exceeding the end of the file. <replaceable>silence</replaceable> is
  394. the number of seconds of silence allowed before the function returns despite the
  395. lack of dtmf digits or reaching <replaceable>timeout</replaceable>. <replaceable>silence</replaceable>
  396. value must be preceded by <literal>s=</literal> and is also optional.</para>
  397. </description>
  398. </agi>
  399. <agi name="say alpha" language="en_US">
  400. <synopsis>
  401. Says a given character string.
  402. </synopsis>
  403. <syntax>
  404. <parameter name="number" required="true" />
  405. <parameter name="escape_digits" required="true" />
  406. </syntax>
  407. <description>
  408. <para>Say a given character string, returning early if any of the given DTMF digits
  409. are received on the channel. Returns <literal>0</literal> if playback completes
  410. without a digit being pressed, or the ASCII numerical value of the digit if one
  411. was pressed or <literal>-1</literal> on error/hangup.</para>
  412. </description>
  413. </agi>
  414. <agi name="say digits" language="en_US">
  415. <synopsis>
  416. Says a given digit string.
  417. </synopsis>
  418. <syntax>
  419. <parameter name="number" required="true" />
  420. <parameter name="escape_digits" required="true" />
  421. </syntax>
  422. <description>
  423. <para>Say a given digit string, returning early if any of the given DTMF digits
  424. are received on the channel. Returns <literal>0</literal> if playback completes
  425. without a digit being pressed, or the ASCII numerical value of the digit if one
  426. was pressed or <literal>-1</literal> on error/hangup.</para>
  427. </description>
  428. </agi>
  429. <agi name="say number" language="en_US">
  430. <synopsis>
  431. Says a given number.
  432. </synopsis>
  433. <syntax>
  434. <parameter name="number" required="true" />
  435. <parameter name="escape_digits" required="true" />
  436. <parameter name="gender" />
  437. </syntax>
  438. <description>
  439. <para>Say a given number, returning early if any of the given DTMF digits
  440. are received on the channel. Returns <literal>0</literal> if playback
  441. completes without a digit being pressed, or the ASCII numerical value of
  442. the digit if one was pressed or <literal>-1</literal> on error/hangup.</para>
  443. </description>
  444. </agi>
  445. <agi name="say phonetic" language="en_US">
  446. <synopsis>
  447. Says a given character string with phonetics.
  448. </synopsis>
  449. <syntax>
  450. <parameter name="string" required="true" />
  451. <parameter name="escape_digits" required="true" />
  452. </syntax>
  453. <description>
  454. <para>Say a given character string with phonetics, returning early if any of the
  455. given DTMF digits are received on the channel. Returns <literal>0</literal> if
  456. playback completes without a digit pressed, the ASCII numerical value of the digit
  457. if one was pressed, or <literal>-1</literal> on error/hangup.</para>
  458. </description>
  459. </agi>
  460. <agi name="say date" language="en_US">
  461. <synopsis>
  462. Says a given date.
  463. </synopsis>
  464. <syntax>
  465. <parameter name="date" required="true">
  466. <para>Is number of seconds elapsed since 00:00:00 on January 1, 1970.
  467. Coordinated Universal Time (UTC).</para>
  468. </parameter>
  469. <parameter name="escape_digits" required="true" />
  470. </syntax>
  471. <description>
  472. <para>Say a given date, returning early if any of the given DTMF digits are
  473. received on the channel. Returns <literal>0</literal> if playback
  474. completes without a digit being pressed, or the ASCII numerical value of the
  475. digit if one was pressed or <literal>-1</literal> on error/hangup.</para>
  476. </description>
  477. </agi>
  478. <agi name="say time" language="en_US">
  479. <synopsis>
  480. Says a given time.
  481. </synopsis>
  482. <syntax>
  483. <parameter name="time" required="true">
  484. <para>Is number of seconds elapsed since 00:00:00 on January 1, 1970.
  485. Coordinated Universal Time (UTC).</para>
  486. </parameter>
  487. <parameter name="escape_digits" required="true" />
  488. </syntax>
  489. <description>
  490. <para>Say a given time, returning early if any of the given DTMF digits are
  491. received on the channel. Returns <literal>0</literal> if playback completes
  492. without a digit being pressed, or the ASCII numerical value of the digit if
  493. one was pressed or <literal>-1</literal> on error/hangup.</para>
  494. </description>
  495. </agi>
  496. <agi name="say datetime" language="en_US">
  497. <synopsis>
  498. Says a given time as specified by the format given.
  499. </synopsis>
  500. <syntax>
  501. <parameter name="time" required="true">
  502. <para>Is number of seconds elapsed since 00:00:00
  503. on January 1, 1970, Coordinated Universal Time (UTC)</para>
  504. </parameter>
  505. <parameter name="escape_digits" required="true" />
  506. <parameter name="format">
  507. <para>Is the format the time should be said in. See
  508. <filename>voicemail.conf</filename> (defaults to <literal>ABdY
  509. 'digits/at' IMp</literal>).</para>
  510. </parameter>
  511. <parameter name="timezone">
  512. <para>Acceptable values can be found in <filename>/usr/share/zoneinfo</filename>
  513. Defaults to machine default.</para>
  514. </parameter>
  515. </syntax>
  516. <description>
  517. <para>Say a given time, returning early if any of the given DTMF digits are
  518. received on the channel. Returns <literal>0</literal> if playback
  519. completes without a digit being pressed, or the ASCII numerical value of the
  520. digit if one was pressed or <literal>-1</literal> on error/hangup.</para>
  521. </description>
  522. </agi>
  523. <agi name="send image" language="en_US">
  524. <synopsis>
  525. Sends images to channels supporting it.
  526. </synopsis>
  527. <syntax>
  528. <parameter name="image" required="true" />
  529. </syntax>
  530. <description>
  531. <para>Sends the given image on a channel. Most channels do not support the
  532. transmission of images. Returns <literal>0</literal> if image is sent, or if
  533. the channel does not support image transmission. Returns <literal>-1</literal>
  534. only on error/hangup. Image names should not include extensions.</para>
  535. </description>
  536. </agi>
  537. <agi name="send text" language="en_US">
  538. <synopsis>
  539. Sends text to channels supporting it.
  540. </synopsis>
  541. <syntax>
  542. <parameter name="text to send" required="true">
  543. <para>Text consisting of greater than one word should be placed
  544. in quotes since the command only accepts a single argument.</para>
  545. </parameter>
  546. </syntax>
  547. <description>
  548. <para>Sends the given text on a channel. Most channels do not support the
  549. transmission of text. Returns <literal>0</literal> if text is sent, or if the
  550. channel does not support text transmission. Returns <literal>-1</literal> only
  551. on error/hangup.</para>
  552. </description>
  553. </agi>
  554. <agi name="set autohangup" language="en_US">
  555. <synopsis>
  556. Autohangup channel in some time.
  557. </synopsis>
  558. <syntax>
  559. <parameter name="time" required="true" />
  560. </syntax>
  561. <description>
  562. <para>Cause the channel to automatically hangup at <replaceable>time</replaceable>
  563. seconds in the future. Of course it can be hungup before then as well. Setting to
  564. <literal>0</literal> will cause the autohangup feature to be disabled on this channel.</para>
  565. </description>
  566. </agi>
  567. <agi name="set callerid" language="en_US">
  568. <synopsis>
  569. Sets callerid for the current channel.
  570. </synopsis>
  571. <syntax>
  572. <parameter name="number" required="true" />
  573. </syntax>
  574. <description>
  575. <para>Changes the callerid of the current channel.</para>
  576. </description>
  577. </agi>
  578. <agi name="set context" language="en_US">
  579. <synopsis>
  580. Sets channel context.
  581. </synopsis>
  582. <syntax>
  583. <parameter name="desired context" required="true" />
  584. </syntax>
  585. <description>
  586. <para>Sets the context for continuation upon exiting the application.</para>
  587. </description>
  588. </agi>
  589. <agi name="set extension" language="en_US">
  590. <synopsis>
  591. Changes channel extension.
  592. </synopsis>
  593. <syntax>
  594. <parameter name="new extension" required="true" />
  595. </syntax>
  596. <description>
  597. <para>Changes the extension for continuation upon exiting the application.</para>
  598. </description>
  599. </agi>
  600. <agi name="set music" language="en_US">
  601. <synopsis>
  602. Enable/Disable Music on hold generator
  603. </synopsis>
  604. <syntax>
  605. <parameter required="true">
  606. <enumlist>
  607. <enum>
  608. <parameter name="on" literal="true" required="true" />
  609. </enum>
  610. <enum>
  611. <parameter name="off" literal="true" required="true" />
  612. </enum>
  613. </enumlist>
  614. </parameter>
  615. <parameter name="class" required="true" />
  616. </syntax>
  617. <description>
  618. <para>Enables/Disables the music on hold generator. If <replaceable>class</replaceable>
  619. is not specified, then the <literal>default</literal> music on hold class will be
  620. used. This generator will be stopped automatically when playing a file.</para>
  621. <para>Always returns <literal>0</literal>.</para>
  622. </description>
  623. </agi>
  624. <agi name="set priority" language="en_US">
  625. <synopsis>
  626. Set channel dialplan priority.
  627. </synopsis>
  628. <syntax>
  629. <parameter name="priority" required="true" />
  630. </syntax>
  631. <description>
  632. <para>Changes the priority for continuation upon exiting the application.
  633. The priority must be a valid priority or label.</para>
  634. </description>
  635. </agi>
  636. <agi name="set variable" language="en_US">
  637. <synopsis>
  638. Sets a channel variable.
  639. </synopsis>
  640. <syntax>
  641. <parameter name="variablename" required="true" />
  642. <parameter name="value" required="true" />
  643. </syntax>
  644. <description>
  645. <para>Sets a variable to the current channel.</para>
  646. </description>
  647. </agi>
  648. <agi name="stream file" language="en_US">
  649. <synopsis>
  650. Sends audio file on channel.
  651. </synopsis>
  652. <syntax>
  653. <parameter name="filename" required="true">
  654. <para>File name to play. The file extension must not be
  655. included in the <replaceable>filename</replaceable>.</para>
  656. </parameter>
  657. <parameter name="escape_digits" required="true">
  658. <para>Use double quotes for the digits if you wish none to be
  659. permitted.</para>
  660. </parameter>
  661. <parameter name="sample offset">
  662. <para>If sample offset is provided then the audio will seek to sample
  663. offset before play starts.</para>
  664. </parameter>
  665. </syntax>
  666. <description>
  667. <para>Send the given file, allowing playback to be interrupted by the given
  668. digits, if any. Returns <literal>0</literal> if playback completes without a digit
  669. being pressed, or the ASCII numerical value of the digit if one was pressed,
  670. or <literal>-1</literal> on error or if the channel was disconnected. If
  671. musiconhold is playing before calling stream file it will be automatically
  672. stopped and will not be restarted after completion.</para>
  673. <para>It sets the following channel variables upon completion:</para>
  674. <variablelist>
  675. <variable name="PLAYBACKSTATUS">
  676. <para>The status of the playback attempt as a text string.</para>
  677. <value name="SUCCESS"/>
  678. <value name="FAILED"/>
  679. </variable>
  680. </variablelist>
  681. </description>
  682. <see-also>
  683. <ref type="agi">control stream file</ref>
  684. </see-also>
  685. </agi>
  686. <agi name="tdd mode" language="en_US">
  687. <synopsis>
  688. Toggles TDD mode (for the deaf).
  689. </synopsis>
  690. <syntax>
  691. <parameter name="boolean" required="true">
  692. <enumlist>
  693. <enum name="on" />
  694. <enum name="off" />
  695. </enumlist>
  696. </parameter>
  697. </syntax>
  698. <description>
  699. <para>Enable/Disable TDD transmission/reception on a channel. Returns <literal>1</literal> if
  700. successful, or <literal>0</literal> if channel is not TDD-capable.</para>
  701. </description>
  702. </agi>
  703. <agi name="verbose" language="en_US">
  704. <synopsis>
  705. Logs a message to the asterisk verbose log.
  706. </synopsis>
  707. <syntax>
  708. <parameter name="message" required="true" />
  709. <parameter name="level" required="true" />
  710. </syntax>
  711. <description>
  712. <para>Sends <replaceable>message</replaceable> to the console via verbose
  713. message system. <replaceable>level</replaceable> is the verbose level (1-4).
  714. Always returns <literal>1</literal></para>
  715. </description>
  716. </agi>
  717. <agi name="wait for digit" language="en_US">
  718. <synopsis>
  719. Waits for a digit to be pressed.
  720. </synopsis>
  721. <syntax>
  722. <parameter name="timeout" required="true" />
  723. </syntax>
  724. <description>
  725. <para>Waits up to <replaceable>timeout</replaceable> milliseconds for channel to
  726. receive a DTMF digit. Returns <literal>-1</literal> on channel failure, <literal>0</literal>
  727. if no digit is received in the timeout, or the numerical value of the ascii of the digit if
  728. one is received. Use <literal>-1</literal> for the <replaceable>timeout</replaceable> value if
  729. you desire the call to block indefinitely.</para>
  730. </description>
  731. </agi>
  732. <agi name="speech create" language="en_US">
  733. <synopsis>
  734. Creates a speech object.
  735. </synopsis>
  736. <syntax>
  737. <parameter name="engine" required="true" />
  738. </syntax>
  739. <description>
  740. <para>Create a speech object to be used by the other Speech AGI commands.</para>
  741. </description>
  742. </agi>
  743. <agi name="speech set" language="en_US">
  744. <synopsis>
  745. Sets a speech engine setting.
  746. </synopsis>
  747. <syntax>
  748. <parameter name="name" required="true" />
  749. <parameter name="value" required="true" />
  750. </syntax>
  751. <description>
  752. <para>Set an engine-specific setting.</para>
  753. </description>
  754. </agi>
  755. <agi name="speech destroy" language="en_US">
  756. <synopsis>
  757. Destroys a speech object.
  758. </synopsis>
  759. <syntax>
  760. </syntax>
  761. <description>
  762. <para>Destroy the speech object created by <literal>SPEECH CREATE</literal>.</para>
  763. </description>
  764. <see-also>
  765. <ref type="agi">speech create</ref>
  766. </see-also>
  767. </agi>
  768. <agi name="speech load grammar" language="en_US">
  769. <synopsis>
  770. Loads a grammar.
  771. </synopsis>
  772. <syntax>
  773. <parameter name="grammar name" required="true" />
  774. <parameter name="path to grammar" required="true" />
  775. </syntax>
  776. <description>
  777. <para>Loads the specified grammar as the specified name.</para>
  778. </description>
  779. </agi>
  780. <agi name="speech unload grammar" language="en_US">
  781. <synopsis>
  782. Unloads a grammar.
  783. </synopsis>
  784. <syntax>
  785. <parameter name="grammar name" required="true" />
  786. </syntax>
  787. <description>
  788. <para>Unloads the specified grammar.</para>
  789. </description>
  790. </agi>
  791. <agi name="speech activate grammar" language="en_US">
  792. <synopsis>
  793. Activates a grammar.
  794. </synopsis>
  795. <syntax>
  796. <parameter name="grammar name" required="true" />
  797. </syntax>
  798. <description>
  799. <para>Activates the specified grammar on the speech object.</para>
  800. </description>
  801. </agi>
  802. <agi name="speech deactivate grammar" language="en_US">
  803. <synopsis>
  804. Deactivates a grammar.
  805. </synopsis>
  806. <syntax>
  807. <parameter name="grammar name" required="true" />
  808. </syntax>
  809. <description>
  810. <para>Deactivates the specified grammar on the speech object.</para>
  811. </description>
  812. </agi>
  813. <agi name="speech recognize" language="en_US">
  814. <synopsis>
  815. Recognizes speech.
  816. </synopsis>
  817. <syntax>
  818. <parameter name="prompt" required="true" />
  819. <parameter name="timeout" required="true" />
  820. <parameter name="offset" />
  821. </syntax>
  822. <description>
  823. <para>Plays back given <replaceable>prompt</replaceable> while listening for
  824. speech and dtmf.</para>
  825. </description>
  826. </agi>
  827. <application name="AGI" language="en_US">
  828. <synopsis>
  829. Executes an AGI compliant application.
  830. </synopsis>
  831. <syntax>
  832. <parameter name="command" required="true" />
  833. <parameter name="args">
  834. <argument name="arg1" required="true" />
  835. <argument name="arg2" multiple="yes" />
  836. </parameter>
  837. </syntax>
  838. <description>
  839. <para>Executes an Asterisk Gateway Interface compliant
  840. program on a channel. AGI allows Asterisk to launch external programs written
  841. in any language to control a telephony channel, play audio, read DTMF digits,
  842. etc. by communicating with the AGI protocol on <emphasis>stdin</emphasis> and
  843. <emphasis>stdout</emphasis>. As of <literal>1.6.0</literal>, this channel will
  844. not stop dialplan execution on hangup inside of this application. Dialplan
  845. execution will continue normally, even upon hangup until the AGI application
  846. signals a desire to stop (either by exiting or, in the case of a net script, by
  847. closing the connection). A locally executed AGI script will receive SIGHUP on
  848. hangup from the channel except when using DeadAGI. A fast AGI server will
  849. correspondingly receive a HANGUP inline with the command dialog. Both of theses
  850. signals may be disabled by setting the <variable>AGISIGHUP</variable> channel
  851. variable to <literal>no</literal> before executing the AGI application.
  852. Alternatively, if you would like the AGI application to exit immediately
  853. after a channel hangup is detected, set the <variable>AGIEXITONHANGUP</variable>
  854. variable to <literal>yes</literal>.</para>
  855. <para>Use the CLI command <literal>agi show commands</literal> to list available agi
  856. commands.</para>
  857. <para>This application sets the following channel variable upon completion:</para>
  858. <variablelist>
  859. <variable name="AGISTATUS">
  860. <para>The status of the attempt to the run the AGI script
  861. text string, one of:</para>
  862. <value name="SUCCESS" />
  863. <value name="FAILURE" />
  864. <value name="NOTFOUND" />
  865. <value name="HANGUP" />
  866. </variable>
  867. </variablelist>
  868. </description>
  869. <see-also>
  870. <ref type="application">EAGI</ref>
  871. <ref type="application">DeadAGI</ref>
  872. </see-also>
  873. </application>
  874. <application name="EAGI" language="en_US">
  875. <synopsis>
  876. Executes an EAGI compliant application.
  877. </synopsis>
  878. <syntax>
  879. <xi:include xpointer="xpointer(/docs/application[@name='AGI']/syntax/parameter[@name='command'])" />
  880. <xi:include xpointer="xpointer(/docs/application[@name='AGI']/syntax/parameter[@name='args'])" />
  881. </syntax>
  882. <description>
  883. <para>Using 'EAGI' provides enhanced AGI, with incoming audio available out of band
  884. on file descriptor 3.</para>
  885. <xi:include xpointer="xpointer(/docs/application[@name='AGI']/description/para)" />
  886. <xi:include xpointer="xpointer(/docs/application[@name='AGI']/description/variablelist)" />
  887. </description>
  888. <see-also>
  889. <ref type="application">AGI</ref>
  890. <ref type="application">DeadAGI</ref>
  891. </see-also>
  892. </application>
  893. <application name="DeadAGI" language="en_US">
  894. <synopsis>
  895. Executes AGI on a hungup channel.
  896. </synopsis>
  897. <syntax>
  898. <xi:include xpointer="xpointer(/docs/application[@name='AGI']/syntax/parameter[@name='command'])" />
  899. <xi:include xpointer="xpointer(/docs/application[@name='AGI']/syntax/parameter[@name='args'])" />
  900. </syntax>
  901. <description>
  902. <xi:include xpointer="xpointer(/docs/application[@name='AGI']/description/para)" />
  903. <xi:include xpointer="xpointer(/docs/application[@name='AGI']/description/variablelist)" />
  904. </description>
  905. <see-also>
  906. <ref type="application">AGI</ref>
  907. <ref type="application">EAGI</ref>
  908. </see-also>
  909. </application>
  910. <manager name="AGI" language="en_US">
  911. <synopsis>
  912. Add an AGI command to execute by Async AGI.
  913. </synopsis>
  914. <syntax>
  915. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  916. <parameter name="Channel" required="true">
  917. <para>Channel that is currently in Async AGI.</para>
  918. </parameter>
  919. <parameter name="Command" required="true">
  920. <para>Application to execute.</para>
  921. </parameter>
  922. <parameter name="CommandID">
  923. <para>This will be sent back in CommandID header of AsyncAGI exec
  924. event notification.</para>
  925. </parameter>
  926. </syntax>
  927. <description>
  928. <para>Add an AGI command to the execute queue of the channel in Async AGI.</para>
  929. </description>
  930. </manager>
  931. <managerEvent language="en_US" name="AsyncAGIStart">
  932. <managerEventInstance class="EVENT_FLAG_AGI">
  933. <synopsis>Raised when a channel starts AsyncAGI command processing.</synopsis>
  934. <syntax>
  935. <channel_snapshot/>
  936. <parameter name="Env">
  937. <para>URL encoded string read from the AsyncAGI server.</para>
  938. </parameter>
  939. </syntax>
  940. </managerEventInstance>
  941. </managerEvent>
  942. <managerEvent language="en_US" name="AsyncAGIEnd">
  943. <managerEventInstance class="EVENT_FLAG_AGI">
  944. <synopsis>Raised when a channel stops AsyncAGI command processing.</synopsis>
  945. <syntax>
  946. <channel_snapshot/>
  947. </syntax>
  948. </managerEventInstance>
  949. </managerEvent>
  950. <managerEvent language="en_US" name="AsyncAGIExec">
  951. <managerEventInstance class="EVENT_FLAG_AGI">
  952. <synopsis>Raised when AsyncAGI completes an AGI command.</synopsis>
  953. <syntax>
  954. <channel_snapshot/>
  955. <parameter name="CommandID" required="false">
  956. <para>Optional command ID sent by the AsyncAGI server to identify the command.</para>
  957. </parameter>
  958. <parameter name="Result">
  959. <para>URL encoded result string from the executed AGI command.</para>
  960. </parameter>
  961. </syntax>
  962. </managerEventInstance>
  963. </managerEvent>
  964. <managerEvent language="en_US" name="AGIExecStart">
  965. <managerEventInstance class="EVENT_FLAG_AGI">
  966. <synopsis>Raised when a received AGI command starts processing.</synopsis>
  967. <syntax>
  968. <channel_snapshot/>
  969. <parameter name="Command">
  970. <para>The AGI command as received from the external source.</para>
  971. </parameter>
  972. <parameter name="CommandId">
  973. <para>Random identification number assigned to the execution of this command.</para>
  974. </parameter>
  975. </syntax>
  976. </managerEventInstance>
  977. </managerEvent>
  978. <managerEvent language="en_US" name="AGIExecEnd">
  979. <managerEventInstance class="EVENT_FLAG_AGI">
  980. <synopsis>Raised when a received AGI command completes processing.</synopsis>
  981. <syntax>
  982. <channel_snapshot/>
  983. <xi:include xpointer="xpointer(/docs/managerEvent[@name='AGIExecStart']/managerEventInstance/syntax/parameter)" />
  984. <parameter name="ResultCode">
  985. <para>The numeric result code from AGI</para>
  986. </parameter>
  987. <parameter name="Result">
  988. <para>The text result reason from AGI</para>
  989. </parameter>
  990. </syntax>
  991. </managerEventInstance>
  992. </managerEvent>
  993. ***/
  994. #define MAX_ARGS 128
  995. #define MAX_CMD_LEN 80
  996. #define AGI_NANDFS_RETRY 3
  997. #define AGI_BUF_LEN 2048
  998. #define SRV_PREFIX "_agi._tcp."
  999. static char *app = "AGI";
  1000. static char *eapp = "EAGI";
  1001. static char *deadapp = "DeadAGI";
  1002. static int agidebug = 0;
  1003. #define TONE_BLOCK_SIZE 200
  1004. /* Max time to connect to an AGI remote host */
  1005. #define MAX_AGI_CONNECT 2000
  1006. #define AGI_PORT 4573
  1007. /*! Special return code for "asyncagi break" command. */
  1008. #define ASYNC_AGI_BREAK 3
  1009. enum agi_result {
  1010. AGI_RESULT_FAILURE = -1,
  1011. AGI_RESULT_SUCCESS,
  1012. AGI_RESULT_SUCCESS_FAST,
  1013. AGI_RESULT_SUCCESS_ASYNC,
  1014. AGI_RESULT_NOTFOUND,
  1015. AGI_RESULT_HANGUP,
  1016. };
  1017. static struct ast_manager_event_blob *agi_channel_to_ami(const char *type, struct stasis_message *message)
  1018. {
  1019. struct ast_channel_blob *obj = stasis_message_data(message);
  1020. RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
  1021. RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
  1022. channel_string = ast_manager_build_channel_state_string(obj->snapshot);
  1023. event_string = ast_manager_str_from_json_object(obj->blob, NULL);
  1024. if (!channel_string || !event_string) {
  1025. return NULL;
  1026. }
  1027. return ast_manager_event_blob_create(EVENT_FLAG_AGI, type,
  1028. "%s"
  1029. "%s",
  1030. ast_str_buffer(channel_string),
  1031. ast_str_buffer(event_string));
  1032. }
  1033. static struct ast_manager_event_blob *agi_exec_start_to_ami(struct stasis_message *message)
  1034. {
  1035. return agi_channel_to_ami("AGIExecStart", message);
  1036. }
  1037. static struct ast_manager_event_blob *agi_exec_end_to_ami(struct stasis_message *message)
  1038. {
  1039. return agi_channel_to_ami("AGIExecEnd", message);
  1040. }
  1041. static struct ast_manager_event_blob *agi_async_start_to_ami(struct stasis_message *message)
  1042. {
  1043. return agi_channel_to_ami("AsyncAGIStart", message);
  1044. }
  1045. static struct ast_manager_event_blob *agi_async_exec_to_ami(struct stasis_message *message)
  1046. {
  1047. return agi_channel_to_ami("AsyncAGIExec", message);
  1048. }
  1049. static struct ast_manager_event_blob *agi_async_end_to_ami(struct stasis_message *message)
  1050. {
  1051. return agi_channel_to_ami("AsyncAGIEnd", message);
  1052. }
  1053. STASIS_MESSAGE_TYPE_DEFN_LOCAL(agi_exec_start_type,
  1054. .to_ami = agi_exec_start_to_ami,
  1055. );
  1056. STASIS_MESSAGE_TYPE_DEFN_LOCAL(agi_exec_end_type,
  1057. .to_ami = agi_exec_end_to_ami,
  1058. );
  1059. STASIS_MESSAGE_TYPE_DEFN_LOCAL(agi_async_start_type,
  1060. .to_ami = agi_async_start_to_ami,
  1061. );
  1062. STASIS_MESSAGE_TYPE_DEFN_LOCAL(agi_async_exec_type,
  1063. .to_ami = agi_async_exec_to_ami,
  1064. );
  1065. STASIS_MESSAGE_TYPE_DEFN_LOCAL(agi_async_end_type,
  1066. .to_ami = agi_async_end_to_ami,
  1067. );
  1068. static agi_command *find_command(const char * const cmds[], int exact);
  1069. AST_THREADSTORAGE(agi_buf);
  1070. #define AGI_BUF_INITSIZE 256
  1071. int AST_OPTIONAL_API_NAME(ast_agi_send)(int fd, struct ast_channel *chan, char *fmt, ...)
  1072. {
  1073. int res = 0;
  1074. va_list ap;
  1075. struct ast_str *buf;
  1076. if (!(buf = ast_str_thread_get(&agi_buf, AGI_BUF_INITSIZE)))
  1077. return -1;
  1078. va_start(ap, fmt);
  1079. res = ast_str_set_va(&buf, 0, fmt, ap);
  1080. va_end(ap);
  1081. if (res == -1) {
  1082. ast_log(LOG_ERROR, "Out of memory\n");
  1083. return -1;
  1084. }
  1085. if (agidebug) {
  1086. if (chan) {
  1087. ast_verbose("<%s>AGI Tx >> %s", ast_channel_name(chan), ast_str_buffer(buf));
  1088. } else {
  1089. ast_verbose("AGI Tx >> %s", ast_str_buffer(buf));
  1090. }
  1091. }
  1092. return ast_carefulwrite(fd, ast_str_buffer(buf), ast_str_strlen(buf), 100);
  1093. }
  1094. /* linked list of AGI commands ready to be executed by Async AGI */
  1095. struct agi_cmd {
  1096. char *cmd_buffer;
  1097. char *cmd_id;
  1098. AST_LIST_ENTRY(agi_cmd) entry;
  1099. };
  1100. static void free_agi_cmd(struct agi_cmd *cmd)
  1101. {
  1102. ast_free(cmd->cmd_buffer);
  1103. ast_free(cmd->cmd_id);
  1104. ast_free(cmd);
  1105. }
  1106. /* AGI datastore destructor */
  1107. static void agi_destroy_commands_cb(void *data)
  1108. {
  1109. struct agi_cmd *cmd;
  1110. AST_LIST_HEAD(, agi_cmd) *chan_cmds = data;
  1111. AST_LIST_LOCK(chan_cmds);
  1112. while ( (cmd = AST_LIST_REMOVE_HEAD(chan_cmds, entry)) ) {
  1113. free_agi_cmd(cmd);
  1114. }
  1115. AST_LIST_UNLOCK(chan_cmds);
  1116. AST_LIST_HEAD_DESTROY(chan_cmds);
  1117. ast_free(chan_cmds);
  1118. }
  1119. /* channel datastore to keep the queue of AGI commands in the channel */
  1120. static const struct ast_datastore_info agi_commands_datastore_info = {
  1121. .type = "AsyncAGI",
  1122. .destroy = agi_destroy_commands_cb
  1123. };
  1124. /*!
  1125. * \brief Retrieve the list head to the requested channel's AGI datastore
  1126. * \param chan Channel datastore is requested for
  1127. * \param cmd Pointer to the struct pointer which will reference the head of the agi command list.
  1128. *
  1129. * \retval 0 if the datastore was valid and the list head was retrieved appropriately (even if it's
  1130. * NULL and the list is empty)
  1131. * \retval -1 if the datastore could not be retrieved causing an error
  1132. */
  1133. static int get_agi_cmd(struct ast_channel *chan, struct agi_cmd **cmd)
  1134. {
  1135. struct ast_datastore *store;
  1136. AST_LIST_HEAD(, agi_cmd) *agi_commands;
  1137. ast_channel_lock(chan);
  1138. store = ast_channel_datastore_find(chan, &agi_commands_datastore_info, NULL);
  1139. ast_channel_unlock(chan);
  1140. if (!store) {
  1141. ast_log(LOG_ERROR, "Huh? Async AGI datastore disappeared on Channel %s!\n",
  1142. ast_channel_name(chan));
  1143. *cmd = NULL;
  1144. return -1;
  1145. }
  1146. agi_commands = store->data;
  1147. AST_LIST_LOCK(agi_commands);
  1148. *cmd = AST_LIST_REMOVE_HEAD(agi_commands, entry);
  1149. AST_LIST_UNLOCK(agi_commands);
  1150. return 0;
  1151. }
  1152. /* channel is locked when calling this one either from the CLI or manager thread */
  1153. static int add_agi_cmd(struct ast_channel *chan, const char *cmd_buff, const char *cmd_id)
  1154. {
  1155. struct ast_datastore *store;
  1156. struct agi_cmd *cmd;
  1157. AST_LIST_HEAD(, agi_cmd) *agi_commands;
  1158. store = ast_channel_datastore_find(chan, &agi_commands_datastore_info, NULL);
  1159. if (!store) {
  1160. ast_log(LOG_WARNING, "Channel %s is not setup for Async AGI.\n", ast_channel_name(chan));
  1161. return -1;
  1162. }
  1163. agi_commands = store->data;
  1164. cmd = ast_calloc(1, sizeof(*cmd));
  1165. if (!cmd) {
  1166. return -1;
  1167. }
  1168. cmd->cmd_buffer = ast_strdup(cmd_buff);
  1169. if (!cmd->cmd_buffer) {
  1170. ast_free(cmd);
  1171. return -1;
  1172. }
  1173. cmd->cmd_id = ast_strdup(cmd_id);
  1174. if (!cmd->cmd_id) {
  1175. ast_free(cmd->cmd_buffer);
  1176. ast_free(cmd);
  1177. return -1;
  1178. }
  1179. AST_LIST_LOCK(agi_commands);
  1180. AST_LIST_INSERT_TAIL(agi_commands, cmd, entry);
  1181. AST_LIST_UNLOCK(agi_commands);
  1182. return 0;
  1183. }
  1184. static int add_to_agi(struct ast_channel *chan)
  1185. {
  1186. struct ast_datastore *datastore;
  1187. AST_LIST_HEAD(, agi_cmd) *agi_cmds_list;
  1188. /* check if already on AGI */
  1189. ast_channel_lock(chan);
  1190. datastore = ast_channel_datastore_find(chan, &agi_commands_datastore_info, NULL);
  1191. ast_channel_unlock(chan);
  1192. if (datastore) {
  1193. /* we already have an AGI datastore, let's just
  1194. return success */
  1195. return 0;
  1196. }
  1197. /* the channel has never been on Async AGI,
  1198. let's allocate it's datastore */
  1199. datastore = ast_datastore_alloc(&agi_commands_datastore_info, "AGI");
  1200. if (!datastore) {
  1201. return -1;
  1202. }
  1203. agi_cmds_list = ast_calloc(1, sizeof(*agi_cmds_list));
  1204. if (!agi_cmds_list) {
  1205. ast_log(LOG_ERROR, "Unable to allocate Async AGI commands list.\n");
  1206. ast_datastore_free(datastore);
  1207. return -1;
  1208. }
  1209. datastore->data = agi_cmds_list;
  1210. AST_LIST_HEAD_INIT(agi_cmds_list);
  1211. ast_channel_lock(chan);
  1212. ast_channel_datastore_add(chan, datastore);
  1213. ast_channel_unlock(chan);
  1214. return 0;
  1215. }
  1216. /*!
  1217. * \brief CLI command to add applications to execute in Async AGI
  1218. * \param e
  1219. * \param cmd
  1220. * \param a
  1221. *
  1222. * \retval CLI_SUCCESS on success
  1223. * \retval NULL when init or tab completion is used
  1224. */
  1225. static char *handle_cli_agi_add_cmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1226. {
  1227. struct ast_channel *chan;
  1228. switch (cmd) {
  1229. case CLI_INIT:
  1230. e->command = "agi exec";
  1231. e->usage = "Usage: agi exec <channel name> <app and arguments> [id]\n"
  1232. " Add AGI command to the execute queue of the specified channel in Async AGI\n";
  1233. return NULL;
  1234. case CLI_GENERATE:
  1235. if (a->pos == 2)
  1236. return ast_complete_channels(a->line, a->word, a->pos, a->n, 2);
  1237. return NULL;
  1238. }
  1239. if (a->argc < 4) {
  1240. return CLI_SHOWUSAGE;
  1241. }
  1242. if (!(chan = ast_channel_get_by_name(a->argv[2]))) {
  1243. ast_cli(a->fd, "Channel %s does not exist.\n", a->argv[2]);
  1244. return CLI_FAILURE;
  1245. }
  1246. ast_channel_lock(chan);
  1247. if (add_agi_cmd(chan, a->argv[3], (a->argc > 4 ? a->argv[4] : ""))) {
  1248. ast_cli(a->fd, "Failed to add AGI command to queue of channel %s\n", ast_channel_name(chan));
  1249. ast_channel_unlock(chan);
  1250. chan = ast_channel_unref(chan);
  1251. return CLI_FAILURE;
  1252. }
  1253. ast_debug(1, "Added AGI command to channel %s queue\n", ast_channel_name(chan));
  1254. ast_channel_unlock(chan);
  1255. chan = ast_channel_unref(chan);
  1256. return CLI_SUCCESS;
  1257. }
  1258. /*!
  1259. * \brief Add a new command to execute by the Async AGI application
  1260. * \param s
  1261. * \param m
  1262. *
  1263. * It will append the application to the specified channel's queue
  1264. * if the channel is not inside Async AGI application it will return an error
  1265. * \retval 0 on success or incorrect use
  1266. * \retval 1 on failure to add the command ( most likely because the channel
  1267. * is not in Async AGI loop )
  1268. */
  1269. static int action_add_agi_cmd(struct mansession *s, const struct message *m)
  1270. {
  1271. const char *channel = astman_get_header(m, "Channel");
  1272. const char *cmdbuff = astman_get_header(m, "Command");
  1273. const char *cmdid = astman_get_header(m, "CommandID");
  1274. struct ast_channel *chan;
  1275. char buf[256];
  1276. if (ast_strlen_zero(channel) || ast_strlen_zero(cmdbuff)) {
  1277. astman_send_error(s, m, "Both, Channel and Command are *required*");
  1278. return 0;
  1279. }
  1280. if (!(chan = ast_channel_get_by_name(channel))) {
  1281. snprintf(buf, sizeof(buf), "Channel %s does not exist.", channel);
  1282. astman_send_error(s, m, buf);
  1283. return 0;
  1284. }
  1285. ast_channel_lock(chan);
  1286. if (add_agi_cmd(chan, cmdbuff, cmdid)) {
  1287. snprintf(buf, sizeof(buf), "Failed to add AGI command to channel %s queue", ast_channel_name(chan));
  1288. astman_send_error(s, m, buf);
  1289. ast_channel_unlock(chan);
  1290. chan = ast_channel_unref(chan);
  1291. return 0;
  1292. }
  1293. ast_channel_unlock(chan);
  1294. chan = ast_channel_unref(chan);
  1295. astman_send_ack(s, m, "Added AGI command to queue");
  1296. return 0;
  1297. }
  1298. static enum agi_result agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf, int dead);
  1299. static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced, int argc, char *argv[]);
  1300. /*!
  1301. * \internal
  1302. * \brief Read and handle a channel frame for Async AGI.
  1303. *
  1304. * \param chan Channel to read a frame from.
  1305. *
  1306. * \retval AGI_RESULT_SUCCESS on success.
  1307. * \retval AGI_RESULT_HANGUP on hangup.
  1308. * \retval AGI_RESULT_FAILURE on error.
  1309. */
  1310. static enum agi_result async_agi_read_frame(struct ast_channel *chan)
  1311. {
  1312. struct ast_frame *f;
  1313. f = ast_read(chan);
  1314. if (!f) {
  1315. ast_debug(3, "No frame read on channel %s, going out ...\n", ast_channel_name(chan));
  1316. return AGI_RESULT_HANGUP;
  1317. }
  1318. if (f->frametype == AST_FRAME_CONTROL) {
  1319. /*
  1320. * Is there any other frame we should care about besides
  1321. * AST_CONTROL_HANGUP?
  1322. */
  1323. switch (f->subclass.integer) {
  1324. case AST_CONTROL_HANGUP:
  1325. ast_debug(3, "Got HANGUP frame on channel %s, going out ...\n", ast_channel_name(chan));
  1326. ast_frfree(f);
  1327. return AGI_RESULT_HANGUP;
  1328. default:
  1329. break;
  1330. }
  1331. }
  1332. ast_frfree(f);
  1333. return AGI_RESULT_SUCCESS;
  1334. }
  1335. static enum agi_result launch_asyncagi(struct ast_channel *chan, int argc, char *argv[], int *efd)
  1336. {
  1337. /* This buffer sizes might cause truncation if the AGI command writes more data
  1338. than AGI_BUF_SIZE as result. But let's be serious, is there an AGI command
  1339. that writes a response larger than 1024 bytes?, I don't think so, most of
  1340. them are just result=blah stuff. However probably if GET VARIABLE is called
  1341. and the variable has large amount of data, that could be a problem. We could
  1342. make this buffers dynamic, but let's leave that as a second step.
  1343. AMI_BUF_SIZE is twice AGI_BUF_SIZE just for the sake of choosing a safe
  1344. number. Some characters of AGI buf will be url encoded to be sent to manager
  1345. clients. An URL encoded character will take 3 bytes, but again, to cause
  1346. truncation more than about 70% of the AGI buffer should be URL encoded for
  1347. that to happen. Not likely at all.
  1348. On the other hand. I wonder if read() could eventually return less data than
  1349. the amount already available in the pipe? If so, how to deal with that?
  1350. So far, my tests on Linux have not had any problems.
  1351. */
  1352. #define AGI_BUF_SIZE 1024
  1353. #define AMI_BUF_SIZE 2048
  1354. enum agi_result cmd_status;
  1355. struct agi_cmd *cmd;
  1356. int res;
  1357. int fds[2];
  1358. int hungup;
  1359. int timeout = 100;
  1360. char agi_buffer[AGI_BUF_SIZE + 1];
  1361. char ami_buffer[AMI_BUF_SIZE];
  1362. enum agi_result returnstatus = AGI_RESULT_SUCCESS;
  1363. AGI async_agi;
  1364. RAII_VAR(struct ast_json *, startblob, NULL, ast_json_unref);
  1365. if (efd) {
  1366. ast_log(LOG_WARNING, "Async AGI does not support Enhanced AGI yet\n");
  1367. return AGI_RESULT_FAILURE;
  1368. }
  1369. /* add AsyncAGI datastore to the channel */
  1370. if (add_to_agi(chan)) {
  1371. ast_log(LOG_ERROR, "Failed to start Async AGI on channel %s\n", ast_channel_name(chan));
  1372. return AGI_RESULT_FAILURE;
  1373. }
  1374. /* this pipe allows us to create a "fake" AGI struct to use
  1375. the AGI commands */
  1376. res = pipe(fds);
  1377. if (res) {
  1378. ast_log(LOG_ERROR, "Failed to create Async AGI pipe\n");
  1379. /*
  1380. * Intentionally do not remove the datastore added with
  1381. * add_to_agi() the from channel. It will be removed when the
  1382. * channel is hung up anyway.
  1383. */
  1384. return AGI_RESULT_FAILURE;
  1385. }
  1386. /* handlers will get the pipe write fd and we read the AGI responses
  1387. from the pipe read fd */
  1388. async_agi.fd = fds[1];
  1389. async_agi.ctrl = fds[1];
  1390. async_agi.audio = -1; /* no audio support */
  1391. async_agi.fast = 0;
  1392. async_agi.speech = NULL;
  1393. /* notify possible manager users of a new channel ready to
  1394. receive commands */
  1395. setup_env(chan, "async", fds[1], 0, argc, argv);
  1396. /* read the environment */
  1397. res = read(fds[0], agi_buffer, AGI_BUF_SIZE);
  1398. if (res <= 0) {
  1399. ast_log(LOG_ERROR, "Failed to read from Async AGI pipe on channel %s: %s\n",
  1400. ast_channel_name(chan), res < 0 ? strerror(errno) : "EOF");
  1401. returnstatus = AGI_RESULT_FAILURE;
  1402. goto async_agi_abort;
  1403. }
  1404. agi_buffer[res] = '\0';
  1405. /* encode it and send it thru the manager so whoever is going to take
  1406. care of AGI commands on this channel can decide which AGI commands
  1407. to execute based on the setup info */
  1408. ast_uri_encode(agi_buffer, ami_buffer, AMI_BUF_SIZE, ast_uri_http);
  1409. startblob = ast_json_pack("{s: s}", "Env", ami_buffer);
  1410. ast_channel_publish_cached_blob(chan, agi_async_start_type(), startblob);
  1411. hungup = ast_check_hangup_locked(chan);
  1412. for (;;) {
  1413. /*
  1414. * Process as many commands as we can. Commands are added via
  1415. * the manager or the cli threads.
  1416. */
  1417. while (!hungup) {
  1418. RAII_VAR(struct ast_json *, execblob, NULL, ast_json_unref);
  1419. res = get_agi_cmd(chan, &cmd);
  1420. if (res) {
  1421. returnstatus = AGI_RESULT_FAILURE;
  1422. goto async_agi_done;
  1423. } else if (!cmd) {
  1424. break;
  1425. }
  1426. /* OK, we have a command, let's call the command handler. */
  1427. cmd_status = agi_handle_command(chan, &async_agi, cmd->cmd_buffer, 0);
  1428. /*
  1429. * The command handler must have written to our fake AGI struct
  1430. * fd (the pipe), let's read the response.
  1431. */
  1432. res = read(fds[0], agi_buffer, AGI_BUF_SIZE);
  1433. if (res <= 0) {
  1434. ast_log(LOG_ERROR, "Failed to read from Async AGI pipe on channel %s: %s\n",
  1435. ast_channel_name(chan), res < 0 ? strerror(errno) : "EOF");
  1436. free_agi_cmd(cmd);
  1437. returnstatus = AGI_RESULT_FAILURE;
  1438. goto async_agi_done;
  1439. }
  1440. /*
  1441. * We have a response, let's send the response thru the manager.
  1442. * Include the CommandID if it was specified when the command
  1443. * was added.
  1444. */
  1445. agi_buffer[res] = '\0';
  1446. ast_uri_encode(agi_buffer, ami_buffer, AMI_BUF_SIZE, ast_uri_http);
  1447. execblob = ast_json_pack("{s: s}", "Result", ami_buffer);
  1448. if (execblob && !ast_strlen_zero(cmd->cmd_id)) {
  1449. ast_json_object_set(execblob, "CommandId", ast_json_string_create(cmd->cmd_id));
  1450. }
  1451. ast_channel_publish_cached_blob(chan, agi_async_exec_type(), execblob);
  1452. free_agi_cmd(cmd);
  1453. /*
  1454. * Check the command status to determine if we should continue
  1455. * executing more commands.
  1456. */
  1457. hungup = ast_check_hangup(chan);
  1458. switch (cmd_status) {
  1459. case AGI_RESULT_FAILURE:
  1460. if (!hungup) {
  1461. /* The failure was not because of a hangup. */
  1462. returnstatus = AGI_RESULT_FAILURE;
  1463. goto async_agi_done;
  1464. }
  1465. break;
  1466. case AGI_RESULT_SUCCESS_ASYNC:
  1467. /* Only the "asyncagi break" command does this. */
  1468. returnstatus = AGI_RESULT_SUCCESS_ASYNC;
  1469. goto async_agi_done;
  1470. default:
  1471. break;
  1472. }
  1473. }
  1474. if (!hungup) {
  1475. /* Wait a bit for a frame to read or to poll for a new command. */
  1476. res = ast_waitfor(chan, timeout);
  1477. if (res < 0) {
  1478. ast_debug(1, "ast_waitfor returned <= 0 on chan %s\n", ast_channel_name(chan));
  1479. returnstatus = AGI_RESULT_FAILURE;
  1480. break;
  1481. }
  1482. } else {
  1483. /*
  1484. * Read the channel control queue until it is dry so we can
  1485. * quit.
  1486. */
  1487. res = 1;
  1488. }
  1489. if (0 < res) {
  1490. do {
  1491. cmd_status = async_agi_read_frame(chan);
  1492. if (cmd_status != AGI_RESULT_SUCCESS) {
  1493. returnstatus = cmd_status;
  1494. goto async_agi_done;
  1495. }
  1496. hungup = ast_check_hangup(chan);
  1497. } while (hungup);
  1498. } else {
  1499. hungup = ast_check_hangup(chan);
  1500. }
  1501. }
  1502. async_agi_done:
  1503. if (async_agi.speech) {
  1504. ast_speech_destroy(async_agi.speech);
  1505. }
  1506. /* notify manager users this channel cannot be controlled anymore by Async AGI */
  1507. ast_channel_publish_cached_blob(chan, agi_async_end_type(), NULL);
  1508. async_agi_abort:
  1509. /* close the pipe */
  1510. close(fds[0]);
  1511. close(fds[1]);
  1512. /*
  1513. * Intentionally do not remove the datastore added with
  1514. * add_to_agi() the from channel. There might be commands still
  1515. * in the queue or in-flight to us and AsyncAGI may get called
  1516. * again. The datastore destructor will be called on channel
  1517. * destruction anyway.
  1518. */
  1519. if (returnstatus == AGI_RESULT_SUCCESS) {
  1520. returnstatus = AGI_RESULT_SUCCESS_ASYNC;
  1521. }
  1522. return returnstatus;
  1523. #undef AGI_BUF_SIZE
  1524. #undef AMI_BUF_SIZE
  1525. }
  1526. /*!
  1527. * \internal
  1528. * \brief Handle the connection that was started by launch_netscript.
  1529. *
  1530. * \param agiurl Url that we are trying to connect to.
  1531. * \param addr Address that host was resolved to.
  1532. * \param netsockfd File descriptor of socket.
  1533. *
  1534. * \retval 0 when connection is succesful.
  1535. * \retval 1 when there is an error.
  1536. */
  1537. static int handle_connection(const char *agiurl, const struct ast_sockaddr addr, const int netsockfd)
  1538. {
  1539. struct pollfd pfds[1];
  1540. int res, conresult;
  1541. socklen_t reslen;
  1542. reslen = sizeof(conresult);
  1543. pfds[0].fd = netsockfd;
  1544. pfds[0].events = POLLOUT;
  1545. while ((res = ast_poll(pfds, 1, MAX_AGI_CONNECT)) != 1) {
  1546. if (errno != EINTR) {
  1547. if (!res) {
  1548. ast_log(LOG_WARNING, "FastAGI connection to '%s' timed out after MAX_AGI_CONNECT (%d) milliseconds.\n",
  1549. agiurl, MAX_AGI_CONNECT);
  1550. } else {
  1551. ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", agiurl, strerror(errno));
  1552. }
  1553. return 1;
  1554. }
  1555. }
  1556. if (getsockopt(pfds[0].fd, SOL_SOCKET, SO_ERROR, &conresult, &reslen) < 0) {
  1557. ast_log(LOG_WARNING, "Connection to %s failed with error: %s\n",
  1558. ast_sockaddr_stringify(&addr), strerror(errno));
  1559. return 1;
  1560. }
  1561. if (conresult) {
  1562. ast_log(LOG_WARNING, "Connecting to '%s' failed for url '%s': %s\n",
  1563. ast_sockaddr_stringify(&addr), agiurl, strerror(conresult));
  1564. return 1;
  1565. }
  1566. return 0;
  1567. }
  1568. /* launch_netscript: The fastagi handler.
  1569. FastAGI defaults to port 4573 */
  1570. static enum agi_result launch_netscript(char *agiurl, char *argv[], int *fds)
  1571. {
  1572. int s = 0, flags;
  1573. char *host, *script;
  1574. int num_addrs = 0, i = 0;
  1575. struct ast_sockaddr *addrs;
  1576. /* agiurl is "agi://host.domain[:port][/script/name]" */
  1577. host = ast_strdupa(agiurl + 6); /* Remove agi:// */
  1578. /* Strip off any script name */
  1579. if ((script = strchr(host, '/'))) {
  1580. *script++ = '\0';
  1581. } else {
  1582. script = "";
  1583. }
  1584. if (!(num_addrs = ast_sockaddr_resolve(&addrs, host, 0, AST_AF_UNSPEC))) {
  1585. ast_log(LOG_WARNING, "Unable to locate host '%s'\n", host);
  1586. return AGI_RESULT_FAILURE;
  1587. }
  1588. for (i = 0; i < num_addrs; i++) {
  1589. if (!ast_sockaddr_port(&addrs[i])) {
  1590. ast_sockaddr_set_port(&addrs[i], AGI_PORT);
  1591. }
  1592. if ((s = socket(addrs[i].ss.ss_family, SOCK_STREAM, IPPROTO_TCP)) < 0) {
  1593. ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
  1594. continue;
  1595. }
  1596. if ((flags = fcntl(s, F_GETFL)) < 0) {
  1597. ast_log(LOG_WARNING, "fcntl(F_GETFL) failed: %s\n", strerror(errno));
  1598. close(s);
  1599. continue;
  1600. }
  1601. if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0) {
  1602. ast_log(LOG_WARNING, "fnctl(F_SETFL) failed: %s\n", strerror(errno));
  1603. close(s);
  1604. continue;
  1605. }
  1606. if (ast_connect(s, &addrs[i]) && errno == EINPROGRESS) {
  1607. if (handle_connection(agiurl, addrs[i], s)) {
  1608. close(s);
  1609. continue;
  1610. }
  1611. } else {
  1612. ast_log(LOG_WARNING, "Connection to %s failed with unexpected error: %s\n",
  1613. ast_sockaddr_stringify(&addrs[i]), strerror(errno));
  1614. }
  1615. break;
  1616. }
  1617. ast_free(addrs);
  1618. if (i == num_addrs) {
  1619. ast_log(LOG_WARNING, "Couldn't connect to any host. FastAGI failed.\n");
  1620. return AGI_RESULT_FAILURE;
  1621. }
  1622. if (ast_agi_send(s, NULL, "agi_network: yes\n") < 0) {
  1623. if (errno != EINTR) {
  1624. ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", agiurl, strerror(errno));
  1625. close(s);
  1626. return AGI_RESULT_FAILURE;
  1627. }
  1628. }
  1629. /* If we have a script parameter, relay it to the fastagi server */
  1630. /* Script parameters take the form of: AGI(agi://my.example.com/?extension=${EXTEN}) */
  1631. if (!ast_strlen_zero(script)) {
  1632. ast_agi_send(s, NULL, "agi_network_script: %s\n", script);
  1633. }
  1634. ast_debug(4, "Wow, connected!\n");
  1635. fds[0] = s;
  1636. fds[1] = s;
  1637. return AGI_RESULT_SUCCESS_FAST;
  1638. }
  1639. /*!
  1640. * \internal
  1641. * \brief The HA fastagi handler.
  1642. * \param agiurl The request URL as passed to Agi() in the dial plan
  1643. * \param argv The parameters after the URL passed to Agi() in the dial plan
  1644. * \param fds Input/output file descriptors
  1645. *
  1646. * Uses SRV lookups to try to connect to a list of FastAGI servers. The hostname in
  1647. * the URI is prefixed with _agi._tcp. prior to the DNS resolution. For
  1648. * example, if you specify the URI \a hagi://agi.example.com/foo.agi the DNS
  1649. * query would be for \a _agi._tcp.agi.example.com and you'll need to make sure
  1650. * this resolves.
  1651. *
  1652. * This function parses the URI, resolves the SRV service name, forms new URIs
  1653. * with the results of the DNS lookup, and then calls launch_netscript on the
  1654. * new URIs until one succeeds.
  1655. *
  1656. * \return the result of the AGI operation.
  1657. */
  1658. static enum agi_result launch_ha_netscript(char *agiurl, char *argv[], int *fds)
  1659. {
  1660. char *host, *script;
  1661. enum agi_result result;
  1662. struct srv_context *context = NULL;
  1663. int srv_ret;
  1664. char service[256];
  1665. char resolved_uri[1024];
  1666. const char *srvhost;
  1667. unsigned short srvport;
  1668. /* format of agiurl is "hagi://host.domain[:port][/script/name]" */
  1669. if (strlen(agiurl) < 7) { /* Remove hagi:// */
  1670. ast_log(LOG_WARNING, "An error occurred parsing the AGI URI: %s", agiurl);
  1671. return AGI_RESULT_FAILURE;
  1672. }
  1673. host = ast_strdupa(agiurl + 7);
  1674. /* Strip off any script name */
  1675. if ((script = strchr(host, '/'))) {
  1676. *script++ = '\0';
  1677. } else {
  1678. script = "";
  1679. }
  1680. if (strchr(host, ':')) {
  1681. ast_log(LOG_WARNING, "Specifying a port number disables SRV lookups: %s\n", agiurl);
  1682. return launch_netscript(agiurl + 1, argv, fds); /* +1 to strip off leading h from hagi:// */
  1683. }
  1684. snprintf(service, sizeof(service), "%s%s", SRV_PREFIX, host);
  1685. while (!(srv_ret = ast_srv_lookup(&context, service, &srvhost, &srvport))) {
  1686. snprintf(resolved_uri, sizeof(resolved_uri), "agi://%s:%d/%s", srvhost, srvport, script);
  1687. result = launch_netscript(resolved_uri, argv, fds);
  1688. if (result == AGI_RESULT_FAILURE || result == AGI_RESULT_NOTFOUND) {
  1689. ast_log(LOG_WARNING, "AGI request failed for host '%s' (%s:%d)\n", host, srvhost, srvport);
  1690. } else {
  1691. /* The script launched so we must cleanup the context. */
  1692. ast_srv_cleanup(&context);
  1693. return result;
  1694. }
  1695. }
  1696. /*
  1697. * The DNS SRV lookup failed or we ran out of servers to check.
  1698. * ast_srv_lookup() has already cleaned up the context for us.
  1699. */
  1700. if (srv_ret < 0) {
  1701. ast_log(LOG_WARNING, "SRV lookup failed for %s\n", agiurl);
  1702. }
  1703. return AGI_RESULT_FAILURE;
  1704. }
  1705. static enum agi_result launch_script(struct ast_channel *chan, char *script, int argc, char *argv[], int *fds, int *efd, int *opid)
  1706. {
  1707. char tmp[256];
  1708. int pid, toast[2], fromast[2], audio[2], res;
  1709. struct stat st;
  1710. if (!strncasecmp(script, "agi://", 6)) {
  1711. return (efd == NULL) ? launch_netscript(script, argv, fds) : AGI_RESULT_FAILURE;
  1712. }
  1713. if (!strncasecmp(script, "hagi://", 7)) {
  1714. return (efd == NULL) ? launch_ha_netscript(script, argv, fds) : AGI_RESULT_FAILURE;
  1715. }
  1716. if (!strncasecmp(script, "agi:async", sizeof("agi:async") - 1)) {
  1717. return launch_asyncagi(chan, argc, argv, efd);
  1718. }
  1719. if (script[0] != '/') {
  1720. snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_AGI_DIR, script);
  1721. script = tmp;
  1722. }
  1723. /* Before even trying let's see if the file actually exists */
  1724. if (stat(script, &st)) {
  1725. ast_log(LOG_WARNING, "Failed to execute '%s': File does not exist.\n", script);
  1726. return AGI_RESULT_NOTFOUND;
  1727. }
  1728. if (pipe(toast)) {
  1729. ast_log(LOG_WARNING, "Unable to create toast pipe: %s\n",strerror(errno));
  1730. return AGI_RESULT_FAILURE;
  1731. }
  1732. if (pipe(fromast)) {
  1733. ast_log(LOG_WARNING, "unable to create fromast pipe: %s\n", strerror(errno));
  1734. close(toast[0]);
  1735. close(toast[1]);
  1736. return AGI_RESULT_FAILURE;
  1737. }
  1738. if (efd) {
  1739. if (pipe(audio)) {
  1740. ast_log(LOG_WARNING, "unable to create audio pipe: %s\n", strerror(errno));
  1741. close(fromast[0]);
  1742. close(fromast[1]);
  1743. close(toast[0]);
  1744. close(toast[1]);
  1745. return AGI_RESULT_FAILURE;
  1746. }
  1747. res = fcntl(audio[1], F_GETFL);
  1748. if (res > -1)
  1749. res = fcntl(audio[1], F_SETFL, res | O_NONBLOCK);
  1750. if (res < 0) {
  1751. ast_log(LOG_WARNING, "unable to set audio pipe parameters: %s\n", strerror(errno));
  1752. close(fromast[0]);
  1753. close(fromast[1]);
  1754. close(toast[0]);
  1755. close(toast[1]);
  1756. close(audio[0]);
  1757. close(audio[1]);
  1758. return AGI_RESULT_FAILURE;
  1759. }
  1760. }
  1761. if ((pid = ast_safe_fork(1)) < 0) {
  1762. ast_log(LOG_WARNING, "Failed to fork(): %s\n", strerror(errno));
  1763. return AGI_RESULT_FAILURE;
  1764. }
  1765. if (!pid) {
  1766. /* Pass paths to AGI via environmental variables */
  1767. setenv("AST_CONFIG_DIR", ast_config_AST_CONFIG_DIR, 1);
  1768. setenv("AST_CONFIG_FILE", ast_config_AST_CONFIG_FILE, 1);
  1769. setenv("AST_MODULE_DIR", ast_config_AST_MODULE_DIR, 1);
  1770. setenv("AST_SPOOL_DIR", ast_config_AST_SPOOL_DIR, 1);
  1771. setenv("AST_MONITOR_DIR", ast_config_AST_MONITOR_DIR, 1);
  1772. setenv("AST_VAR_DIR", ast_config_AST_VAR_DIR, 1);
  1773. setenv("AST_DATA_DIR", ast_config_AST_DATA_DIR, 1);
  1774. setenv("AST_LOG_DIR", ast_config_AST_LOG_DIR, 1);
  1775. setenv("AST_AGI_DIR", ast_config_AST_AGI_DIR, 1);
  1776. setenv("AST_KEY_DIR", ast_config_AST_KEY_DIR, 1);
  1777. setenv("AST_RUN_DIR", ast_config_AST_RUN_DIR, 1);
  1778. /* Don't run AGI scripts with realtime priority -- it causes audio stutter */
  1779. ast_set_priority(0);
  1780. /* Redirect stdin and out, provide enhanced audio channel if desired */
  1781. dup2(fromast[0], STDIN_FILENO);
  1782. dup2(toast[1], STDOUT_FILENO);
  1783. if (efd)
  1784. dup2(audio[0], STDERR_FILENO + 1);
  1785. else
  1786. close(STDERR_FILENO + 1);
  1787. /* Close everything but stdin/out/error */
  1788. ast_close_fds_above_n(STDERR_FILENO + 1);
  1789. /* Execute script */
  1790. /* XXX argv should be deprecated in favor of passing agi_argX paramaters */
  1791. execv(script, argv);
  1792. /* Can't use ast_log since FD's are closed */
  1793. ast_child_verbose(1, "Failed to execute '%s': %s", script, strerror(errno));
  1794. /* Special case to set status of AGI to failure */
  1795. fprintf(stdout, "failure\n");
  1796. fflush(stdout);
  1797. _exit(1);
  1798. }
  1799. ast_verb(3, "Launched AGI Script %s\n", script);
  1800. fds[0] = toast[0];
  1801. fds[1] = fromast[1];
  1802. if (efd)
  1803. *efd = audio[1];
  1804. /* close what we're not using in the parent */
  1805. close(toast[1]);
  1806. close(fromast[0]);
  1807. if (efd)
  1808. close(audio[0]);
  1809. *opid = pid;
  1810. return AGI_RESULT_SUCCESS;
  1811. }
  1812. static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced, int argc, char *argv[])
  1813. {
  1814. int count;
  1815. /* Print initial environment, with agi_request always being the first
  1816. thing */
  1817. ast_agi_send(fd, chan, "agi_request: %s\n", request);
  1818. ast_agi_send(fd, chan, "agi_channel: %s\n", ast_channel_name(chan));
  1819. ast_agi_send(fd, chan, "agi_language: %s\n", ast_channel_language(chan));
  1820. ast_agi_send(fd, chan, "agi_type: %s\n", ast_channel_tech(chan)->type);
  1821. ast_agi_send(fd, chan, "agi_uniqueid: %s\n", ast_channel_uniqueid(chan));
  1822. ast_agi_send(fd, chan, "agi_version: %s\n", ast_get_version());
  1823. /* ANI/DNIS */
  1824. ast_agi_send(fd, chan, "agi_callerid: %s\n",
  1825. S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "unknown"));
  1826. ast_agi_send(fd, chan, "agi_calleridname: %s\n",
  1827. S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "unknown"));
  1828. ast_agi_send(fd, chan, "agi_callingpres: %d\n",
  1829. ast_party_id_presentation(&ast_channel_caller(chan)->id));
  1830. ast_agi_send(fd, chan, "agi_callingani2: %d\n", ast_channel_caller(chan)->ani2);
  1831. ast_agi_send(fd, chan, "agi_callington: %d\n", ast_channel_caller(chan)->id.number.plan);
  1832. ast_agi_send(fd, chan, "agi_callingtns: %d\n", ast_channel_dialed(chan)->transit_network_select);
  1833. ast_agi_send(fd, chan, "agi_dnid: %s\n", S_OR(ast_channel_dialed(chan)->number.str, "unknown"));
  1834. ast_agi_send(fd, chan, "agi_rdnis: %s\n",
  1835. S_COR(ast_channel_redirecting(chan)->from.number.valid, ast_channel_redirecting(chan)->from.number.str, "unknown"));
  1836. /* Context information */
  1837. ast_agi_send(fd, chan, "agi_context: %s\n", ast_channel_context(chan));
  1838. ast_agi_send(fd, chan, "agi_extension: %s\n", ast_channel_exten(chan));
  1839. ast_agi_send(fd, chan, "agi_priority: %d\n", ast_channel_priority(chan));
  1840. ast_agi_send(fd, chan, "agi_enhanced: %s\n", enhanced ? "1.0" : "0.0");
  1841. /* User information */
  1842. ast_agi_send(fd, chan, "agi_accountcode: %s\n", ast_channel_accountcode(chan) ? ast_channel_accountcode(chan) : "");
  1843. ast_agi_send(fd, chan, "agi_threadid: %ld\n", (long)pthread_self());
  1844. /* Send any parameters to the fastagi server that have been passed via the agi application */
  1845. /* Agi application paramaters take the form of: AGI(/path/to/example/script|${EXTEN}) */
  1846. for(count = 1; count < argc; count++)
  1847. ast_agi_send(fd, chan, "agi_arg_%d: %s\n", count, argv[count]);
  1848. /* End with empty return */
  1849. ast_agi_send(fd, chan, "\n");
  1850. }
  1851. static int handle_answer(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  1852. {
  1853. int res = 0;
  1854. /* Answer the channel */
  1855. if (ast_channel_state(chan) != AST_STATE_UP)
  1856. res = ast_answer(chan);
  1857. ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
  1858. return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
  1859. }
  1860. static int handle_asyncagi_break(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  1861. {
  1862. ast_agi_send(agi->fd, chan, "200 result=0\n");
  1863. return ASYNC_AGI_BREAK;
  1864. }
  1865. static int handle_waitfordigit(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  1866. {
  1867. int res, to;
  1868. if (argc != 4)
  1869. return RESULT_SHOWUSAGE;
  1870. if (sscanf(argv[3], "%30d", &to) != 1)
  1871. return RESULT_SHOWUSAGE;
  1872. res = ast_waitfordigit_full(chan, to, agi->audio, agi->ctrl);
  1873. ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
  1874. return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
  1875. }
  1876. static int handle_sendtext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  1877. {
  1878. int res;
  1879. if (argc != 3)
  1880. return RESULT_SHOWUSAGE;
  1881. /* At the moment, the parser (perhaps broken) returns with
  1882. the last argument PLUS the newline at the end of the input
  1883. buffer. This probably needs to be fixed, but I wont do that
  1884. because other stuff may break as a result. The right way
  1885. would probably be to strip off the trailing newline before
  1886. parsing, then here, add a newline at the end of the string
  1887. before sending it to ast_sendtext --DUDE */
  1888. res = ast_sendtext(chan, argv[2]);
  1889. ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
  1890. return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
  1891. }
  1892. static int handle_recvchar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  1893. {
  1894. int res;
  1895. if (argc != 3)
  1896. return RESULT_SHOWUSAGE;
  1897. res = ast_recvchar(chan,atoi(argv[2]));
  1898. if (res == 0) {
  1899. ast_agi_send(agi->fd, chan, "200 result=%d (timeout)\n", res);
  1900. return RESULT_SUCCESS;
  1901. }
  1902. if (res > 0) {
  1903. ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
  1904. return RESULT_SUCCESS;
  1905. }
  1906. ast_agi_send(agi->fd, chan, "200 result=%d (hangup)\n", res);
  1907. return RESULT_FAILURE;
  1908. }
  1909. static int handle_recvtext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  1910. {
  1911. char *buf;
  1912. if (argc != 3)
  1913. return RESULT_SHOWUSAGE;
  1914. buf = ast_recvtext(chan, atoi(argv[2]));
  1915. if (buf) {
  1916. ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", buf);
  1917. ast_free(buf);
  1918. } else {
  1919. ast_agi_send(agi->fd, chan, "200 result=-1\n");
  1920. }
  1921. return RESULT_SUCCESS;
  1922. }
  1923. static int handle_tddmode(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  1924. {
  1925. int res, x;
  1926. if (argc != 3)
  1927. return RESULT_SHOWUSAGE;
  1928. if (!strncasecmp(argv[2],"on",2)) {
  1929. x = 1;
  1930. } else {
  1931. x = 0;
  1932. }
  1933. if (!strncasecmp(argv[2],"mate",4)) {
  1934. x = 2;
  1935. }
  1936. if (!strncasecmp(argv[2],"tdd",3)) {
  1937. x = 1;
  1938. }
  1939. res = ast_channel_setoption(chan, AST_OPTION_TDD, &x, sizeof(char), 0);
  1940. if (res) {
  1941. /* Set channel option failed */
  1942. ast_agi_send(agi->fd, chan, "200 result=0\n");
  1943. } else {
  1944. ast_agi_send(agi->fd, chan, "200 result=1\n");
  1945. }
  1946. return RESULT_SUCCESS;
  1947. }
  1948. static int handle_sendimage(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  1949. {
  1950. int res;
  1951. if (argc != 3) {
  1952. return RESULT_SHOWUSAGE;
  1953. }
  1954. res = ast_send_image(chan, argv[2]);
  1955. if (!ast_check_hangup(chan)) {
  1956. res = 0;
  1957. }
  1958. ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
  1959. return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
  1960. }
  1961. static int handle_controlstreamfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  1962. {
  1963. int res = 0, skipms = 3000;
  1964. const char *fwd = "#", *rev = "*", *suspend = NULL, *stop = NULL; /* Default values */
  1965. char stopkeybuf[2];
  1966. long offsetms = 0;
  1967. char offsetbuf[20];
  1968. if (argc < 5 || argc > 10) {
  1969. return RESULT_SHOWUSAGE;
  1970. }
  1971. if (!ast_strlen_zero(argv[4])) {
  1972. stop = argv[4];
  1973. }
  1974. if ((argc > 5) && (sscanf(argv[5], "%30d", &skipms) != 1)) {
  1975. return RESULT_SHOWUSAGE;
  1976. }
  1977. if (argc > 6 && !ast_strlen_zero(argv[6])) {
  1978. fwd = argv[6];
  1979. }
  1980. if (argc > 7 && !ast_strlen_zero(argv[7])) {
  1981. rev = argv[7];
  1982. }
  1983. if (argc > 8 && !ast_strlen_zero(argv[8])) {
  1984. suspend = argv[8];
  1985. }
  1986. if (argc > 9 && (sscanf(argv[9], "%30ld", &offsetms) != 1)) {
  1987. return RESULT_SHOWUSAGE;
  1988. }
  1989. res = ast_control_streamfile(chan, argv[3], fwd, rev, stop, suspend, NULL, skipms, &offsetms);
  1990. /* If we stopped on one of our stop keys, return 0 */
  1991. if (res > 0 && stop && strchr(stop, res)) {
  1992. pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "USERSTOPPED");
  1993. snprintf(stopkeybuf, sizeof(stopkeybuf), "%c", res);
  1994. pbx_builtin_setvar_helper(chan, "CPLAYBACKSTOPKEY", stopkeybuf);
  1995. } else if (res > 0 && res == AST_CONTROL_STREAM_STOP) {
  1996. pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "REMOTESTOPPED");
  1997. res = 0;
  1998. } else {
  1999. if (res < 0) {
  2000. pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "ERROR");
  2001. } else {
  2002. pbx_builtin_setvar_helper(chan, "CPLAYBACKSTATUS", "SUCCESS");
  2003. }
  2004. }
  2005. snprintf(offsetbuf, sizeof(offsetbuf), "%ld", offsetms);
  2006. pbx_builtin_setvar_helper(chan, "CPLAYBACKOFFSET", offsetbuf);
  2007. ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, offsetms);
  2008. return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
  2009. }
  2010. static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2011. {
  2012. int res;
  2013. struct ast_filestream *fs, *vfs;
  2014. long sample_offset = 0, max_length;
  2015. const char *edigits = "";
  2016. if (argc < 4 || argc > 5) {
  2017. return RESULT_SHOWUSAGE;
  2018. }
  2019. if (argv[3]) {
  2020. edigits = argv[3];
  2021. }
  2022. if ((argc > 4) && (sscanf(argv[4], "%30ld", &sample_offset) != 1)) {
  2023. return RESULT_SHOWUSAGE;
  2024. }
  2025. if (!(fs = ast_openstream(chan, argv[2], ast_channel_language(chan)))) {
  2026. ast_agi_send(agi->fd, chan, "200 result=-1 endpos=%ld\n", sample_offset);
  2027. return RESULT_FAILURE;
  2028. }
  2029. if ((vfs = ast_openvstream(chan, argv[2], ast_channel_language(chan)))) {
  2030. ast_debug(1, "Ooh, found a video stream, too\n");
  2031. }
  2032. ast_verb(3, "Playing '%s' (escape_digits=%s) (sample_offset %ld)\n", argv[2], edigits, sample_offset);
  2033. ast_seekstream(fs, 0, SEEK_END);
  2034. max_length = ast_tellstream(fs);
  2035. ast_seekstream(fs, sample_offset, SEEK_SET);
  2036. res = ast_applystream(chan, fs);
  2037. if (vfs) {
  2038. ast_applystream(chan, vfs);
  2039. }
  2040. ast_playstream(fs);
  2041. if (vfs) {
  2042. ast_playstream(vfs);
  2043. }
  2044. res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
  2045. /* this is to check for if ast_waitstream closed the stream, we probably are at
  2046. * the end of the stream, return that amount, else check for the amount */
  2047. sample_offset = (ast_channel_stream(chan)) ? ast_tellstream(fs) : max_length;
  2048. ast_stopstream(chan);
  2049. if (res == 1) {
  2050. /* Stop this command, don't print a result line, as there is a new command */
  2051. return RESULT_SUCCESS;
  2052. }
  2053. ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, sample_offset);
  2054. pbx_builtin_setvar_helper(chan, "PLAYBACKSTATUS", res ? "FAILED" : "SUCCESS");
  2055. return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
  2056. }
  2057. /*! \brief get option - really similar to the handle_streamfile, but with a timeout */
  2058. static int handle_getoption(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2059. {
  2060. int res;
  2061. struct ast_filestream *fs, *vfs;
  2062. long sample_offset = 0, max_length;
  2063. int timeout = 0;
  2064. const char *edigits = "";
  2065. if ( argc < 4 || argc > 5 )
  2066. return RESULT_SHOWUSAGE;
  2067. if ( argv[3] )
  2068. edigits = argv[3];
  2069. if ( argc == 5 )
  2070. timeout = atoi(argv[4]);
  2071. else if (ast_channel_pbx(chan)->dtimeoutms) {
  2072. /* by default dtimeout is set to 5sec */
  2073. timeout = ast_channel_pbx(chan)->dtimeoutms; /* in msec */
  2074. }
  2075. if (!(fs = ast_openstream(chan, argv[2], ast_channel_language(chan)))) {
  2076. ast_agi_send(agi->fd, chan, "200 result=-1 endpos=%ld\n", sample_offset);
  2077. ast_log(LOG_WARNING, "Unable to open %s\n", argv[2]);
  2078. return RESULT_FAILURE;
  2079. }
  2080. if ((vfs = ast_openvstream(chan, argv[2], ast_channel_language(chan))))
  2081. ast_debug(1, "Ooh, found a video stream, too\n");
  2082. ast_verb(3, "Playing '%s' (escape_digits=%s) (timeout %d)\n", argv[2], edigits, timeout);
  2083. ast_seekstream(fs, 0, SEEK_END);
  2084. max_length = ast_tellstream(fs);
  2085. ast_seekstream(fs, sample_offset, SEEK_SET);
  2086. res = ast_applystream(chan, fs);
  2087. if (vfs)
  2088. ast_applystream(chan, vfs);
  2089. ast_playstream(fs);
  2090. if (vfs)
  2091. ast_playstream(vfs);
  2092. res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
  2093. /* this is to check for if ast_waitstream closed the stream, we probably are at
  2094. * the end of the stream, return that amount, else check for the amount */
  2095. sample_offset = (ast_channel_stream(chan))?ast_tellstream(fs):max_length;
  2096. ast_stopstream(chan);
  2097. if (res == 1) {
  2098. /* Stop this command, don't print a result line, as there is a new command */
  2099. return RESULT_SUCCESS;
  2100. }
  2101. /* If the user didnt press a key, wait for digitTimeout*/
  2102. if (res == 0 ) {
  2103. res = ast_waitfordigit_full(chan, timeout, agi->audio, agi->ctrl);
  2104. /* Make sure the new result is in the escape digits of the GET OPTION */
  2105. if ( !strchr(edigits,res) )
  2106. res=0;
  2107. }
  2108. ast_agi_send(agi->fd, chan, "200 result=%d endpos=%ld\n", res, sample_offset);
  2109. return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
  2110. }
  2111. /*! \brief Say number in various language syntaxes */
  2112. /* While waiting, we're sending a NULL. */
  2113. static int handle_saynumber(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2114. {
  2115. int res, num;
  2116. if (argc < 4 || argc > 5)
  2117. return RESULT_SHOWUSAGE;
  2118. if (sscanf(argv[2], "%30d", &num) != 1)
  2119. return RESULT_SHOWUSAGE;
  2120. res = ast_say_number_full(chan, num, argv[3], ast_channel_language(chan), argc > 4 ? argv[4] : NULL, agi->audio, agi->ctrl);
  2121. if (res == 1)
  2122. return RESULT_SUCCESS;
  2123. ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
  2124. return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
  2125. }
  2126. static int handle_saydigits(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2127. {
  2128. int res, num;
  2129. if (argc != 4)
  2130. return RESULT_SHOWUSAGE;
  2131. if (sscanf(argv[2], "%30d", &num) != 1)
  2132. return RESULT_SHOWUSAGE;
  2133. res = ast_say_digit_str_full(chan, argv[2], argv[3], ast_channel_language(chan), agi->audio, agi->ctrl);
  2134. if (res == 1) /* New command */
  2135. return RESULT_SUCCESS;
  2136. ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
  2137. return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
  2138. }
  2139. static int handle_sayalpha(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2140. {
  2141. int res;
  2142. int sensitivity = AST_SAY_CASE_NONE;
  2143. if (argc < 4 || argc > 5) {
  2144. return RESULT_SHOWUSAGE;
  2145. }
  2146. if (argc > 4) {
  2147. switch (argv[4][0]) {
  2148. case 'a':
  2149. case 'A':
  2150. sensitivity = AST_SAY_CASE_ALL;
  2151. break;
  2152. case 'l':
  2153. case 'L':
  2154. sensitivity = AST_SAY_CASE_LOWER;
  2155. break;
  2156. case 'n':
  2157. case 'N':
  2158. sensitivity = AST_SAY_CASE_NONE;
  2159. break;
  2160. case 'u':
  2161. case 'U':
  2162. sensitivity = AST_SAY_CASE_UPPER;
  2163. break;
  2164. case '\0':
  2165. break;
  2166. default:
  2167. return RESULT_SHOWUSAGE;
  2168. }
  2169. }
  2170. res = ast_say_character_str_full(chan, argv[2], argv[3], ast_channel_language(chan), sensitivity, agi->audio, agi->ctrl);
  2171. if (res == 1) /* New command */
  2172. return RESULT_SUCCESS;
  2173. ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
  2174. return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
  2175. }
  2176. static int handle_saydate(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2177. {
  2178. int res, num;
  2179. if (argc != 4)
  2180. return RESULT_SHOWUSAGE;
  2181. if (sscanf(argv[2], "%30d", &num) != 1)
  2182. return RESULT_SHOWUSAGE;
  2183. res = ast_say_date(chan, num, argv[3], ast_channel_language(chan));
  2184. if (res == 1)
  2185. return RESULT_SUCCESS;
  2186. ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
  2187. return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
  2188. }
  2189. static int handle_saytime(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2190. {
  2191. int res, num;
  2192. if (argc != 4)
  2193. return RESULT_SHOWUSAGE;
  2194. if (sscanf(argv[2], "%30d", &num) != 1)
  2195. return RESULT_SHOWUSAGE;
  2196. res = ast_say_time(chan, num, argv[3], ast_channel_language(chan));
  2197. if (res == 1)
  2198. return RESULT_SUCCESS;
  2199. ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
  2200. return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
  2201. }
  2202. static int handle_saydatetime(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2203. {
  2204. int res = 0;
  2205. time_t unixtime;
  2206. const char *format, *zone = NULL;
  2207. if (argc < 4)
  2208. return RESULT_SHOWUSAGE;
  2209. if (argc > 4) {
  2210. format = argv[4];
  2211. } else {
  2212. /* XXX this doesn't belong here, but in the 'say' module */
  2213. if (!strcasecmp(ast_channel_language(chan), "de")) {
  2214. format = "A dBY HMS";
  2215. } else {
  2216. format = "ABdY 'digits/at' IMp";
  2217. }
  2218. }
  2219. if (argc > 5 && !ast_strlen_zero(argv[5]))
  2220. zone = argv[5];
  2221. if (ast_get_time_t(argv[2], &unixtime, 0, NULL))
  2222. return RESULT_SHOWUSAGE;
  2223. res = ast_say_date_with_format(chan, unixtime, argv[3], ast_channel_language(chan), format, zone);
  2224. if (res == 1)
  2225. return RESULT_SUCCESS;
  2226. ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
  2227. return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
  2228. }
  2229. static int handle_sayphonetic(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2230. {
  2231. int res;
  2232. if (argc != 4)
  2233. return RESULT_SHOWUSAGE;
  2234. res = ast_say_phonetic_str_full(chan, argv[2], argv[3], ast_channel_language(chan), agi->audio, agi->ctrl);
  2235. if (res == 1) /* New command */
  2236. return RESULT_SUCCESS;
  2237. ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
  2238. return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
  2239. }
  2240. static int handle_getdata(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2241. {
  2242. int res, max, timeout;
  2243. char data[1024];
  2244. if (argc < 3)
  2245. return RESULT_SHOWUSAGE;
  2246. if (argc >= 4)
  2247. timeout = atoi(argv[3]);
  2248. else
  2249. timeout = 0;
  2250. if (argc >= 5)
  2251. max = atoi(argv[4]);
  2252. else
  2253. max = 1024;
  2254. res = ast_app_getdata_full(chan, argv[2], data, max, timeout, agi->audio, agi->ctrl);
  2255. if (res == 2) /* New command */
  2256. return RESULT_SUCCESS;
  2257. else if (res == 1)
  2258. ast_agi_send(agi->fd, chan, "200 result=%s (timeout)\n", data);
  2259. else if (res < 0 )
  2260. ast_agi_send(agi->fd, chan, "200 result=-1\n");
  2261. else
  2262. ast_agi_send(agi->fd, chan, "200 result=%s\n", data);
  2263. return RESULT_SUCCESS;
  2264. }
  2265. static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2266. {
  2267. if (argc != 3)
  2268. return RESULT_SHOWUSAGE;
  2269. ast_channel_context_set(chan, argv[2]);
  2270. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2271. return RESULT_SUCCESS;
  2272. }
  2273. static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2274. {
  2275. if (argc != 3)
  2276. return RESULT_SHOWUSAGE;
  2277. ast_channel_exten_set(chan, argv[2]);
  2278. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2279. return RESULT_SUCCESS;
  2280. }
  2281. static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2282. {
  2283. int pri;
  2284. if (argc != 3)
  2285. return RESULT_SHOWUSAGE;
  2286. if (sscanf(argv[2], "%30d", &pri) != 1) {
  2287. pri = ast_findlabel_extension(chan, ast_channel_context(chan), ast_channel_exten(chan), argv[2],
  2288. S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL));
  2289. if (pri < 1)
  2290. return RESULT_SHOWUSAGE;
  2291. }
  2292. ast_explicit_goto(chan, NULL, NULL, pri);
  2293. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2294. return RESULT_SUCCESS;
  2295. }
  2296. static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2297. {
  2298. struct ast_filestream *fs;
  2299. struct ast_frame *f;
  2300. struct timeval start;
  2301. long sample_offset = 0;
  2302. int res = 0;
  2303. int ms;
  2304. struct ast_dsp *sildet=NULL; /* silence detector dsp */
  2305. int totalsilence = 0;
  2306. int dspsilence = 0;
  2307. int silence = 0; /* amount of silence to allow */
  2308. int gotsilence = 0; /* did we timeout for silence? */
  2309. char *silencestr = NULL;
  2310. RAII_VAR(struct ast_format *, rfmt, NULL, ao2_cleanup);
  2311. /* XXX EAGI FIXME XXX */
  2312. if (argc < 6)
  2313. return RESULT_SHOWUSAGE;
  2314. if (sscanf(argv[5], "%30d", &ms) != 1)
  2315. return RESULT_SHOWUSAGE;
  2316. if (argc > 6)
  2317. silencestr = strchr(argv[6],'s');
  2318. if ((argc > 7) && (!silencestr))
  2319. silencestr = strchr(argv[7],'s');
  2320. if ((argc > 8) && (!silencestr))
  2321. silencestr = strchr(argv[8],'s');
  2322. if (silencestr) {
  2323. if (strlen(silencestr) > 2) {
  2324. if ((silencestr[0] == 's') && (silencestr[1] == '=')) {
  2325. silencestr++;
  2326. silencestr++;
  2327. if (silencestr)
  2328. silence = atoi(silencestr);
  2329. if (silence > 0)
  2330. silence *= 1000;
  2331. }
  2332. }
  2333. }
  2334. if (silence > 0) {
  2335. rfmt = ao2_bump(ast_channel_readformat(chan));
  2336. res = ast_set_read_format(chan, ast_format_slin);
  2337. if (res < 0) {
  2338. ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
  2339. ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
  2340. return RESULT_FAILURE;
  2341. }
  2342. sildet = ast_dsp_new();
  2343. if (!sildet) {
  2344. ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
  2345. ast_agi_send(agi->fd, chan, "200 result=-1\n");
  2346. return RESULT_FAILURE;
  2347. }
  2348. ast_dsp_set_threshold(sildet, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE));
  2349. }
  2350. /* backward compatibility, if no offset given, arg[6] would have been
  2351. * caught below and taken to be a beep, else if it is a digit then it is a
  2352. * offset */
  2353. if ((argc >6) && (sscanf(argv[6], "%30ld", &sample_offset) != 1) && (!strchr(argv[6], '=')))
  2354. res = ast_streamfile(chan, "beep", ast_channel_language(chan));
  2355. if ((argc > 7) && (!strchr(argv[7], '=')))
  2356. res = ast_streamfile(chan, "beep", ast_channel_language(chan));
  2357. if (!res)
  2358. res = ast_waitstream(chan, argv[4]);
  2359. if (res) {
  2360. ast_agi_send(agi->fd, chan, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
  2361. } else {
  2362. fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY | (sample_offset ? O_APPEND : 0), 0, AST_FILE_MODE);
  2363. if (!fs) {
  2364. res = -1;
  2365. ast_agi_send(agi->fd, chan, "200 result=%d (writefile)\n", res);
  2366. if (sildet)
  2367. ast_dsp_free(sildet);
  2368. return RESULT_FAILURE;
  2369. }
  2370. /* Request a video update */
  2371. ast_indicate(chan, AST_CONTROL_VIDUPDATE);
  2372. ast_channel_stream_set(chan, fs);
  2373. ast_applystream(chan,fs);
  2374. /* really should have checks */
  2375. ast_seekstream(fs, sample_offset, SEEK_SET);
  2376. ast_truncstream(fs);
  2377. start = ast_tvnow();
  2378. while ((ms < 0) || ast_tvdiff_ms(ast_tvnow(), start) < ms) {
  2379. res = ast_waitfor(chan, ms - ast_tvdiff_ms(ast_tvnow(), start));
  2380. if (res < 0) {
  2381. ast_closestream(fs);
  2382. ast_agi_send(agi->fd, chan, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
  2383. if (sildet)
  2384. ast_dsp_free(sildet);
  2385. return RESULT_FAILURE;
  2386. }
  2387. f = ast_read(chan);
  2388. if (!f) {
  2389. ast_agi_send(agi->fd, chan, "200 result=%d (hangup) endpos=%ld\n", -1, sample_offset);
  2390. ast_closestream(fs);
  2391. if (sildet)
  2392. ast_dsp_free(sildet);
  2393. return RESULT_FAILURE;
  2394. }
  2395. switch(f->frametype) {
  2396. case AST_FRAME_DTMF:
  2397. if (strchr(argv[4], f->subclass.integer)) {
  2398. /* This is an interrupting chracter, so rewind to chop off any small
  2399. amount of DTMF that may have been recorded
  2400. */
  2401. ast_stream_rewind(fs, 200);
  2402. ast_truncstream(fs);
  2403. sample_offset = ast_tellstream(fs);
  2404. ast_agi_send(agi->fd, chan, "200 result=%d (dtmf) endpos=%ld\n", f->subclass.integer, sample_offset);
  2405. ast_closestream(fs);
  2406. ast_frfree(f);
  2407. if (sildet)
  2408. ast_dsp_free(sildet);
  2409. return RESULT_SUCCESS;
  2410. }
  2411. break;
  2412. case AST_FRAME_VOICE:
  2413. ast_writestream(fs, f);
  2414. /* this is a safe place to check progress since we know that fs
  2415. * is valid after a write, and it will then have our current
  2416. * location */
  2417. sample_offset = ast_tellstream(fs);
  2418. if (silence > 0) {
  2419. dspsilence = 0;
  2420. ast_dsp_silence(sildet, f, &dspsilence);
  2421. if (dspsilence) {
  2422. totalsilence = dspsilence;
  2423. } else {
  2424. totalsilence = 0;
  2425. }
  2426. if (totalsilence > silence) {
  2427. /* Ended happily with silence */
  2428. gotsilence = 1;
  2429. break;
  2430. }
  2431. }
  2432. break;
  2433. case AST_FRAME_VIDEO:
  2434. ast_writestream(fs, f);
  2435. default:
  2436. /* Ignore all other frames */
  2437. break;
  2438. }
  2439. ast_frfree(f);
  2440. if (gotsilence)
  2441. break;
  2442. }
  2443. if (gotsilence) {
  2444. ast_stream_rewind(fs, silence-1000);
  2445. ast_truncstream(fs);
  2446. sample_offset = ast_tellstream(fs);
  2447. }
  2448. ast_agi_send(agi->fd, chan, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
  2449. ast_closestream(fs);
  2450. }
  2451. if (silence > 0) {
  2452. res = ast_set_read_format(chan, rfmt);
  2453. if (res)
  2454. ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", ast_channel_name(chan));
  2455. ast_dsp_free(sildet);
  2456. }
  2457. return RESULT_SUCCESS;
  2458. }
  2459. static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2460. {
  2461. double timeout;
  2462. struct timeval whentohangup = { 0, 0 };
  2463. if (argc != 3)
  2464. return RESULT_SHOWUSAGE;
  2465. if (sscanf(argv[2], "%30lf", &timeout) != 1)
  2466. return RESULT_SHOWUSAGE;
  2467. if (timeout < 0)
  2468. timeout = 0;
  2469. if (timeout) {
  2470. whentohangup.tv_sec = timeout;
  2471. whentohangup.tv_usec = (timeout - whentohangup.tv_sec) * 1000000.0;
  2472. }
  2473. ast_channel_lock(chan);
  2474. ast_channel_setwhentohangup_tv(chan, whentohangup);
  2475. ast_channel_unlock(chan);
  2476. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2477. return RESULT_SUCCESS;
  2478. }
  2479. static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2480. {
  2481. struct ast_channel *c;
  2482. if (argc == 1) {
  2483. /* no argument: hangup the current channel */
  2484. ast_set_hangupsource(chan, "dialplan/agi", 0);
  2485. ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
  2486. ast_agi_send(agi->fd, chan, "200 result=1\n");
  2487. return RESULT_SUCCESS;
  2488. } else if (argc == 2) {
  2489. /* one argument: look for info on the specified channel */
  2490. if ((c = ast_channel_get_by_name(argv[1]))) {
  2491. /* we have a matching channel */
  2492. ast_set_hangupsource(c, "dialplan/agi", 0);
  2493. ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
  2494. c = ast_channel_unref(c);
  2495. ast_agi_send(agi->fd, chan, "200 result=1\n");
  2496. return RESULT_SUCCESS;
  2497. }
  2498. /* if we get this far no channel name matched the argument given */
  2499. ast_agi_send(agi->fd, chan, "200 result=-1\n");
  2500. return RESULT_SUCCESS;
  2501. } else {
  2502. return RESULT_SHOWUSAGE;
  2503. }
  2504. }
  2505. static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2506. {
  2507. int res, workaround;
  2508. struct ast_app *app_to_exec;
  2509. if (argc < 2)
  2510. return RESULT_SHOWUSAGE;
  2511. ast_verb(3, "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argc >= 3 ? argv[2] : "");
  2512. if ((app_to_exec = pbx_findapp(argv[1]))) {
  2513. if (!(workaround = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_WORKAROUNDS))) {
  2514. ast_set_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_WORKAROUNDS);
  2515. }
  2516. res = pbx_exec(chan, app_to_exec, argc == 2 ? "" : argv[2]);
  2517. if (!workaround) {
  2518. ast_clear_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_WORKAROUNDS);
  2519. }
  2520. } else {
  2521. ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
  2522. res = -2;
  2523. }
  2524. ast_agi_send(agi->fd, chan, "200 result=%d\n", res);
  2525. /* Even though this is wrong, users are depending upon this result. */
  2526. return res;
  2527. }
  2528. static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2529. {
  2530. char tmp[256]="";
  2531. char *l = NULL, *n = NULL;
  2532. if (argv[2]) {
  2533. ast_copy_string(tmp, argv[2], sizeof(tmp));
  2534. ast_callerid_parse(tmp, &n, &l);
  2535. if (l)
  2536. ast_shrink_phone_number(l);
  2537. else
  2538. l = "";
  2539. if (!n)
  2540. n = "";
  2541. ast_set_callerid(chan, l, n, NULL);
  2542. }
  2543. ast_agi_send(agi->fd, chan, "200 result=1\n");
  2544. return RESULT_SUCCESS;
  2545. }
  2546. static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2547. {
  2548. if (argc == 2) {
  2549. /* no argument: supply info on the current channel */
  2550. ast_agi_send(agi->fd, chan, "200 result=%u\n", ast_channel_state(chan));
  2551. return RESULT_SUCCESS;
  2552. } else if (argc == 3) {
  2553. RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
  2554. /* one argument: look for info on the specified channel */
  2555. if ((msg = stasis_cache_get(ast_channel_cache_by_name(), ast_channel_snapshot_type(), argv[2]))) {
  2556. struct ast_channel_snapshot *snapshot = stasis_message_data(msg);
  2557. ast_agi_send(agi->fd, chan, "200 result=%u\n", snapshot->state);
  2558. return RESULT_SUCCESS;
  2559. }
  2560. /* if we get this far no channel name matched the argument given */
  2561. ast_agi_send(agi->fd, chan, "200 result=-1\n");
  2562. return RESULT_SUCCESS;
  2563. } else {
  2564. return RESULT_SHOWUSAGE;
  2565. }
  2566. }
  2567. static int handle_setvariable(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2568. {
  2569. if (argv[3])
  2570. pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
  2571. ast_agi_send(agi->fd, chan, "200 result=1\n");
  2572. return RESULT_SUCCESS;
  2573. }
  2574. static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2575. {
  2576. char *ret;
  2577. char tempstr[1024] = "";
  2578. if (argc != 3)
  2579. return RESULT_SHOWUSAGE;
  2580. /* check if we want to execute an ast_custom_function */
  2581. if (!ast_strlen_zero(argv[2]) && (argv[2][strlen(argv[2]) - 1] == ')')) {
  2582. ret = ast_func_read(chan, argv[2], tempstr, sizeof(tempstr)) ? NULL : tempstr;
  2583. } else {
  2584. pbx_retrieve_variable(chan, argv[2], &ret, tempstr, sizeof(tempstr), NULL);
  2585. }
  2586. if (ret)
  2587. ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ret);
  2588. else
  2589. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2590. return RESULT_SUCCESS;
  2591. }
  2592. static int handle_getvariablefull(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2593. {
  2594. struct ast_channel *chan2 = NULL;
  2595. if (argc != 4 && argc != 5) {
  2596. return RESULT_SHOWUSAGE;
  2597. }
  2598. if (argc == 5) {
  2599. chan2 = ast_channel_get_by_name(argv[4]);
  2600. } else {
  2601. chan2 = ast_channel_ref(chan);
  2602. }
  2603. if (chan2) {
  2604. struct ast_str *str = ast_str_create(16);
  2605. if (!str) {
  2606. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2607. return RESULT_SUCCESS;
  2608. }
  2609. ast_str_substitute_variables(&str, 0, chan2, argv[3]);
  2610. ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ast_str_buffer(str));
  2611. ast_free(str);
  2612. } else {
  2613. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2614. }
  2615. if (chan2) {
  2616. chan2 = ast_channel_unref(chan2);
  2617. }
  2618. return RESULT_SUCCESS;
  2619. }
  2620. static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2621. {
  2622. int level = 0;
  2623. if (argc < 2)
  2624. return RESULT_SHOWUSAGE;
  2625. if (argv[2])
  2626. sscanf(argv[2], "%30d", &level);
  2627. ast_verb(level, "%s: %s\n", ast_channel_data(chan), argv[1]);
  2628. ast_agi_send(agi->fd, chan, "200 result=1\n");
  2629. return RESULT_SUCCESS;
  2630. }
  2631. static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2632. {
  2633. int res;
  2634. struct ast_str *buf;
  2635. if (argc != 4)
  2636. return RESULT_SHOWUSAGE;
  2637. if (!(buf = ast_str_create(16))) {
  2638. ast_agi_send(agi->fd, chan, "200 result=-1\n");
  2639. return RESULT_SUCCESS;
  2640. }
  2641. do {
  2642. res = ast_db_get(argv[2], argv[3], ast_str_buffer(buf), ast_str_size(buf));
  2643. ast_str_update(buf);
  2644. if (ast_str_strlen(buf) < ast_str_size(buf) - 1) {
  2645. break;
  2646. }
  2647. if (ast_str_make_space(&buf, ast_str_size(buf) * 2)) {
  2648. break;
  2649. }
  2650. } while (1);
  2651. if (res)
  2652. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2653. else
  2654. ast_agi_send(agi->fd, chan, "200 result=1 (%s)\n", ast_str_buffer(buf));
  2655. ast_free(buf);
  2656. return RESULT_SUCCESS;
  2657. }
  2658. static int handle_dbput(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2659. {
  2660. int res;
  2661. if (argc != 5)
  2662. return RESULT_SHOWUSAGE;
  2663. res = ast_db_put(argv[2], argv[3], argv[4]);
  2664. ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
  2665. return RESULT_SUCCESS;
  2666. }
  2667. static int handle_dbdel(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2668. {
  2669. int res;
  2670. if (argc != 4)
  2671. return RESULT_SHOWUSAGE;
  2672. res = ast_db_del(argv[2], argv[3]);
  2673. ast_agi_send(agi->fd, chan, "200 result=%c\n", res ? '0' : '1');
  2674. return RESULT_SUCCESS;
  2675. }
  2676. static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2677. {
  2678. int num_deleted;
  2679. if ((argc < 3) || (argc > 4)) {
  2680. return RESULT_SHOWUSAGE;
  2681. }
  2682. if (argc == 4) {
  2683. num_deleted = ast_db_deltree(argv[2], argv[3]);
  2684. } else {
  2685. num_deleted = ast_db_deltree(argv[2], NULL);
  2686. }
  2687. ast_agi_send(agi->fd, chan, "200 result=%c\n", num_deleted > 0 ? '0' : '1');
  2688. return RESULT_SUCCESS;
  2689. }
  2690. static char *handle_cli_agi_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2691. {
  2692. switch (cmd) {
  2693. case CLI_INIT:
  2694. e->command = "agi set debug [on|off]";
  2695. e->usage =
  2696. "Usage: agi set debug [on|off]\n"
  2697. " Enables/disables dumping of AGI transactions for\n"
  2698. " debugging purposes.\n";
  2699. return NULL;
  2700. case CLI_GENERATE:
  2701. return NULL;
  2702. }
  2703. if (a->argc != e->args)
  2704. return CLI_SHOWUSAGE;
  2705. if (strncasecmp(a->argv[3], "off", 3) == 0) {
  2706. agidebug = 0;
  2707. } else if (strncasecmp(a->argv[3], "on", 2) == 0) {
  2708. agidebug = 1;
  2709. } else {
  2710. return CLI_SHOWUSAGE;
  2711. }
  2712. ast_cli(a->fd, "AGI Debugging %sabled\n", agidebug ? "En" : "Dis");
  2713. return CLI_SUCCESS;
  2714. }
  2715. static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, const char * const argv[])
  2716. {
  2717. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2718. return RESULT_SUCCESS;
  2719. }
  2720. static int handle_setmusic(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2721. {
  2722. if (argc < 3) {
  2723. return RESULT_SHOWUSAGE;
  2724. }
  2725. if (!strncasecmp(argv[2], "on", 2))
  2726. ast_moh_start(chan, argc > 3 ? argv[3] : NULL, NULL);
  2727. else if (!strncasecmp(argv[2], "off", 3))
  2728. ast_moh_stop(chan);
  2729. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2730. return RESULT_SUCCESS;
  2731. }
  2732. static int handle_speechcreate(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2733. {
  2734. struct ast_format_cap *cap;
  2735. /* If a structure already exists, return an error */
  2736. if (agi->speech) {
  2737. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2738. return RESULT_SUCCESS;
  2739. }
  2740. if (!(cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
  2741. return RESULT_FAILURE;
  2742. }
  2743. ast_format_cap_append(cap, ast_format_slin, 0);
  2744. if ((agi->speech = ast_speech_new(argv[2], cap))) {
  2745. ast_agi_send(agi->fd, chan, "200 result=1\n");
  2746. } else {
  2747. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2748. }
  2749. ao2_ref(cap, -1);
  2750. return RESULT_SUCCESS;
  2751. }
  2752. static int handle_speechset(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2753. {
  2754. /* Check for minimum arguments */
  2755. if (argc != 4)
  2756. return RESULT_SHOWUSAGE;
  2757. /* Check to make sure speech structure exists */
  2758. if (!agi->speech) {
  2759. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2760. return RESULT_SUCCESS;
  2761. }
  2762. ast_speech_change(agi->speech, argv[2], argv[3]);
  2763. ast_agi_send(agi->fd, chan, "200 result=1\n");
  2764. return RESULT_SUCCESS;
  2765. }
  2766. static int handle_speechdestroy(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2767. {
  2768. if (agi->speech) {
  2769. ast_speech_destroy(agi->speech);
  2770. agi->speech = NULL;
  2771. ast_agi_send(agi->fd, chan, "200 result=1\n");
  2772. } else {
  2773. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2774. }
  2775. return RESULT_SUCCESS;
  2776. }
  2777. static int handle_speechloadgrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2778. {
  2779. if (argc != 5)
  2780. return RESULT_SHOWUSAGE;
  2781. if (!agi->speech) {
  2782. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2783. return RESULT_SUCCESS;
  2784. }
  2785. if (ast_speech_grammar_load(agi->speech, argv[3], argv[4]))
  2786. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2787. else
  2788. ast_agi_send(agi->fd, chan, "200 result=1\n");
  2789. return RESULT_SUCCESS;
  2790. }
  2791. static int handle_speechunloadgrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2792. {
  2793. if (argc != 4)
  2794. return RESULT_SHOWUSAGE;
  2795. if (!agi->speech) {
  2796. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2797. return RESULT_SUCCESS;
  2798. }
  2799. if (ast_speech_grammar_unload(agi->speech, argv[3]))
  2800. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2801. else
  2802. ast_agi_send(agi->fd, chan, "200 result=1\n");
  2803. return RESULT_SUCCESS;
  2804. }
  2805. static int handle_speechactivategrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2806. {
  2807. if (argc != 4)
  2808. return RESULT_SHOWUSAGE;
  2809. if (!agi->speech) {
  2810. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2811. return RESULT_SUCCESS;
  2812. }
  2813. if (ast_speech_grammar_activate(agi->speech, argv[3]))
  2814. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2815. else
  2816. ast_agi_send(agi->fd, chan, "200 result=1\n");
  2817. return RESULT_SUCCESS;
  2818. }
  2819. static int handle_speechdeactivategrammar(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2820. {
  2821. if (argc != 4)
  2822. return RESULT_SHOWUSAGE;
  2823. if (!agi->speech) {
  2824. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2825. return RESULT_SUCCESS;
  2826. }
  2827. if (ast_speech_grammar_deactivate(agi->speech, argv[3]))
  2828. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2829. else
  2830. ast_agi_send(agi->fd, chan, "200 result=1\n");
  2831. return RESULT_SUCCESS;
  2832. }
  2833. static int speech_streamfile(struct ast_channel *chan, const char *filename, const char *preflang, int offset)
  2834. {
  2835. struct ast_filestream *fs = NULL;
  2836. if (!(fs = ast_openstream(chan, filename, preflang)))
  2837. return -1;
  2838. if (offset)
  2839. ast_seekstream(fs, offset, SEEK_SET);
  2840. if (ast_applystream(chan, fs))
  2841. return -1;
  2842. if (ast_playstream(fs))
  2843. return -1;
  2844. return 0;
  2845. }
  2846. static int handle_speechrecognize(struct ast_channel *chan, AGI *agi, int argc, const char * const argv[])
  2847. {
  2848. struct ast_speech *speech = agi->speech;
  2849. const char *prompt;
  2850. char dtmf = 0, tmp[4096] = "", *buf = tmp;
  2851. int timeout = 0, offset = 0, res = 0, i = 0;
  2852. long current_offset = 0;
  2853. const char *reason = NULL;
  2854. struct ast_frame *fr = NULL;
  2855. struct ast_speech_result *result = NULL;
  2856. size_t left = sizeof(tmp);
  2857. time_t start = 0, current;
  2858. if (argc < 4)
  2859. return RESULT_SHOWUSAGE;
  2860. if (!speech) {
  2861. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2862. return RESULT_SUCCESS;
  2863. }
  2864. prompt = argv[2];
  2865. timeout = atoi(argv[3]);
  2866. /* If offset is specified then convert from text to integer */
  2867. if (argc == 5)
  2868. offset = atoi(argv[4]);
  2869. /* We want frames coming in signed linear */
  2870. if (ast_set_read_format(chan, ast_format_slin)) {
  2871. ast_agi_send(agi->fd, chan, "200 result=0\n");
  2872. return RESULT_SUCCESS;
  2873. }
  2874. /* Setup speech structure */
  2875. if (speech->state == AST_SPEECH_STATE_NOT_READY || speech->state == AST_SPEECH_STATE_DONE) {
  2876. ast_speech_change_state(speech, AST_SPEECH_STATE_NOT_READY);
  2877. ast_speech_start(speech);
  2878. }
  2879. /* Start playing prompt */
  2880. speech_streamfile(chan, prompt, ast_channel_language(chan), offset);
  2881. /* Go into loop reading in frames, passing to speech thingy, checking for hangup, all that jazz */
  2882. while (ast_strlen_zero(reason)) {
  2883. /* Run scheduled items */
  2884. ast_sched_runq(ast_channel_sched(chan));
  2885. /* See maximum time of waiting */
  2886. if ((res = ast_sched_wait(ast_channel_sched(chan))) < 0)
  2887. res = 1000;
  2888. /* Wait for frame */
  2889. if (ast_waitfor(chan, res) > 0) {
  2890. if (!(fr = ast_read(chan))) {
  2891. reason = "hangup";
  2892. break;
  2893. }
  2894. }
  2895. /* Perform timeout check */
  2896. if ((timeout > 0) && (start > 0)) {
  2897. time(&current);
  2898. if ((current - start) >= timeout) {
  2899. reason = "timeout";
  2900. if (fr)
  2901. ast_frfree(fr);
  2902. break;
  2903. }
  2904. }
  2905. /* Check the speech structure for any changes */
  2906. ast_mutex_lock(&speech->lock);
  2907. /* See if we need to quiet the audio stream playback */
  2908. if (ast_test_flag(speech, AST_SPEECH_QUIET) && ast_channel_stream(chan)) {
  2909. current_offset = ast_tellstream(ast_channel_stream(chan));
  2910. ast_stopstream(chan);
  2911. ast_clear_flag(speech, AST_SPEECH_QUIET);
  2912. }
  2913. /* Check each state */
  2914. switch (speech->state) {
  2915. case AST_SPEECH_STATE_READY:
  2916. /* If the stream is done, start timeout calculation */
  2917. if ((timeout > 0) && start == 0 && ((!ast_channel_stream(chan)) || (ast_channel_streamid(chan) == -1 && ast_channel_timingfunc(chan) == NULL))) {
  2918. ast_stopstream(chan);
  2919. time(&start);
  2920. }
  2921. /* Write audio frame data into speech engine if possible */
  2922. if (fr && fr->frametype == AST_FRAME_VOICE)
  2923. ast_speech_write(speech, fr->data.ptr, fr->datalen);
  2924. break;
  2925. case AST_SPEECH_STATE_WAIT:
  2926. /* Cue waiting sound if not already playing */
  2927. if ((!ast_channel_stream(chan)) || (ast_channel_streamid(chan) == -1 && ast_channel_timingfunc(chan) == NULL)) {
  2928. ast_stopstream(chan);
  2929. /* If a processing sound exists, or is not none - play it */
  2930. if (!ast_strlen_zero(speech->processing_sound) && strcasecmp(speech->processing_sound, "none"))
  2931. speech_streamfile(chan, speech->processing_sound, ast_channel_language(chan), 0);
  2932. }
  2933. break;
  2934. case AST_SPEECH_STATE_DONE:
  2935. /* Get the results */
  2936. speech->results = ast_speech_results_get(speech);
  2937. /* Change state to not ready */
  2938. ast_speech_change_state(speech, AST_SPEECH_STATE_NOT_READY);
  2939. reason = "speech";
  2940. break;
  2941. default:
  2942. break;
  2943. }
  2944. ast_mutex_unlock(&speech->lock);
  2945. /* Check frame for DTMF or hangup */
  2946. if (fr) {
  2947. if (fr->frametype == AST_FRAME_DTMF) {
  2948. reason = "dtmf";
  2949. dtmf = fr->subclass.integer;
  2950. } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass.integer == AST_CONTROL_HANGUP) {
  2951. reason = "hangup";
  2952. }
  2953. ast_frfree(fr);
  2954. }
  2955. }
  2956. if (!strcasecmp(reason, "speech")) {
  2957. /* Build string containing speech results */
  2958. for (result = speech->results; result; result = AST_LIST_NEXT(result, list)) {
  2959. /* Build result string */
  2960. ast_build_string(&buf, &left, "%sscore%d=%d text%d=\"%s\" grammar%d=%s", (i > 0 ? " " : ""), i, result->score, i, result->text, i, result->grammar);
  2961. /* Increment result count */
  2962. i++;
  2963. }
  2964. /* Print out */
  2965. ast_agi_send(agi->fd, chan, "200 result=1 (speech) endpos=%ld results=%d %s\n", current_offset, i, tmp);
  2966. } else if (!strcasecmp(reason, "dtmf")) {
  2967. ast_agi_send(agi->fd, chan, "200 result=1 (digit) digit=%c endpos=%ld\n", dtmf, current_offset);
  2968. } else if (!strcasecmp(reason, "hangup") || !strcasecmp(reason, "timeout")) {
  2969. ast_agi_send(agi->fd, chan, "200 result=1 (%s) endpos=%ld\n", reason, current_offset);
  2970. } else {
  2971. ast_agi_send(agi->fd, chan, "200 result=0 endpos=%ld\n", current_offset);
  2972. }
  2973. return RESULT_SUCCESS;
  2974. }
  2975. /*!
  2976. * \brief AGI commands list
  2977. */
  2978. static struct agi_command commands[] = {
  2979. { { "answer", NULL }, handle_answer, NULL, NULL, 0 },
  2980. { { "asyncagi", "break", NULL }, handle_asyncagi_break, NULL, NULL, 1 },
  2981. { { "channel", "status", NULL }, handle_channelstatus, NULL, NULL, 0 },
  2982. { { "database", "del", NULL }, handle_dbdel, NULL, NULL, 1 },
  2983. { { "database", "deltree", NULL }, handle_dbdeltree, NULL, NULL, 1 },
  2984. { { "database", "get", NULL }, handle_dbget, NULL, NULL, 1 },
  2985. { { "database", "put", NULL }, handle_dbput, NULL, NULL, 1 },
  2986. { { "exec", NULL }, handle_exec, NULL, NULL, 1 },
  2987. { { "get", "data", NULL }, handle_getdata, NULL, NULL, 0 },
  2988. { { "get", "full", "variable", NULL }, handle_getvariablefull, NULL, NULL, 1 },
  2989. { { "get", "option", NULL }, handle_getoption, NULL, NULL, 0 },
  2990. { { "get", "variable", NULL }, handle_getvariable, NULL, NULL, 1 },
  2991. { { "hangup", NULL }, handle_hangup, NULL, NULL, 0 },
  2992. { { "noop", NULL }, handle_noop, NULL, NULL, 1 },
  2993. { { "receive", "char", NULL }, handle_recvchar, NULL, NULL, 0 },
  2994. { { "receive", "text", NULL }, handle_recvtext, NULL, NULL, 0 },
  2995. { { "record", "file", NULL }, handle_recordfile, NULL, NULL, 0 },
  2996. { { "say", "alpha", NULL }, handle_sayalpha, NULL, NULL, 0},
  2997. { { "say", "digits", NULL }, handle_saydigits, NULL, NULL, 0 },
  2998. { { "say", "number", NULL }, handle_saynumber, NULL, NULL, 0 },
  2999. { { "say", "phonetic", NULL }, handle_sayphonetic, NULL, NULL, 0},
  3000. { { "say", "date", NULL }, handle_saydate, NULL, NULL, 0},
  3001. { { "say", "time", NULL }, handle_saytime, NULL, NULL, 0},
  3002. { { "say", "datetime", NULL }, handle_saydatetime, NULL, NULL, 0},
  3003. { { "send", "image", NULL }, handle_sendimage, NULL, NULL, 0},
  3004. { { "send", "text", NULL }, handle_sendtext, NULL, NULL, 0},
  3005. { { "set", "autohangup", NULL }, handle_autohangup, NULL, NULL, 0},
  3006. { { "set", "callerid", NULL }, handle_setcallerid, NULL, NULL, 0},
  3007. { { "set", "context", NULL }, handle_setcontext, NULL, NULL, 0},
  3008. { { "set", "extension", NULL }, handle_setextension, NULL, NULL, 0},
  3009. { { "set", "music", NULL }, handle_setmusic, NULL, NULL, 0 },
  3010. { { "set", "priority", NULL }, handle_setpriority, NULL, NULL, 0 },
  3011. { { "set", "variable", NULL }, handle_setvariable, NULL, NULL, 1 },
  3012. { { "stream", "file", NULL }, handle_streamfile, NULL, NULL, 0 },
  3013. { { "control", "stream", "file", NULL }, handle_controlstreamfile, NULL, NULL, 0 },
  3014. { { "tdd", "mode", NULL }, handle_tddmode, NULL, NULL, 0 },
  3015. { { "verbose", NULL }, handle_verbose, NULL, NULL, 1 },
  3016. { { "wait", "for", "digit", NULL }, handle_waitfordigit, NULL, NULL, 0 },
  3017. { { "speech", "create", NULL }, handle_speechcreate, NULL, NULL, 0 },
  3018. { { "speech", "set", NULL }, handle_speechset, NULL, NULL, 0 },
  3019. { { "speech", "destroy", NULL }, handle_speechdestroy, NULL, NULL, 1 },
  3020. { { "speech", "load", "grammar", NULL }, handle_speechloadgrammar, NULL, NULL, 0 },
  3021. { { "speech", "unload", "grammar", NULL }, handle_speechunloadgrammar, NULL, NULL, 1 },
  3022. { { "speech", "activate", "grammar", NULL }, handle_speechactivategrammar, NULL, NULL, 0 },
  3023. { { "speech", "deactivate", "grammar", NULL }, handle_speechdeactivategrammar, NULL, NULL, 0 },
  3024. { { "speech", "recognize", NULL }, handle_speechrecognize, NULL, NULL, 0 },
  3025. };
  3026. static AST_RWLIST_HEAD_STATIC(agi_commands, agi_command);
  3027. static char *help_workhorse(int fd, const char * const match[])
  3028. {
  3029. char fullcmd[MAX_CMD_LEN], matchstr[MAX_CMD_LEN];
  3030. struct agi_command *e;
  3031. if (match)
  3032. ast_join(matchstr, sizeof(matchstr), match);
  3033. ast_cli(fd, "%5.5s %30.30s %s\n","Dead","Command","Description");
  3034. AST_RWLIST_RDLOCK(&agi_commands);
  3035. AST_RWLIST_TRAVERSE(&agi_commands, e, list) {
  3036. if (!e->cmda[0])
  3037. break;
  3038. /* Hide commands that start with '_' */
  3039. if ((e->cmda[0])[0] == '_')
  3040. continue;
  3041. ast_join(fullcmd, sizeof(fullcmd), e->cmda);
  3042. if (match && strncasecmp(matchstr, fullcmd, strlen(matchstr)))
  3043. continue;
  3044. ast_cli(fd, "%5.5s %30.30s %s\n", e->dead ? "Yes" : "No" , fullcmd, S_OR(e->summary, "Not available"));
  3045. }
  3046. AST_RWLIST_UNLOCK(&agi_commands);
  3047. return CLI_SUCCESS;
  3048. }
  3049. int AST_OPTIONAL_API_NAME(ast_agi_register)(struct ast_module *mod, agi_command *cmd)
  3050. {
  3051. char fullcmd[MAX_CMD_LEN];
  3052. ast_join(fullcmd, sizeof(fullcmd), cmd->cmda);
  3053. if (!find_command(cmd->cmda, 1)) {
  3054. *((enum ast_doc_src *) &cmd->docsrc) = AST_STATIC_DOC;
  3055. if (ast_strlen_zero(cmd->summary) && ast_strlen_zero(cmd->usage)) {
  3056. #ifdef AST_XML_DOCS
  3057. *((char **) &cmd->summary) = ast_xmldoc_build_synopsis("agi", fullcmd, NULL);
  3058. *((char **) &cmd->usage) = ast_xmldoc_build_description("agi", fullcmd, NULL);
  3059. *((char **) &cmd->syntax) = ast_xmldoc_build_syntax("agi", fullcmd, NULL);
  3060. *((char **) &cmd->seealso) = ast_xmldoc_build_seealso("agi", fullcmd, NULL);
  3061. *((enum ast_doc_src *) &cmd->docsrc) = AST_XML_DOC;
  3062. #endif
  3063. #ifndef HAVE_NULLSAFE_PRINTF
  3064. if (!cmd->summary) {
  3065. *((char **) &cmd->summary) = ast_strdup("");
  3066. }
  3067. if (!cmd->usage) {
  3068. *((char **) &cmd->usage) = ast_strdup("");
  3069. }
  3070. if (!cmd->syntax) {
  3071. *((char **) &cmd->syntax) = ast_strdup("");
  3072. }
  3073. if (!cmd->seealso) {
  3074. *((char **) &cmd->seealso) = ast_strdup("");
  3075. }
  3076. #endif
  3077. }
  3078. cmd->mod = mod;
  3079. AST_RWLIST_WRLOCK(&agi_commands);
  3080. AST_LIST_INSERT_TAIL(&agi_commands, cmd, list);
  3081. AST_RWLIST_UNLOCK(&agi_commands);
  3082. if (mod != ast_module_info->self)
  3083. ast_module_ref(ast_module_info->self);
  3084. ast_verb(2, "AGI Command '%s' registered\n",fullcmd);
  3085. return 1;
  3086. } else {
  3087. ast_log(LOG_WARNING, "Command already registered!\n");
  3088. return 0;
  3089. }
  3090. }
  3091. int AST_OPTIONAL_API_NAME(ast_agi_unregister)(struct ast_module *mod, agi_command *cmd)
  3092. {
  3093. struct agi_command *e;
  3094. int unregistered = 0;
  3095. char fullcmd[MAX_CMD_LEN];
  3096. ast_join(fullcmd, sizeof(fullcmd), cmd->cmda);
  3097. AST_RWLIST_WRLOCK(&agi_commands);
  3098. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&agi_commands, e, list) {
  3099. if (cmd == e) {
  3100. AST_RWLIST_REMOVE_CURRENT(list);
  3101. if (mod != ast_module_info->self)
  3102. ast_module_unref(ast_module_info->self);
  3103. #ifdef AST_XML_DOCS
  3104. if (e->docsrc == AST_XML_DOC) {
  3105. ast_free((char *) e->summary);
  3106. ast_free((char *) e->usage);
  3107. ast_free((char *) e->syntax);
  3108. ast_free((char *) e->seealso);
  3109. *((char **) &e->summary) = NULL;
  3110. *((char **) &e->usage) = NULL;
  3111. *((char **) &e->syntax) = NULL;
  3112. *((char **) &e->seealso) = NULL;
  3113. }
  3114. #endif
  3115. unregistered=1;
  3116. break;
  3117. }
  3118. }
  3119. AST_RWLIST_TRAVERSE_SAFE_END;
  3120. AST_RWLIST_UNLOCK(&agi_commands);
  3121. if (unregistered) {
  3122. ast_verb(2, "AGI Command '%s' unregistered\n",fullcmd);
  3123. }
  3124. return unregistered;
  3125. }
  3126. int AST_OPTIONAL_API_NAME(ast_agi_register_multiple)(struct ast_module *mod, struct agi_command *cmd, unsigned int len)
  3127. {
  3128. unsigned int i, x = 0;
  3129. for (i = 0; i < len; i++) {
  3130. if (ast_agi_register(mod, cmd + i) == 1) {
  3131. x++;
  3132. continue;
  3133. }
  3134. /* registration failed, unregister everything
  3135. that had been registered up to that point
  3136. */
  3137. for (; x > 0; x--) {
  3138. /* we are intentionally ignoring the
  3139. result of ast_agi_unregister() here,
  3140. but it should be safe to do so since
  3141. we just registered these commands and
  3142. the only possible way for unregistration
  3143. to fail is if the command is not
  3144. registered
  3145. */
  3146. (void) ast_agi_unregister(mod, cmd + x - 1);
  3147. }
  3148. return -1;
  3149. }
  3150. return 0;
  3151. }
  3152. int AST_OPTIONAL_API_NAME(ast_agi_unregister_multiple)(struct ast_module *mod, struct agi_command *cmd, unsigned int len)
  3153. {
  3154. unsigned int i;
  3155. int res = 0;
  3156. for (i = 0; i < len; i++) {
  3157. /* remember whether any of the unregistration
  3158. attempts failed... there is no recourse if
  3159. any of them do
  3160. */
  3161. res |= ast_agi_unregister(mod, cmd + i);
  3162. }
  3163. return res;
  3164. }
  3165. static agi_command *find_command(const char * const cmds[], int exact)
  3166. {
  3167. int y, match;
  3168. struct agi_command *e;
  3169. AST_RWLIST_RDLOCK(&agi_commands);
  3170. AST_RWLIST_TRAVERSE(&agi_commands, e, list) {
  3171. if (!e->cmda[0])
  3172. break;
  3173. /* start optimistic */
  3174. match = 1;
  3175. for (y = 0; match && cmds[y]; y++) {
  3176. /* If there are no more words in the command (and we're looking for
  3177. an exact match) or there is a difference between the two words,
  3178. then this is not a match */
  3179. if (!e->cmda[y] && !exact)
  3180. break;
  3181. /* don't segfault if the next part of a command doesn't exist */
  3182. if (!e->cmda[y]) {
  3183. AST_RWLIST_UNLOCK(&agi_commands);
  3184. return NULL;
  3185. }
  3186. if (strcasecmp(e->cmda[y], cmds[y]))
  3187. match = 0;
  3188. }
  3189. /* If more words are needed to complete the command then this is not
  3190. a candidate (unless we're looking for a really inexact answer */
  3191. if ((exact > -1) && e->cmda[y])
  3192. match = 0;
  3193. if (match) {
  3194. AST_RWLIST_UNLOCK(&agi_commands);
  3195. return e;
  3196. }
  3197. }
  3198. AST_RWLIST_UNLOCK(&agi_commands);
  3199. return NULL;
  3200. }
  3201. static int parse_args(char *s, int *max, const char *argv[])
  3202. {
  3203. int x = 0, quoted = 0, escaped = 0, whitespace = 1;
  3204. char *cur;
  3205. cur = s;
  3206. while(*s) {
  3207. switch(*s) {
  3208. case '"':
  3209. /* If it's escaped, put a literal quote */
  3210. if (escaped)
  3211. goto normal;
  3212. else
  3213. quoted = !quoted;
  3214. if (quoted && whitespace) {
  3215. /* If we're starting a quote, coming off white space start a new word, too */
  3216. argv[x++] = cur;
  3217. whitespace=0;
  3218. }
  3219. escaped = 0;
  3220. break;
  3221. case ' ':
  3222. case '\t':
  3223. if (!quoted && !escaped) {
  3224. /* If we're not quoted, mark this as whitespace, and
  3225. end the previous argument */
  3226. whitespace = 1;
  3227. *(cur++) = '\0';
  3228. } else
  3229. /* Otherwise, just treat it as anything else */
  3230. goto normal;
  3231. break;
  3232. case '\\':
  3233. /* If we're escaped, print a literal, otherwise enable escaping */
  3234. if (escaped) {
  3235. goto normal;
  3236. } else {
  3237. escaped=1;
  3238. }
  3239. break;
  3240. default:
  3241. normal:
  3242. if (whitespace) {
  3243. if (x >= MAX_ARGS -1) {
  3244. ast_log(LOG_WARNING, "Too many arguments, truncating\n");
  3245. break;
  3246. }
  3247. /* Coming off of whitespace, start the next argument */
  3248. argv[x++] = cur;
  3249. whitespace=0;
  3250. }
  3251. *(cur++) = *s;
  3252. escaped=0;
  3253. }
  3254. s++;
  3255. }
  3256. /* Null terminate */
  3257. *(cur++) = '\0';
  3258. argv[x] = NULL;
  3259. *max = x;
  3260. return 0;
  3261. }
  3262. static void publish_async_exec_end(struct ast_channel *chan, int command_id, const char *command, int result_code, const char *result)
  3263. {
  3264. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  3265. blob = ast_json_pack("{s: i, s: s, s: i, s: s}",
  3266. "CommandId", command_id,
  3267. "Command", command,
  3268. "ResultCode", result_code,
  3269. "Result", result);
  3270. ast_channel_publish_cached_blob(chan, agi_exec_end_type(), blob);
  3271. }
  3272. static enum agi_result agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf, int dead)
  3273. {
  3274. const char *argv[MAX_ARGS];
  3275. int argc = MAX_ARGS;
  3276. int res;
  3277. agi_command *c;
  3278. char *ami_cmd = ast_strdupa(buf);
  3279. const char *ami_res;
  3280. int command_id = ast_random();
  3281. int resultcode = 0;
  3282. RAII_VAR(struct ast_json *, startblob, NULL, ast_json_unref);
  3283. startblob = ast_json_pack("{s: i, s: s}",
  3284. "CommandId", command_id,
  3285. "Command", ami_cmd);
  3286. ast_channel_publish_cached_blob(chan, agi_exec_start_type(), startblob);
  3287. parse_args(buf, &argc, argv);
  3288. c = find_command(argv, 0);
  3289. if (c && (!dead || (dead && c->dead))) {
  3290. /* if this command wasn't registered by res_agi, be sure to usecount
  3291. the module we are using */
  3292. if (c->mod != ast_module_info->self)
  3293. ast_module_ref(c->mod);
  3294. res = c->handler(chan, agi, argc, argv);
  3295. if (c->mod != ast_module_info->self)
  3296. ast_module_unref(c->mod);
  3297. switch (res) {
  3298. case RESULT_SHOWUSAGE:
  3299. ami_res = "Usage";
  3300. resultcode = 520;
  3301. publish_async_exec_end(chan, command_id, ami_cmd, resultcode, ami_res);
  3302. if (ast_strlen_zero(c->usage)) {
  3303. ast_agi_send(agi->fd, chan, "520 Invalid command syntax. Proper usage not available.\n");
  3304. } else {
  3305. ast_agi_send(agi->fd, chan, "520-Invalid command syntax. Proper usage follows:\n");
  3306. ast_agi_send(agi->fd, chan, "%s", c->usage);
  3307. ast_agi_send(agi->fd, chan, "520 End of proper usage.\n");
  3308. }
  3309. break;
  3310. case RESULT_FAILURE:
  3311. ami_res = "Failure";
  3312. resultcode = -1;
  3313. publish_async_exec_end(chan, command_id, ami_cmd, resultcode, ami_res);
  3314. /* The RESULT_FAILURE code is usually because the channel hungup. */
  3315. return AGI_RESULT_FAILURE;
  3316. case ASYNC_AGI_BREAK:
  3317. ami_res = "Success";
  3318. resultcode = 200;
  3319. publish_async_exec_end(chan, command_id, ami_cmd, resultcode, ami_res);
  3320. return AGI_RESULT_SUCCESS_ASYNC;
  3321. case RESULT_SUCCESS:
  3322. ami_res = "Success";
  3323. resultcode = 200;
  3324. publish_async_exec_end(chan, command_id, ami_cmd, resultcode, ami_res);
  3325. break;
  3326. default:
  3327. ami_res = "Unknown Result";
  3328. resultcode = 200;
  3329. publish_async_exec_end(chan, command_id, ami_cmd, resultcode, ami_res);
  3330. break;
  3331. }
  3332. } else if (c) {
  3333. ami_res = "Command Not Permitted on a dead channel";
  3334. resultcode = 511;
  3335. ast_agi_send(agi->fd, chan, "%d %s\n", resultcode, ami_res);
  3336. publish_async_exec_end(chan, command_id, ami_cmd, resultcode, ami_res);
  3337. } else {
  3338. ami_res = "Invalid or unknown command";
  3339. resultcode = 510;
  3340. ast_agi_send(agi->fd, chan, "%d %s\n", resultcode, ami_res);
  3341. publish_async_exec_end(chan, command_id, ami_cmd, resultcode, ami_res);
  3342. }
  3343. return AGI_RESULT_SUCCESS;
  3344. }
  3345. static enum agi_result run_agi(struct ast_channel *chan, char *request, AGI *agi, int pid, int *status, int dead, int argc, char *argv[])
  3346. {
  3347. struct ast_channel *c;
  3348. int outfd;
  3349. int ms;
  3350. int needhup = 0;
  3351. enum agi_result returnstatus = AGI_RESULT_SUCCESS;
  3352. struct ast_frame *f;
  3353. char buf[AGI_BUF_LEN];
  3354. char *res = NULL;
  3355. FILE *readf;
  3356. /* how many times we'll retry if ast_waitfor_nandfs will return without either
  3357. channel or file descriptor in case select is interrupted by a system call (EINTR) */
  3358. int retry = AGI_NANDFS_RETRY;
  3359. int send_sighup;
  3360. const char *sighup_str;
  3361. const char *exit_on_hangup_str;
  3362. int exit_on_hangup;
  3363. ast_channel_lock(chan);
  3364. sighup_str = pbx_builtin_getvar_helper(chan, "AGISIGHUP");
  3365. send_sighup = !ast_false(sighup_str);
  3366. exit_on_hangup_str = pbx_builtin_getvar_helper(chan, "AGIEXITONHANGUP");
  3367. exit_on_hangup = ast_true(exit_on_hangup_str);
  3368. ast_channel_unlock(chan);
  3369. if (!(readf = fdopen(agi->ctrl, "r"))) {
  3370. ast_log(LOG_WARNING, "Unable to fdopen file descriptor\n");
  3371. if (send_sighup && pid > -1)
  3372. kill(pid, SIGHUP);
  3373. close(agi->ctrl);
  3374. return AGI_RESULT_FAILURE;
  3375. }
  3376. setlinebuf(readf);
  3377. setup_env(chan, request, agi->fd, (agi->audio > -1), argc, argv);
  3378. for (;;) {
  3379. if (needhup) {
  3380. needhup = 0;
  3381. dead = 1;
  3382. if (send_sighup) {
  3383. if (pid > -1) {
  3384. kill(pid, SIGHUP);
  3385. } else if (agi->fast) {
  3386. ast_agi_send(agi->fd, chan, "HANGUP\n");
  3387. }
  3388. }
  3389. if (exit_on_hangup) {
  3390. break;
  3391. }
  3392. }
  3393. ms = -1;
  3394. if (dead) {
  3395. c = ast_waitfor_nandfds(&chan, 0, &agi->ctrl, 1, NULL, &outfd, &ms);
  3396. } else if (!ast_check_hangup(chan)) {
  3397. c = ast_waitfor_nandfds(&chan, 1, &agi->ctrl, 1, NULL, &outfd, &ms);
  3398. } else {
  3399. /*
  3400. * Read the channel control queue until it is dry so we can
  3401. * switch to dead mode.
  3402. */
  3403. c = chan;
  3404. }
  3405. if (c) {
  3406. retry = AGI_NANDFS_RETRY;
  3407. /* Idle the channel until we get a command */
  3408. f = ast_read(c);
  3409. if (!f) {
  3410. ast_debug(1, "%s hungup\n", ast_channel_name(chan));
  3411. needhup = 1;
  3412. if (!returnstatus) {
  3413. returnstatus = AGI_RESULT_HANGUP;
  3414. }
  3415. } else {
  3416. /* If it's voice, write it to the audio pipe */
  3417. if ((agi->audio > -1) && (f->frametype == AST_FRAME_VOICE)) {
  3418. /* Write, ignoring errors */
  3419. if (write(agi->audio, f->data.ptr, f->datalen) < 0) {
  3420. }
  3421. }
  3422. ast_frfree(f);
  3423. }
  3424. } else if (outfd > -1) {
  3425. size_t len = sizeof(buf);
  3426. size_t buflen = 0;
  3427. enum agi_result cmd_status;
  3428. retry = AGI_NANDFS_RETRY;
  3429. buf[0] = '\0';
  3430. while (len > 1) {
  3431. res = fgets(buf + buflen, len, readf);
  3432. if (feof(readf))
  3433. break;
  3434. if (ferror(readf) && ((errno != EINTR) && (errno != EAGAIN)))
  3435. break;
  3436. if (res != NULL && !agi->fast)
  3437. break;
  3438. buflen = strlen(buf);
  3439. if (buflen && buf[buflen - 1] == '\n')
  3440. break;
  3441. len = sizeof(buf) - buflen;
  3442. if (agidebug)
  3443. ast_verbose("AGI Rx << temp buffer %s - errno %s\nNo \\n received, checking again.\n", buf, strerror(errno));
  3444. }
  3445. if (!buf[0]) {
  3446. /* Program terminated */
  3447. ast_verb(3, "<%s>AGI Script %s completed, returning %d\n", ast_channel_name(chan), request, returnstatus);
  3448. if (pid > 0)
  3449. waitpid(pid, status, 0);
  3450. /* No need to kill the pid anymore, since they closed us */
  3451. pid = -1;
  3452. break;
  3453. }
  3454. /* Special case for inability to execute child process */
  3455. if (*buf && strncasecmp(buf, "failure", 7) == 0) {
  3456. returnstatus = AGI_RESULT_FAILURE;
  3457. break;
  3458. }
  3459. /* get rid of trailing newline, if any */
  3460. buflen = strlen(buf);
  3461. if (buflen && buf[buflen - 1] == '\n') {
  3462. buf[buflen - 1] = '\0';
  3463. }
  3464. if (agidebug)
  3465. ast_verbose("<%s>AGI Rx << %s\n", ast_channel_name(chan), buf);
  3466. cmd_status = agi_handle_command(chan, agi, buf, dead);
  3467. switch (cmd_status) {
  3468. case AGI_RESULT_FAILURE:
  3469. if (dead || !ast_check_hangup(chan)) {
  3470. /* The failure was not because of a hangup. */
  3471. returnstatus = AGI_RESULT_FAILURE;
  3472. }
  3473. break;
  3474. default:
  3475. break;
  3476. }
  3477. } else {
  3478. if (--retry <= 0) {
  3479. ast_log(LOG_WARNING, "No channel, no fd?\n");
  3480. returnstatus = AGI_RESULT_FAILURE;
  3481. break;
  3482. }
  3483. }
  3484. }
  3485. if (agi->speech) {
  3486. ast_speech_destroy(agi->speech);
  3487. }
  3488. /* Notify process */
  3489. if (send_sighup) {
  3490. if (pid > -1) {
  3491. if (kill(pid, SIGHUP)) {
  3492. ast_log(LOG_WARNING, "unable to send SIGHUP to AGI process %d: %s\n", pid, strerror(errno));
  3493. } else { /* Give the process a chance to die */
  3494. usleep(1);
  3495. }
  3496. waitpid(pid, status, WNOHANG);
  3497. } else if (agi->fast) {
  3498. ast_agi_send(agi->fd, chan, "HANGUP\n");
  3499. }
  3500. }
  3501. fclose(readf);
  3502. return returnstatus;
  3503. }
  3504. static char *handle_cli_agi_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3505. {
  3506. struct agi_command *command;
  3507. char fullcmd[MAX_CMD_LEN];
  3508. int error = 0;
  3509. switch (cmd) {
  3510. case CLI_INIT:
  3511. e->command = "agi show commands [topic]";
  3512. e->usage =
  3513. "Usage: agi show commands [topic] <topic>\n"
  3514. " When called with a topic as an argument, displays usage\n"
  3515. " information on the given command. If called without a\n"
  3516. " topic, it provides a list of AGI commands.\n";
  3517. case CLI_GENERATE:
  3518. return NULL;
  3519. }
  3520. if (a->argc < e->args - 1 || (a->argc >= e->args && strcasecmp(a->argv[e->args - 1], "topic")))
  3521. return CLI_SHOWUSAGE;
  3522. if (a->argc > e->args - 1) {
  3523. command = find_command(a->argv + e->args, 1);
  3524. if (command) {
  3525. char *synopsis = NULL, *description = NULL, *syntax = NULL, *seealso = NULL;
  3526. char info[30 + MAX_CMD_LEN]; /* '-= Info about...' */
  3527. char infotitle[30 + MAX_CMD_LEN + AST_TERM_MAX_ESCAPE_CHARS]; /* '-= Info about...' with colors */
  3528. char syntitle[11 + AST_TERM_MAX_ESCAPE_CHARS]; /* [Syntax]\n with colors */
  3529. char desctitle[15 + AST_TERM_MAX_ESCAPE_CHARS]; /* [Description]\n with colors */
  3530. char deadtitle[13 + AST_TERM_MAX_ESCAPE_CHARS]; /* [Runs Dead]\n with colors */
  3531. char deadcontent[3 + AST_TERM_MAX_ESCAPE_CHARS]; /* 'Yes' or 'No' with colors */
  3532. char seealsotitle[12 + AST_TERM_MAX_ESCAPE_CHARS]; /* [See Also]\n with colors */
  3533. char stxtitle[10 + AST_TERM_MAX_ESCAPE_CHARS]; /* [Syntax]\n with colors */
  3534. size_t synlen, desclen, seealsolen, stxlen;
  3535. term_color(syntitle, "[Synopsis]\n", COLOR_MAGENTA, 0, sizeof(syntitle));
  3536. term_color(desctitle, "[Description]\n", COLOR_MAGENTA, 0, sizeof(desctitle));
  3537. term_color(deadtitle, "[Runs Dead]\n", COLOR_MAGENTA, 0, sizeof(deadtitle));
  3538. term_color(seealsotitle, "[See Also]\n", COLOR_MAGENTA, 0, sizeof(seealsotitle));
  3539. term_color(stxtitle, "[Syntax]\n", COLOR_MAGENTA, 0, sizeof(stxtitle));
  3540. term_color(deadcontent, command->dead ? "Yes" : "No", COLOR_CYAN, 0, sizeof(deadcontent));
  3541. ast_join(fullcmd, sizeof(fullcmd), a->argv + e->args);
  3542. snprintf(info, sizeof(info), "\n -= Info about agi '%s' =- ", fullcmd);
  3543. term_color(infotitle, info, COLOR_CYAN, 0, sizeof(infotitle));
  3544. #ifdef AST_XML_DOCS
  3545. if (command->docsrc == AST_XML_DOC) {
  3546. synopsis = ast_xmldoc_printable(S_OR(command->summary, "Not available"), 1);
  3547. description = ast_xmldoc_printable(S_OR(command->usage, "Not available"), 1);
  3548. seealso = ast_xmldoc_printable(S_OR(command->seealso, "Not available"), 1);
  3549. if (!seealso || !description || !synopsis) {
  3550. error = 1;
  3551. goto return_cleanup;
  3552. }
  3553. } else
  3554. #endif
  3555. {
  3556. synlen = strlen(S_OR(command->summary, "Not available")) + AST_TERM_MAX_ESCAPE_CHARS;
  3557. synopsis = ast_malloc(synlen);
  3558. desclen = strlen(S_OR(command->usage, "Not available")) + AST_TERM_MAX_ESCAPE_CHARS;
  3559. description = ast_malloc(desclen);
  3560. seealsolen = strlen(S_OR(command->seealso, "Not available")) + AST_TERM_MAX_ESCAPE_CHARS;
  3561. seealso = ast_malloc(seealsolen);
  3562. if (!synopsis || !description || !seealso) {
  3563. error = 1;
  3564. goto return_cleanup;
  3565. }
  3566. term_color(synopsis, S_OR(command->summary, "Not available"), COLOR_CYAN, 0, synlen);
  3567. term_color(description, S_OR(command->usage, "Not available"), COLOR_CYAN, 0, desclen);
  3568. term_color(seealso, S_OR(command->seealso, "Not available"), COLOR_CYAN, 0, seealsolen);
  3569. }
  3570. stxlen = strlen(S_OR(command->syntax, "Not available")) + AST_TERM_MAX_ESCAPE_CHARS;
  3571. syntax = ast_malloc(stxlen);
  3572. if (!syntax) {
  3573. error = 1;
  3574. goto return_cleanup;
  3575. }
  3576. term_color(syntax, S_OR(command->syntax, "Not available"), COLOR_CYAN, 0, stxlen);
  3577. ast_cli(a->fd, "%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n", infotitle, stxtitle, syntax,
  3578. desctitle, description, syntitle, synopsis, deadtitle, deadcontent,
  3579. seealsotitle, seealso);
  3580. return_cleanup:
  3581. ast_free(synopsis);
  3582. ast_free(description);
  3583. ast_free(syntax);
  3584. ast_free(seealso);
  3585. } else {
  3586. if (find_command(a->argv + e->args, -1)) {
  3587. return help_workhorse(a->fd, a->argv + e->args);
  3588. } else {
  3589. ast_join(fullcmd, sizeof(fullcmd), a->argv + e->args);
  3590. ast_cli(a->fd, "No such command '%s'.\n", fullcmd);
  3591. }
  3592. }
  3593. } else {
  3594. return help_workhorse(a->fd, NULL);
  3595. }
  3596. return (error ? CLI_FAILURE : CLI_SUCCESS);
  3597. }
  3598. /*! \brief Convert string to use HTML escaped characters
  3599. \note Maybe this should be a generic function?
  3600. */
  3601. static void write_html_escaped(FILE *htmlfile, char *str)
  3602. {
  3603. char *cur = str;
  3604. while(*cur) {
  3605. switch (*cur) {
  3606. case '<':
  3607. fprintf(htmlfile, "%s", "&lt;");
  3608. break;
  3609. case '>':
  3610. fprintf(htmlfile, "%s", "&gt;");
  3611. break;
  3612. case '&':
  3613. fprintf(htmlfile, "%s", "&amp;");
  3614. break;
  3615. case '"':
  3616. fprintf(htmlfile, "%s", "&quot;");
  3617. break;
  3618. default:
  3619. fprintf(htmlfile, "%c", *cur);
  3620. break;
  3621. }
  3622. cur++;
  3623. }
  3624. return;
  3625. }
  3626. static int write_htmldump(const char *filename)
  3627. {
  3628. struct agi_command *command;
  3629. char fullcmd[MAX_CMD_LEN];
  3630. FILE *htmlfile;
  3631. if (!(htmlfile = fopen(filename, "wt")))
  3632. return -1;
  3633. fprintf(htmlfile, "<HTML>\n<HEAD>\n<TITLE>AGI Commands</TITLE>\n</HEAD>\n");
  3634. fprintf(htmlfile, "<BODY>\n<CENTER><B><H1>AGI Commands</H1></B></CENTER>\n\n");
  3635. fprintf(htmlfile, "<TABLE BORDER=\"0\" CELLSPACING=\"10\">\n");
  3636. AST_RWLIST_RDLOCK(&agi_commands);
  3637. AST_RWLIST_TRAVERSE(&agi_commands, command, list) {
  3638. char *tempstr, *stringp;
  3639. if (!command->cmda[0]) /* end ? */
  3640. break;
  3641. /* Hide commands that start with '_' */
  3642. if ((command->cmda[0])[0] == '_')
  3643. continue;
  3644. ast_join(fullcmd, sizeof(fullcmd), command->cmda);
  3645. fprintf(htmlfile, "<TR><TD><TABLE BORDER=\"1\" CELLPADDING=\"5\" WIDTH=\"100%%\">\n");
  3646. fprintf(htmlfile, "<TR><TH ALIGN=\"CENTER\"><B>%s - %s</B></TH></TR>\n", fullcmd, command->summary);
  3647. #ifdef AST_XML_DOCS
  3648. stringp = ast_xmldoc_printable(command->usage, 0);
  3649. #else
  3650. stringp = ast_strdup(command->usage);
  3651. #endif
  3652. tempstr = strsep(&stringp, "\n");
  3653. fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">");
  3654. write_html_escaped(htmlfile, tempstr);
  3655. fprintf(htmlfile, "</TD></TR>\n");
  3656. fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">\n");
  3657. while ((tempstr = strsep(&stringp, "\n")) != NULL) {
  3658. write_html_escaped(htmlfile, tempstr);
  3659. fprintf(htmlfile, "<BR>\n");
  3660. }
  3661. fprintf(htmlfile, "</TD></TR>\n");
  3662. fprintf(htmlfile, "</TABLE></TD></TR>\n\n");
  3663. ast_free(stringp);
  3664. }
  3665. AST_RWLIST_UNLOCK(&agi_commands);
  3666. fprintf(htmlfile, "</TABLE>\n</BODY>\n</HTML>\n");
  3667. fclose(htmlfile);
  3668. return 0;
  3669. }
  3670. static char *handle_cli_agi_dump_html(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3671. {
  3672. switch (cmd) {
  3673. case CLI_INIT:
  3674. e->command = "agi dump html";
  3675. e->usage =
  3676. "Usage: agi dump html <filename>\n"
  3677. " Dumps the AGI command list in HTML format to the given\n"
  3678. " file.\n";
  3679. return NULL;
  3680. case CLI_GENERATE:
  3681. return NULL;
  3682. }
  3683. if (a->argc != e->args + 1)
  3684. return CLI_SHOWUSAGE;
  3685. if (write_htmldump(a->argv[e->args]) < 0) {
  3686. ast_cli(a->fd, "Could not create file '%s'\n", a->argv[e->args]);
  3687. return CLI_SHOWUSAGE;
  3688. }
  3689. ast_cli(a->fd, "AGI HTML commands dumped to: %s\n", a->argv[e->args]);
  3690. return CLI_SUCCESS;
  3691. }
  3692. static int agi_exec_full(struct ast_channel *chan, const char *data, int enhanced, int dead)
  3693. {
  3694. enum agi_result res;
  3695. char *buf;
  3696. int fds[2], efd = -1, pid = -1;
  3697. AST_DECLARE_APP_ARGS(args,
  3698. AST_APP_ARG(arg)[MAX_ARGS];
  3699. );
  3700. AGI agi;
  3701. if (ast_strlen_zero(data)) {
  3702. ast_log(LOG_WARNING, "AGI requires an argument (script)\n");
  3703. return -1;
  3704. }
  3705. if (dead)
  3706. ast_debug(3, "Hungup channel detected, running agi in dead mode.\n");
  3707. memset(&agi, 0, sizeof(agi));
  3708. buf = ast_strdupa(data);
  3709. AST_STANDARD_APP_ARGS(args, buf);
  3710. args.argv[args.argc] = NULL;
  3711. #if 0
  3712. /* Answer if need be */
  3713. if (chan->_state != AST_STATE_UP) {
  3714. if (ast_answer(chan))
  3715. return -1;
  3716. }
  3717. #endif
  3718. res = launch_script(chan, args.argv[0], args.argc, args.argv, fds, enhanced ? &efd : NULL, &pid);
  3719. /* Async AGI do not require run_agi(), so just proceed if normal AGI
  3720. or Fast AGI are setup with success. */
  3721. if (res == AGI_RESULT_SUCCESS || res == AGI_RESULT_SUCCESS_FAST) {
  3722. int status = 0;
  3723. agi.fd = fds[1];
  3724. agi.ctrl = fds[0];
  3725. agi.audio = efd;
  3726. agi.fast = (res == AGI_RESULT_SUCCESS_FAST) ? 1 : 0;
  3727. res = run_agi(chan, args.argv[0], &agi, pid, &status, dead, args.argc, args.argv);
  3728. /* If the fork'd process returns non-zero, set AGISTATUS to FAILURE */
  3729. if ((res == AGI_RESULT_SUCCESS || res == AGI_RESULT_SUCCESS_FAST) && status)
  3730. res = AGI_RESULT_FAILURE;
  3731. if (fds[1] != fds[0])
  3732. close(fds[1]);
  3733. if (efd > -1)
  3734. close(efd);
  3735. }
  3736. ast_safe_fork_cleanup();
  3737. switch (res) {
  3738. case AGI_RESULT_SUCCESS:
  3739. case AGI_RESULT_SUCCESS_FAST:
  3740. case AGI_RESULT_SUCCESS_ASYNC:
  3741. pbx_builtin_setvar_helper(chan, "AGISTATUS", "SUCCESS");
  3742. break;
  3743. case AGI_RESULT_FAILURE:
  3744. pbx_builtin_setvar_helper(chan, "AGISTATUS", "FAILURE");
  3745. break;
  3746. case AGI_RESULT_NOTFOUND:
  3747. pbx_builtin_setvar_helper(chan, "AGISTATUS", "NOTFOUND");
  3748. break;
  3749. case AGI_RESULT_HANGUP:
  3750. pbx_builtin_setvar_helper(chan, "AGISTATUS", "HANGUP");
  3751. return -1;
  3752. }
  3753. return 0;
  3754. }
  3755. static int agi_exec(struct ast_channel *chan, const char *data)
  3756. {
  3757. if (!ast_check_hangup(chan))
  3758. return agi_exec_full(chan, data, 0, 0);
  3759. else
  3760. return agi_exec_full(chan, data, 0, 1);
  3761. }
  3762. static int eagi_exec(struct ast_channel *chan, const char *data)
  3763. {
  3764. int res;
  3765. struct ast_format *readformat;
  3766. if (ast_check_hangup(chan)) {
  3767. ast_log(LOG_ERROR, "EAGI cannot be run on a dead/hungup channel, please use AGI.\n");
  3768. return 0;
  3769. }
  3770. readformat = ao2_bump(ast_channel_readformat(chan));
  3771. if (ast_set_read_format(chan, ast_format_slin)) {
  3772. ast_log(LOG_WARNING, "Unable to set channel '%s' to linear mode\n", ast_channel_name(chan));
  3773. ao2_ref(readformat, -1);
  3774. return -1;
  3775. }
  3776. res = agi_exec_full(chan, data, 1, 0);
  3777. if (!res) {
  3778. if (ast_set_read_format(chan, readformat)) {
  3779. ast_log(LOG_WARNING, "Unable to restore channel '%s' to format %s\n", ast_channel_name(chan),
  3780. ast_format_get_name(readformat));
  3781. }
  3782. }
  3783. ao2_ref(readformat, -1);
  3784. return res;
  3785. }
  3786. static int deadagi_exec(struct ast_channel *chan, const char *data)
  3787. {
  3788. ast_log(LOG_WARNING, "DeadAGI has been deprecated, please use AGI in all cases!\n");
  3789. return agi_exec(chan, data);
  3790. }
  3791. static struct ast_cli_entry cli_agi[] = {
  3792. AST_CLI_DEFINE(handle_cli_agi_add_cmd, "Add AGI command to a channel in Async AGI"),
  3793. AST_CLI_DEFINE(handle_cli_agi_debug, "Enable/Disable AGI debugging"),
  3794. AST_CLI_DEFINE(handle_cli_agi_show, "List AGI commands or specific help"),
  3795. AST_CLI_DEFINE(handle_cli_agi_dump_html, "Dumps a list of AGI commands in HTML format")
  3796. };
  3797. #ifdef TEST_FRAMEWORK
  3798. AST_TEST_DEFINE(test_agi_null_docs)
  3799. {
  3800. int res = AST_TEST_PASS;
  3801. struct agi_command noop_command =
  3802. { { "testnoop", NULL }, handle_noop, NULL, NULL, 0 };
  3803. switch (cmd) {
  3804. case TEST_INIT:
  3805. info->name = "null_agi_docs";
  3806. info->category = "/res/agi/";
  3807. info->summary = "AGI command with no documentation";
  3808. info->description = "Test whether an AGI command with no documentation will crash Asterisk";
  3809. return AST_TEST_NOT_RUN;
  3810. case TEST_EXECUTE:
  3811. break;
  3812. }
  3813. if (ast_agi_register(ast_module_info->self, &noop_command) == 0) {
  3814. ast_test_status_update(test, "Unable to register testnoop command, because res_agi is not loaded.\n");
  3815. return AST_TEST_NOT_RUN;
  3816. }
  3817. #ifndef HAVE_NULLSAFE_PRINTF
  3818. /* Test for condition without actually crashing Asterisk */
  3819. if (noop_command.usage == NULL) {
  3820. ast_test_status_update(test, "AGI testnoop usage was not updated properly.\n");
  3821. res = AST_TEST_FAIL;
  3822. }
  3823. if (noop_command.syntax == NULL) {
  3824. ast_test_status_update(test, "AGI testnoop syntax was not updated properly.\n");
  3825. res = AST_TEST_FAIL;
  3826. }
  3827. #endif
  3828. ast_agi_unregister(ast_module_info->self, &noop_command);
  3829. return res;
  3830. }
  3831. #endif
  3832. static int unload_module(void)
  3833. {
  3834. STASIS_MESSAGE_TYPE_CLEANUP(agi_exec_start_type);
  3835. STASIS_MESSAGE_TYPE_CLEANUP(agi_exec_end_type);
  3836. STASIS_MESSAGE_TYPE_CLEANUP(agi_async_start_type);
  3837. STASIS_MESSAGE_TYPE_CLEANUP(agi_async_exec_type);
  3838. STASIS_MESSAGE_TYPE_CLEANUP(agi_async_end_type);
  3839. ast_cli_unregister_multiple(cli_agi, ARRAY_LEN(cli_agi));
  3840. ast_agi_unregister_multiple(ast_module_info->self, commands, ARRAY_LEN(commands));
  3841. ast_unregister_application(eapp);
  3842. ast_unregister_application(deadapp);
  3843. ast_manager_unregister("AGI");
  3844. ast_unregister_application(app);
  3845. AST_TEST_UNREGISTER(test_agi_null_docs);
  3846. return 0;
  3847. }
  3848. static int load_module(void)
  3849. {
  3850. int err = 0;
  3851. err |= STASIS_MESSAGE_TYPE_INIT(agi_exec_start_type);
  3852. err |= STASIS_MESSAGE_TYPE_INIT(agi_exec_end_type);
  3853. err |= STASIS_MESSAGE_TYPE_INIT(agi_async_start_type);
  3854. err |= STASIS_MESSAGE_TYPE_INIT(agi_async_exec_type);
  3855. err |= STASIS_MESSAGE_TYPE_INIT(agi_async_end_type);
  3856. err |= ast_cli_register_multiple(cli_agi, ARRAY_LEN(cli_agi));
  3857. err |= ast_agi_register_multiple(ast_module_info->self, commands, ARRAY_LEN(commands));
  3858. err |= ast_register_application_xml(deadapp, deadagi_exec);
  3859. err |= ast_register_application_xml(eapp, eagi_exec);
  3860. err |= ast_manager_register_xml("AGI", EVENT_FLAG_AGI, action_add_agi_cmd);
  3861. err |= ast_register_application_xml(app, agi_exec);
  3862. AST_TEST_REGISTER(test_agi_null_docs);
  3863. if (err) {
  3864. unload_module();
  3865. return AST_MODULE_LOAD_DECLINE;
  3866. }
  3867. return AST_MODULE_LOAD_SUCCESS;
  3868. }
  3869. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Asterisk Gateway Interface (AGI)",
  3870. .support_level = AST_MODULE_SUPPORT_CORE,
  3871. .load = load_module,
  3872. .unload = unload_module,
  3873. .load_pri = AST_MODPRI_APP_DEPEND,
  3874. );