res_agi.c 144 KB

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