res_agi.c 121 KB

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