res_agi.c 120 KB

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