res_fax.c 150 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2008-2009, Digium, Inc.
  5. *
  6. * Dwayne M. Hubbard <dhubbard@digium.com>
  7. * Kevin P. Fleming <kpfleming@digium.com>
  8. * Matthew Nicholson <mnicholson@digium.com>
  9. *
  10. * Initial T.38-gateway code
  11. * 2008, Daniel Ferenci <daniel.ferenci@nethemba.com>
  12. * Created by Nethemba s.r.o. http://www.nethemba.com
  13. * Sponsored by IPEX a.s. http://www.ipex.cz
  14. *
  15. * T.38-gateway integration into asterisk app_fax and rework
  16. * 2008-2011, Gregory Hinton Nietsky <gregory@distrotech.co.za>
  17. * dns Telecom http://www.dnstelecom.co.za
  18. *
  19. * Modified to make T.38-gateway compatible with Asterisk 1.6.2
  20. * 2010, Anton Verevkin <mymail@verevkin.it>
  21. * ViaNetTV http://www.vianettv.com
  22. *
  23. * Modified to make T.38-gateway work
  24. * 2010, Klaus Darilion, IPCom GmbH, www.ipcom.at
  25. *
  26. * See http://www.asterisk.org for more information about
  27. * the Asterisk project. Please do not directly contact
  28. * any of the maintainers of this project for assistance;
  29. * the project provides a web site, mailing lists and IRC
  30. * channels for your use.
  31. *
  32. * This program is free software, distributed under the terms of
  33. * the GNU General Public License Version 2. See the LICENSE file
  34. * at the top of the source tree.
  35. */
  36. /*** MODULEINFO
  37. <conflict>app_fax</conflict>
  38. <support_level>core</support_level>
  39. ***/
  40. /*! \file
  41. *
  42. * \brief Generic FAX Resource for FAX technology resource modules
  43. *
  44. * \author Dwayne M. Hubbard <dhubbard@digium.com>
  45. * \author Kevin P. Fleming <kpfleming@digium.com>
  46. * \author Matthew Nicholson <mnicholson@digium.com>
  47. * \author Gregory H. Nietsky <gregory@distrotech.co.za>
  48. *
  49. * A generic FAX resource module that provides SendFAX and ReceiveFAX applications.
  50. * This module requires FAX technology modules, like res_fax_spandsp, to register with it
  51. * so it can use the technology modules to perform the actual FAX transmissions.
  52. * \ingroup applications
  53. */
  54. /*! \li \ref res_fax.c uses the configuration file \ref res_fax.conf
  55. * \addtogroup configuration_file Configuration Files
  56. */
  57. /*!
  58. * \page res_fax.conf res_fax.conf
  59. * \verbinclude res_fax.conf.sample
  60. */
  61. #include "asterisk.h"
  62. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  63. #include "asterisk/io.h"
  64. #include "asterisk/file.h"
  65. #include "asterisk/logger.h"
  66. #include "asterisk/module.h"
  67. #include "asterisk/app.h"
  68. #include "asterisk/lock.h"
  69. #include "asterisk/options.h"
  70. #include "asterisk/strings.h"
  71. #include "asterisk/cli.h"
  72. #include "asterisk/utils.h"
  73. #include "asterisk/config.h"
  74. #include "asterisk/astobj2.h"
  75. #include "asterisk/res_fax.h"
  76. #include "asterisk/file.h"
  77. #include "asterisk/channel.h"
  78. #include "asterisk/pbx.h"
  79. #include "asterisk/dsp.h"
  80. #include "asterisk/indications.h"
  81. #include "asterisk/ast_version.h"
  82. #include "asterisk/translate.h"
  83. #include "asterisk/stasis.h"
  84. #include "asterisk/stasis_channels.h"
  85. #include "asterisk/smoother.h"
  86. #include "asterisk/format_cache.h"
  87. /*** DOCUMENTATION
  88. <application name="ReceiveFAX" language="en_US" module="res_fax">
  89. <synopsis>
  90. Receive a FAX and save as a TIFF/F file.
  91. </synopsis>
  92. <syntax>
  93. <parameter name="filename" required="true" />
  94. <parameter name="options">
  95. <optionlist>
  96. <option name="d">
  97. <para>Enable FAX debugging.</para>
  98. </option>
  99. <option name="f">
  100. <para>Allow audio fallback FAX transfer on T.38 capable channels.</para>
  101. </option>
  102. <option name="F">
  103. <para>Force usage of audio mode on T.38 capable channels.</para>
  104. </option>
  105. <option name="s">
  106. <para>Send progress Manager events (overrides statusevents setting in res_fax.conf).</para>
  107. </option>
  108. </optionlist>
  109. </parameter>
  110. </syntax>
  111. <description>
  112. <para>This application is provided by res_fax, which is a FAX technology agnostic module
  113. that utilizes FAX technology resource modules to complete a FAX transmission.</para>
  114. <para>Session arguments can be set by the FAXOPT function and to check results of the ReceiveFax() application.</para>
  115. </description>
  116. <see-also>
  117. <ref type="function">FAXOPT</ref>
  118. </see-also>
  119. </application>
  120. <application name="SendFAX" language="en_US" module="res_fax">
  121. <synopsis>
  122. Sends a specified TIFF/F file as a FAX.
  123. </synopsis>
  124. <syntax>
  125. <parameter name="filename" required="true" argsep="&amp;">
  126. <argument name="filename2" multiple="true">
  127. <para>TIFF file to send as a FAX.</para>
  128. </argument>
  129. </parameter>
  130. <parameter name="options">
  131. <optionlist>
  132. <option name="d">
  133. <para>Enable FAX debugging.</para>
  134. </option>
  135. <option name="f">
  136. <para>Allow audio fallback FAX transfer on T.38 capable channels.</para>
  137. </option>
  138. <option name="F">
  139. <para>Force usage of audio mode on T.38 capable channels.</para>
  140. </option>
  141. <option name="s">
  142. <para>Send progress Manager events (overrides statusevents setting in res_fax.conf).</para>
  143. </option>
  144. <option name="z">
  145. <para>Initiate a T.38 reinvite on the channel if the remote end does not.</para>
  146. </option>
  147. </optionlist>
  148. </parameter>
  149. </syntax>
  150. <description>
  151. <para>This application is provided by res_fax, which is a FAX technology agnostic module
  152. that utilizes FAX technology resource modules to complete a FAX transmission.</para>
  153. <para>Session arguments can be set by the FAXOPT function and to check results of the SendFax() application.</para>
  154. </description>
  155. <see-also>
  156. <ref type="function">FAXOPT</ref>
  157. </see-also>
  158. </application>
  159. <function name="FAXOPT" language="en_US" module="res_fax">
  160. <synopsis>
  161. Gets/sets various pieces of information about a fax session.
  162. </synopsis>
  163. <syntax>
  164. <parameter name="item" required="true">
  165. <enumlist>
  166. <enum name="ecm">
  167. <para>R/W Error Correction Mode (ECM) enable with 'yes', disable with 'no'.</para>
  168. </enum>
  169. <enum name="error">
  170. <para>R/O FAX transmission error code upon failure.</para>
  171. </enum>
  172. <enum name="filename">
  173. <para>R/O Filename of the first file of the FAX transmission.</para>
  174. </enum>
  175. <enum name="filenames">
  176. <para>R/O Filenames of all of the files in the FAX transmission (comma separated).</para>
  177. </enum>
  178. <enum name="headerinfo">
  179. <para>R/W FAX header information.</para>
  180. </enum>
  181. <enum name="localstationid">
  182. <para>R/W Local Station Identification.</para>
  183. </enum>
  184. <enum name="minrate">
  185. <para>R/W Minimum transfer rate set before transmission.</para>
  186. </enum>
  187. <enum name="maxrate">
  188. <para>R/W Maximum transfer rate set before transmission.</para>
  189. </enum>
  190. <enum name="modem">
  191. <para>R/W Modem type (v17/v27/v29).</para>
  192. </enum>
  193. <enum name="gateway">
  194. <para>R/W T38 fax gateway, with optional fax activity timeout in seconds (yes[,timeout]/no)</para>
  195. </enum>
  196. <enum name="faxdetect">
  197. <para>R/W Enable FAX detect with optional timeout in seconds (yes,t38,cng[,timeout]/no)</para>
  198. </enum>
  199. <enum name="pages">
  200. <para>R/O Number of pages transferred.</para>
  201. </enum>
  202. <enum name="rate">
  203. <para>R/O Negotiated transmission rate.</para>
  204. </enum>
  205. <enum name="remotestationid">
  206. <para>R/O Remote Station Identification after transmission.</para>
  207. </enum>
  208. <enum name="resolution">
  209. <para>R/O Negotiated image resolution after transmission.</para>
  210. </enum>
  211. <enum name="sessionid">
  212. <para>R/O Session ID of the FAX transmission.</para>
  213. </enum>
  214. <enum name="status">
  215. <para>R/O Result Status of the FAX transmission.</para>
  216. </enum>
  217. <enum name="statusstr">
  218. <para>R/O Verbose Result Status of the FAX transmission.</para>
  219. </enum>
  220. </enumlist>
  221. </parameter>
  222. </syntax>
  223. <description>
  224. <para>FAXOPT can be used to override the settings for a FAX session listed in <filename>res_fax.conf</filename>,
  225. it can also be used to retreive information about a FAX session that has finished eg. pages/status.</para>
  226. </description>
  227. <see-also>
  228. <ref type="application">ReceiveFax</ref>
  229. <ref type="application">SendFax</ref>
  230. </see-also>
  231. </function>
  232. <manager name="FAXSessions" language="en_US">
  233. <synopsis>
  234. Lists active FAX sessions
  235. </synopsis>
  236. <syntax>
  237. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  238. </syntax>
  239. <description>
  240. <para>Will generate a series of FAXSession events with information about each FAXSession. Closes with
  241. a FAXSessionsComplete event which includes a count of the included FAX sessions. This action works in
  242. the same manner as the CLI command 'fax show sessions'</para>
  243. </description>
  244. </manager>
  245. <managerEvent language="en_US" name="FAXSessionsEntry">
  246. <managerEventInstance class="EVENT_FLAG_REPORTING">
  247. <synopsis>A single list item for the FAXSessions AMI command</synopsis>
  248. <syntax>
  249. <parameter name="ActionID" required="false"/>
  250. <parameter name="Channel">
  251. <para>Name of the channel responsible for the FAX session</para>
  252. </parameter>
  253. <parameter name="Technology">
  254. <para>The FAX technology that the FAX session is using</para>
  255. </parameter>
  256. <parameter name="SessionNumber">
  257. <para>The numerical identifier for this particular session</para>
  258. </parameter>
  259. <parameter name="SessionType">
  260. <para>FAX session passthru/relay type</para>
  261. <enumlist>
  262. <enum name="G.711" />
  263. <enum name="T.38" />
  264. </enumlist>
  265. </parameter>
  266. <parameter name="Operation">
  267. <para>FAX session operation type</para>
  268. <enumlist>
  269. <enum name="gateway" />
  270. <enum name="V.21" />
  271. <enum name="send" />
  272. <enum name="receive" />
  273. <enum name="none" />
  274. </enumlist>
  275. </parameter>
  276. <parameter name="State">
  277. <para>Current state of the FAX session</para>
  278. <enumlist>
  279. <enum name="Uninitialized" />
  280. <enum name="Initialized" />
  281. <enum name="Open" />
  282. <enum name="Active" />
  283. <enum name="Complete" />
  284. <enum name="Reserved" />
  285. <enum name="Inactive" />
  286. <enum name="Unknown" />
  287. </enumlist>
  288. </parameter>
  289. <parameter name="Files">
  290. <para>File or list of files associated with this FAX session</para>
  291. </parameter>
  292. </syntax>
  293. </managerEventInstance>
  294. </managerEvent>
  295. <managerEvent language="en_US" name="FAXSessionsComplete">
  296. <managerEventInstance class="EVENT_FLAG_CALL">
  297. <synopsis>Raised when all FAXSession events are completed for a FAXSessions command</synopsis>
  298. <syntax>
  299. <parameter name="ActionID" required="false"/>
  300. <parameter name="Total">
  301. <para>Count of FAXSession events sent in response to FAXSessions action</para>
  302. </parameter>
  303. </syntax>
  304. </managerEventInstance>
  305. </managerEvent>
  306. <manager name="FAXSession" language="en_US">
  307. <synopsis>
  308. Responds with a detailed description of a single FAX session
  309. </synopsis>
  310. <syntax>
  311. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  312. <parameter name="SessionNumber" required="true">
  313. <para>The session ID of the fax the user is interested in.</para>
  314. </parameter>
  315. </syntax>
  316. <description>
  317. <para>Provides details about a specific FAX session. The response will include a common subset of
  318. the output from the CLI command 'fax show session &lt;session_number&gt;' for each technology. If the
  319. FAX technolgy used by this session does not include a handler for FAXSession, then this action
  320. will fail.</para>
  321. </description>
  322. </manager>
  323. <managerEvent language="en_US" name="FAXSession">
  324. <managerEventInstance class="EVENT_FLAG_REPORTING">
  325. <synopsis>Raised in response to FAXSession manager command</synopsis>
  326. <syntax>
  327. <parameter name="ActionID" required="false"/>
  328. <parameter name="SessionNumber">
  329. <para>The numerical identifier for this particular session</para>
  330. </parameter>
  331. <xi:include xpointer="xpointer(/docs/managerEvent[@name='FAXSessionsEntry']/managerEventInstance/syntax/parameter[@name='Operation'])" />
  332. <xi:include xpointer="xpointer(/docs/managerEvent[@name='FAXSessionsEntry']/managerEventInstance/syntax/parameter[@name='State'])" />
  333. <parameter name="ErrorCorrectionMode" required="false">
  334. <para>Whether error correcting mode is enabled for the FAX session. This field is not
  335. included when operation is 'V.21 Detect' or if operation is 'gateway' and state is
  336. 'Uninitialized'
  337. </para>
  338. <enumlist>
  339. <enum name="yes" />
  340. <enum name="no" />
  341. </enumlist>
  342. </parameter>
  343. <parameter name="DataRate" required="false">
  344. <para>Bit rate of the FAX. This field is not included when operation is 'V.21 Detect' or
  345. if operation is 'gateway' and state is 'Uninitialized'.</para>
  346. </parameter>
  347. <parameter name="ImageResolution" required="false">
  348. <para>Resolution of each page of the FAX. Will be in the format of X_RESxY_RES. This field
  349. is not included if the operation is anything other than Receive/Transmit.</para>
  350. </parameter>
  351. <parameter name="PageNumber" required="false">
  352. <para>Current number of pages transferred during this FAX session. May change as the FAX
  353. progresses. This field is not included when operation is 'V.21 Detect' or if operation is
  354. 'gateway' and state is 'Uninitialized'.</para>
  355. </parameter>
  356. <parameter name="FileName" required="false">
  357. <para>Filename of the image being sent/recieved for this FAX session. This field is not
  358. included if Operation isn't 'send' or 'receive'.</para>
  359. </parameter>
  360. <parameter name="PagesTransmitted" required="false">
  361. <para>Total number of pages sent during this session. This field is not included if
  362. Operation isn't 'send' or 'receive'. Will always be 0 for 'receive'.</para>
  363. </parameter>
  364. <parameter name="PagesReceived" required="false">
  365. <para>Total number of pages received during this session. This field is not included if
  366. Operation is not 'send' or 'receive'. Will be 0 for 'send'.</para>
  367. </parameter>
  368. <parameter name="TotalBadLines" required="false">
  369. <para>Total number of bad lines sent/recieved during this session. This field is not
  370. included if Operation is not 'send' or 'received'.</para>
  371. </parameter>
  372. </syntax>
  373. </managerEventInstance>
  374. </managerEvent>
  375. <manager name="FAXStats" language="en_US">
  376. <synopsis>
  377. Responds with fax statistics
  378. </synopsis>
  379. <syntax>
  380. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  381. </syntax>
  382. <description>
  383. <para>Provides FAX statistics including the number of active sessions, reserved sessions, completed
  384. sessions, failed sessions, and the number of receive/transmit attempts. This command provides all
  385. of the non-technology specific information provided by the CLI command 'fax show stats'</para>
  386. </description>
  387. </manager>
  388. <managerEvent language="en_US" name="FAXStats">
  389. <managerEventInstance class="EVENT_FLAG_REPORTING">
  390. <synopsis>Raised in response to FAXStats manager command</synopsis>
  391. <syntax>
  392. <parameter name="ActionID" required="false"/>
  393. <parameter name="CurrentSessions" required="true">
  394. <para>Number of active FAX sessions</para>
  395. </parameter>
  396. <parameter name="ReservedSessions" required="true">
  397. <para>Number of reserved FAX sessions</para>
  398. </parameter>
  399. <parameter name="TransmitAttempts" required="true">
  400. <para>Total FAX sessions for which Asterisk is/was the transmitter</para>
  401. </parameter>
  402. <parameter name="ReceiveAttempts" required="true">
  403. <para>Total FAX sessions for which Asterisk is/was the recipient</para>
  404. </parameter>
  405. <parameter name="CompletedFAXes" required="true">
  406. <para>Total FAX sessions which have been completed successfully</para>
  407. </parameter>
  408. <parameter name="FailedFAXes" required="true">
  409. <para>Total FAX sessions which failed to complete successfully</para>
  410. </parameter>
  411. </syntax>
  412. </managerEventInstance>
  413. </managerEvent>
  414. ***/
  415. static const char app_receivefax[] = "ReceiveFAX";
  416. static const char app_sendfax[] = "SendFAX";
  417. struct debug_info_history {
  418. unsigned int consec_frames;
  419. unsigned int consec_ms;
  420. unsigned char silence;
  421. };
  422. struct ast_fax_debug_info {
  423. struct timeval base_tv;
  424. struct debug_info_history c2s, s2c;
  425. struct ast_dsp *dsp;
  426. };
  427. /*! \brief used for gateway framehook */
  428. struct fax_gateway {
  429. /*! \brief FAX Session */
  430. struct ast_fax_session *s;
  431. struct ast_fax_session *peer_v21_session;
  432. struct ast_fax_session *chan_v21_session;
  433. /*! \brief reserved fax session token */
  434. struct ast_fax_tech_token *token;
  435. /*! \brief the start of our timeout counter */
  436. struct timeval timeout_start;
  437. /*! \brief framehook used in gateway mode */
  438. int framehook;
  439. /*! \brief bridged */
  440. int bridged:1;
  441. /*! \brief 1 if a v21 preamble has been detected */
  442. int detected_v21:1;
  443. /*! \brief a flag to track the state of our negotiation */
  444. enum ast_t38_state t38_state;
  445. /*! \brief original audio formats */
  446. struct ast_format *chan_read_format;
  447. struct ast_format *chan_write_format;
  448. struct ast_format *peer_read_format;
  449. struct ast_format *peer_write_format;
  450. };
  451. /*! \brief used for fax detect framehook */
  452. struct fax_detect {
  453. /*! \brief the start of our timeout counter */
  454. struct timeval timeout_start;
  455. /*! \brief faxdetect timeout */
  456. int timeout;
  457. /*! \brief DSP Processor */
  458. struct ast_dsp *dsp;
  459. /*! \brief original audio formats */
  460. struct ast_format *orig_format;
  461. /*! \brief fax session details */
  462. struct ast_fax_session_details *details;
  463. /*! \brief mode */
  464. int flags;
  465. };
  466. /*! \brief FAX Detect flags */
  467. #define FAX_DETECT_MODE_CNG (1 << 0)
  468. #define FAX_DETECT_MODE_T38 (1 << 1)
  469. #define FAX_DETECT_MODE_BOTH (FAX_DETECT_MODE_CNG | FAX_DETECT_MODE_T38)
  470. static int fax_logger_level = -1;
  471. /*! \brief maximum buckets for res_fax ao2 containers */
  472. #define FAX_MAXBUCKETS 10
  473. #define RES_FAX_TIMEOUT 10000
  474. #define FAX_GATEWAY_TIMEOUT RES_FAX_TIMEOUT
  475. /*! \brief The faxregistry is used to manage information and statistics for all FAX sessions. */
  476. static struct {
  477. /*! The number of active FAX sessions */
  478. int active_sessions;
  479. /*! The number of reserved FAX sessions */
  480. int reserved_sessions;
  481. /*! active sessions are astobj2 objects */
  482. struct ao2_container *container;
  483. /*! Total number of Tx FAX attempts */
  484. int fax_tx_attempts;
  485. /*! Total number of Rx FAX attempts */
  486. int fax_rx_attempts;
  487. /*! Number of successful FAX transmissions */
  488. int fax_complete;
  489. /*! Number of failed FAX transmissions */
  490. int fax_failures;
  491. /*! the next unique session name */
  492. int nextsessionname;
  493. } faxregistry;
  494. /*! \brief registered FAX technology modules are put into this list */
  495. struct fax_module {
  496. const struct ast_fax_tech *tech;
  497. AST_RWLIST_ENTRY(fax_module) list;
  498. };
  499. static AST_RWLIST_HEAD_STATIC(faxmodules, fax_module);
  500. #define RES_FAX_MINRATE 4800
  501. #define RES_FAX_MAXRATE 14400
  502. #define RES_FAX_STATUSEVENTS 0
  503. #define RES_FAX_MODEM (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V27 | AST_FAX_MODEM_V29)
  504. struct fax_options {
  505. enum ast_fax_modems modems;
  506. uint32_t statusevents:1;
  507. uint32_t ecm:1;
  508. unsigned int minrate;
  509. unsigned int maxrate;
  510. };
  511. static struct fax_options general_options;
  512. static const struct fax_options default_options = {
  513. .minrate = RES_FAX_MINRATE,
  514. .maxrate = RES_FAX_MAXRATE,
  515. .statusevents = RES_FAX_STATUSEVENTS,
  516. .modems = RES_FAX_MODEM,
  517. .ecm = AST_FAX_OPTFLAG_TRUE,
  518. };
  519. AST_RWLOCK_DEFINE_STATIC(options_lock);
  520. static void get_general_options(struct fax_options* options);
  521. static void set_general_options(const struct fax_options* options);
  522. static const char *config = "res_fax.conf";
  523. static int global_fax_debug = 0;
  524. enum {
  525. OPT_CALLEDMODE = (1 << 0),
  526. OPT_CALLERMODE = (1 << 1),
  527. OPT_DEBUG = (1 << 2),
  528. OPT_STATUS = (1 << 3),
  529. OPT_ALLOWAUDIO = (1 << 5),
  530. OPT_REQUEST_T38 = (1 << 6),
  531. OPT_FORCE_AUDIO = (1 << 7),
  532. };
  533. AST_APP_OPTIONS(fax_exec_options, BEGIN_OPTIONS
  534. AST_APP_OPTION('a', OPT_CALLEDMODE),
  535. AST_APP_OPTION('c', OPT_CALLERMODE),
  536. AST_APP_OPTION('d', OPT_DEBUG),
  537. AST_APP_OPTION('f', OPT_ALLOWAUDIO),
  538. AST_APP_OPTION('F', OPT_FORCE_AUDIO),
  539. AST_APP_OPTION('s', OPT_STATUS),
  540. AST_APP_OPTION('z', OPT_REQUEST_T38),
  541. END_OPTIONS);
  542. static void debug_check_frame_for_silence(struct ast_fax_session *s, unsigned int c2s, struct ast_frame *frame)
  543. {
  544. struct debug_info_history *history = c2s ? &s->debug_info->c2s : &s->debug_info->s2c;
  545. int dspsilence;
  546. unsigned int last_consec_frames, last_consec_ms;
  547. unsigned char wassil;
  548. struct timeval diff;
  549. diff = ast_tvsub(ast_tvnow(), s->debug_info->base_tv);
  550. ast_dsp_reset(s->debug_info->dsp);
  551. ast_dsp_silence(s->debug_info->dsp, frame, &dspsilence);
  552. wassil = history->silence;
  553. history->silence = (dspsilence != 0) ? 1 : 0;
  554. if (history->silence != wassil) {
  555. last_consec_frames = history->consec_frames;
  556. last_consec_ms = history->consec_ms;
  557. history->consec_frames = 0;
  558. history->consec_ms = 0;
  559. if ((last_consec_frames != 0)) {
  560. ast_verb(0, "Channel '%s' fax session '%u', [ %.3ld.%.6ld ], %s sent %u frames (%u ms) of %s.\n",
  561. s->channame, s->id, (long) diff.tv_sec, (long int) diff.tv_usec,
  562. (c2s) ? "channel" : "stack", last_consec_frames, last_consec_ms,
  563. (wassil) ? "silence" : "energy");
  564. }
  565. }
  566. history->consec_frames++;
  567. history->consec_ms += (frame->samples / 8);
  568. }
  569. static void destroy_callback(void *data)
  570. {
  571. if (data) {
  572. ao2_ref(data, -1);
  573. }
  574. }
  575. static void fixup_callback(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan);
  576. static const struct ast_datastore_info fax_datastore = {
  577. .type = "res_fax",
  578. .destroy = destroy_callback,
  579. .chan_fixup = fixup_callback,
  580. };
  581. static int fax_gateway_attach(struct ast_channel *chan, struct ast_fax_session_details *details);
  582. static int fax_detect_attach(struct ast_channel *chan, int timeout, int flags);
  583. static struct ast_fax_session_details *find_or_create_details(struct ast_channel *chan);
  584. /*! \brief Copies fax detection and gateway framehooks during masquerades
  585. *
  586. * \note must be called with both old_chan and new_chan locked. Since this
  587. * is only called by do_masquerade, that shouldn't be an issue.
  588. */
  589. static void fixup_callback(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan)
  590. {
  591. struct ast_fax_session_details *old_details = data;
  592. struct ast_datastore *datastore = ast_channel_datastore_find(old_chan, &fax_datastore, NULL);
  593. if (old_details->gateway_id >= 0) {
  594. struct ast_fax_session_details *new_details = find_or_create_details(new_chan);
  595. ast_framehook_detach(old_chan, old_details->gateway_id);
  596. fax_gateway_attach(new_chan, new_details);
  597. ao2_cleanup(new_details);
  598. }
  599. if (old_details->faxdetect_id >= 0) {
  600. ast_framehook_detach(old_chan, old_details->faxdetect_id);
  601. fax_detect_attach(new_chan, old_details->faxdetect_timeout, old_details->faxdetect_flags);
  602. }
  603. if (datastore) {
  604. ast_channel_datastore_remove(old_chan, datastore);
  605. ast_datastore_free(datastore);
  606. }
  607. }
  608. /*! \brief returns a reference counted pointer to a fax datastore, if it exists */
  609. static struct ast_fax_session_details *find_details(struct ast_channel *chan)
  610. {
  611. struct ast_fax_session_details *details;
  612. struct ast_datastore *datastore;
  613. ast_channel_lock(chan);
  614. if (!(datastore = ast_channel_datastore_find(chan, &fax_datastore, NULL))) {
  615. ast_channel_unlock(chan);
  616. return NULL;
  617. }
  618. if (!(details = datastore->data)) {
  619. ast_log(LOG_WARNING, "Huh? channel '%s' has a FAX datastore without data!\n", ast_channel_name(chan));
  620. ast_channel_unlock(chan);
  621. return NULL;
  622. }
  623. ao2_ref(details, 1);
  624. ast_channel_unlock(chan);
  625. return details;
  626. }
  627. /*! \brief destroy a FAX session details structure */
  628. static void destroy_session_details(void *details)
  629. {
  630. struct ast_fax_session_details *d = details;
  631. struct ast_fax_document *doc;
  632. while ((doc = AST_LIST_REMOVE_HEAD(&d->documents, next))) {
  633. ast_free(doc);
  634. }
  635. ast_string_field_free_memory(d);
  636. }
  637. /*! \brief create a FAX session details structure */
  638. static struct ast_fax_session_details *session_details_new(void)
  639. {
  640. struct ast_fax_session_details *d;
  641. struct fax_options options;
  642. if (!(d = ao2_alloc(sizeof(*d), destroy_session_details))) {
  643. return NULL;
  644. }
  645. if (ast_string_field_init(d, 512)) {
  646. ao2_ref(d, -1);
  647. return NULL;
  648. }
  649. get_general_options(&options);
  650. AST_LIST_HEAD_INIT_NOLOCK(&d->documents);
  651. /* These options need to be set to the configured default and may be overridden by
  652. * SendFAX, ReceiveFAX, or FAXOPT */
  653. d->option.request_t38 = AST_FAX_OPTFLAG_FALSE;
  654. d->option.send_cng = AST_FAX_OPTFLAG_FALSE;
  655. d->option.send_ced = AST_FAX_OPTFLAG_FALSE;
  656. d->option.ecm = options.ecm;
  657. d->option.statusevents = options.statusevents;
  658. d->modems = options.modems;
  659. d->minrate = options.minrate;
  660. d->maxrate = options.maxrate;
  661. d->gateway_id = -1;
  662. d->faxdetect_id = -1;
  663. d->gateway_timeout = 0;
  664. return d;
  665. }
  666. static struct ast_control_t38_parameters our_t38_parameters = {
  667. .version = 0,
  668. .max_ifp = 400,
  669. .rate = AST_T38_RATE_14400,
  670. .rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF,
  671. };
  672. static void t38_parameters_ast_to_fax(struct ast_fax_t38_parameters *dst, const struct ast_control_t38_parameters *src)
  673. {
  674. dst->version = src->version;
  675. dst->max_ifp = src->max_ifp;
  676. dst->rate = src->rate;
  677. dst->rate_management = src->rate_management;
  678. dst->fill_bit_removal = src->fill_bit_removal;
  679. dst->transcoding_mmr = src->transcoding_mmr;
  680. dst->transcoding_jbig = src->transcoding_jbig;
  681. }
  682. static void t38_parameters_fax_to_ast(struct ast_control_t38_parameters *dst, const struct ast_fax_t38_parameters *src)
  683. {
  684. dst->version = src->version;
  685. dst->max_ifp = src->max_ifp;
  686. dst->rate = src->rate;
  687. dst->rate_management = src->rate_management;
  688. dst->fill_bit_removal = src->fill_bit_removal;
  689. dst->transcoding_mmr = src->transcoding_mmr;
  690. dst->transcoding_jbig = src->transcoding_jbig;
  691. }
  692. /*! \brief returns a reference counted details structure from the channel's fax datastore. If the datastore
  693. * does not exist it will be created */
  694. static struct ast_fax_session_details *find_or_create_details(struct ast_channel *chan)
  695. {
  696. struct ast_fax_session_details *details;
  697. struct ast_datastore *datastore;
  698. if ((details = find_details(chan))) {
  699. return details;
  700. }
  701. /* channel does not have one so we must create one */
  702. if (!(details = session_details_new())) {
  703. ast_log(LOG_WARNING, "channel '%s' can't get a FAX details structure for the datastore!\n", ast_channel_name(chan));
  704. return NULL;
  705. }
  706. if (!(datastore = ast_datastore_alloc(&fax_datastore, NULL))) {
  707. ao2_ref(details, -1);
  708. ast_log(LOG_WARNING, "channel '%s' can't get a datastore!\n", ast_channel_name(chan));
  709. return NULL;
  710. }
  711. /* add the datastore to the channel and increment the refcount */
  712. datastore->data = details;
  713. /* initialize default T.38 parameters */
  714. t38_parameters_ast_to_fax(&details->our_t38_parameters, &our_t38_parameters);
  715. t38_parameters_ast_to_fax(&details->their_t38_parameters, &our_t38_parameters);
  716. ao2_ref(details, 1);
  717. ast_channel_lock(chan);
  718. ast_channel_datastore_add(chan, datastore);
  719. ast_channel_unlock(chan);
  720. return details;
  721. }
  722. unsigned int ast_fax_maxrate(void)
  723. {
  724. struct fax_options options;
  725. get_general_options(&options);
  726. return options.maxrate;
  727. }
  728. unsigned int ast_fax_minrate(void)
  729. {
  730. struct fax_options options;
  731. get_general_options(&options);
  732. return options.minrate;
  733. }
  734. static int update_modem_bits(enum ast_fax_modems *bits, const char *value)
  735. {
  736. char *m[5], *tok, *v = (char *)value;
  737. int i = 0, j;
  738. if (!strchr(v, ',')) {
  739. m[i++] = v;
  740. m[i] = NULL;
  741. } else {
  742. tok = strtok(v, ", ");
  743. while (tok && i < ARRAY_LEN(m) - 1) {
  744. m[i++] = tok;
  745. tok = strtok(NULL, ", ");
  746. }
  747. m[i] = NULL;
  748. }
  749. *bits = 0;
  750. for (j = 0; j < i; j++) {
  751. if (!strcasecmp(m[j], "v17")) {
  752. *bits |= AST_FAX_MODEM_V17;
  753. } else if (!strcasecmp(m[j], "v27")) {
  754. *bits |= AST_FAX_MODEM_V27;
  755. } else if (!strcasecmp(m[j], "v29")) {
  756. *bits |= AST_FAX_MODEM_V29;
  757. } else if (!strcasecmp(m[j], "v34")) {
  758. *bits |= AST_FAX_MODEM_V34;
  759. } else {
  760. ast_log(LOG_WARNING, "ignoring invalid modem setting: '%s', valid options {v17 | v27 | v29 | v34}\n", m[j]);
  761. }
  762. }
  763. return 0;
  764. }
  765. static char *ast_fax_caps_to_str(enum ast_fax_capabilities caps, char *buf, size_t bufsize)
  766. {
  767. char *out = buf;
  768. size_t size = bufsize;
  769. int first = 1;
  770. if (caps & AST_FAX_TECH_SEND) {
  771. if (!first) {
  772. ast_build_string(&buf, &size, ",");
  773. }
  774. ast_build_string(&buf, &size, "SEND");
  775. first = 0;
  776. }
  777. if (caps & AST_FAX_TECH_RECEIVE) {
  778. if (!first) {
  779. ast_build_string(&buf, &size, ",");
  780. }
  781. ast_build_string(&buf, &size, "RECEIVE");
  782. first = 0;
  783. }
  784. if (caps & AST_FAX_TECH_AUDIO) {
  785. if (!first) {
  786. ast_build_string(&buf, &size, ",");
  787. }
  788. ast_build_string(&buf, &size, "AUDIO");
  789. first = 0;
  790. }
  791. if (caps & AST_FAX_TECH_T38) {
  792. if (!first) {
  793. ast_build_string(&buf, &size, ",");
  794. }
  795. ast_build_string(&buf, &size, "T38");
  796. first = 0;
  797. }
  798. if (caps & AST_FAX_TECH_MULTI_DOC) {
  799. if (!first) {
  800. ast_build_string(&buf, &size, ",");
  801. }
  802. ast_build_string(&buf, &size, "MULTI_DOC");
  803. first = 0;
  804. }
  805. if (caps & AST_FAX_TECH_GATEWAY) {
  806. if (!first) {
  807. ast_build_string(&buf, &size, ",");
  808. }
  809. ast_build_string(&buf, &size, "GATEWAY");
  810. first = 0;
  811. }
  812. if (caps & AST_FAX_TECH_V21_DETECT) {
  813. if (!first) {
  814. ast_build_string(&buf, &size, ",");
  815. }
  816. ast_build_string(&buf, &size, "V21");
  817. first = 0;
  818. }
  819. return out;
  820. }
  821. static int ast_fax_modem_to_str(enum ast_fax_modems bits, char *tbuf, size_t bufsize)
  822. {
  823. int count = 0;
  824. if (bits & AST_FAX_MODEM_V17) {
  825. strcat(tbuf, "V17");
  826. count++;
  827. }
  828. if (bits & AST_FAX_MODEM_V27) {
  829. if (count) {
  830. strcat(tbuf, ",");
  831. }
  832. strcat(tbuf, "V27");
  833. count++;
  834. }
  835. if (bits & AST_FAX_MODEM_V29) {
  836. if (count) {
  837. strcat(tbuf, ",");
  838. }
  839. strcat(tbuf, "V29");
  840. count++;
  841. }
  842. if (bits & AST_FAX_MODEM_V34) {
  843. if (count) {
  844. strcat(tbuf, ",");
  845. }
  846. strcat(tbuf, "V34");
  847. count++;
  848. }
  849. return 0;
  850. }
  851. static int check_modem_rate(enum ast_fax_modems modems, unsigned int rate)
  852. {
  853. switch (rate) {
  854. case 2400:
  855. if (!(modems & (AST_FAX_MODEM_V34))) {
  856. return 1;
  857. }
  858. break;
  859. case 4800:
  860. if (!(modems & (AST_FAX_MODEM_V27 | AST_FAX_MODEM_V34))) {
  861. return 1;
  862. }
  863. break;
  864. case 7200:
  865. if (!(modems & (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V29 | AST_FAX_MODEM_V34))) {
  866. return 1;
  867. }
  868. break;
  869. case 9600:
  870. if (!(modems & (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V27 | AST_FAX_MODEM_V29 | AST_FAX_MODEM_V34))) {
  871. return 1;
  872. }
  873. break;
  874. case 12000:
  875. case 14400:
  876. if (!(modems & (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V34))) {
  877. return 1;
  878. }
  879. break;
  880. case 28800:
  881. case 33600:
  882. if (!(modems & AST_FAX_MODEM_V34)) {
  883. return 1;
  884. }
  885. break;
  886. default:
  887. /* this should never happen */
  888. return 1;
  889. }
  890. return 0;
  891. }
  892. /*! \brief register a FAX technology module */
  893. int ast_fax_tech_register(struct ast_fax_tech *tech)
  894. {
  895. struct fax_module *fax;
  896. if (!(fax = ast_calloc(1, sizeof(*fax)))) {
  897. return -1;
  898. }
  899. fax->tech = tech;
  900. AST_RWLIST_WRLOCK(&faxmodules);
  901. AST_RWLIST_INSERT_TAIL(&faxmodules, fax, list);
  902. AST_RWLIST_UNLOCK(&faxmodules);
  903. ast_module_ref(ast_module_info->self);
  904. ast_verb(3, "Registered handler for '%s' (%s)\n", fax->tech->type, fax->tech->description);
  905. return 0;
  906. }
  907. /*! \brief unregister a FAX technology module */
  908. void ast_fax_tech_unregister(struct ast_fax_tech *tech)
  909. {
  910. struct fax_module *fax;
  911. ast_verb(3, "Unregistering FAX module type '%s'\n", tech->type);
  912. AST_RWLIST_WRLOCK(&faxmodules);
  913. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&faxmodules, fax, list) {
  914. if (fax->tech != tech) {
  915. continue;
  916. }
  917. AST_RWLIST_REMOVE_CURRENT(list);
  918. ast_module_unref(ast_module_info->self);
  919. ast_free(fax);
  920. ast_verb(4, "Unregistered FAX module type '%s'\n", tech->type);
  921. break;
  922. }
  923. AST_RWLIST_TRAVERSE_SAFE_END;
  924. AST_RWLIST_UNLOCK(&faxmodules);
  925. }
  926. /*! \brief convert a ast_fax_state to a string */
  927. const char *ast_fax_state_to_str(enum ast_fax_state state)
  928. {
  929. switch (state) {
  930. case AST_FAX_STATE_UNINITIALIZED:
  931. return "Uninitialized";
  932. case AST_FAX_STATE_INITIALIZED:
  933. return "Initialized";
  934. case AST_FAX_STATE_OPEN:
  935. return "Open";
  936. case AST_FAX_STATE_ACTIVE:
  937. return "Active";
  938. case AST_FAX_STATE_COMPLETE:
  939. return "Complete";
  940. case AST_FAX_STATE_RESERVED:
  941. return "Reserved";
  942. case AST_FAX_STATE_INACTIVE:
  943. return "Inactive";
  944. default:
  945. ast_log(LOG_WARNING, "unhandled FAX state: %u\n", state);
  946. return "Unknown";
  947. }
  948. }
  949. void ast_fax_log(int level, const char *file, const int line, const char *function, const char *msg)
  950. {
  951. if (fax_logger_level != -1) {
  952. ast_log_dynamic_level(fax_logger_level, "%s", msg);
  953. } else {
  954. ast_log(level, file, line, function, "%s", msg);
  955. }
  956. }
  957. /*! \brief convert a rate string to a rate */
  958. static unsigned int fax_rate_str_to_int(const char *ratestr)
  959. {
  960. int rate;
  961. if (sscanf(ratestr, "%d", &rate) != 1) {
  962. ast_log(LOG_ERROR, "failed to sscanf '%s' to rate\n", ratestr);
  963. return 0;
  964. }
  965. switch (rate) {
  966. case 2400:
  967. case 4800:
  968. case 7200:
  969. case 9600:
  970. case 12000:
  971. case 14400:
  972. case 28800:
  973. case 33600:
  974. return rate;
  975. default:
  976. ast_log(LOG_WARNING, "ignoring invalid rate '%s'. Valid options are {2400 | 4800 | 7200 | 9600 | 12000 | 14400 | 28800 | 33600}\n", ratestr);
  977. return 0;
  978. }
  979. }
  980. /*! \brief Release a session token.
  981. * \param s a session returned from fax_session_reserve()
  982. * \param token a token generated from fax_session_reserve()
  983. *
  984. * This function releases the given token and marks the given session as no
  985. * longer reserved. It is safe to call on a session that is not actually
  986. * reserved and with a NULL token. This is so that sessions returned by
  987. * technologies that do not support reserved sessions don't require extra logic
  988. * to handle.
  989. *
  990. * \note This function DOES NOT release the given fax session, only the given
  991. * token.
  992. */
  993. static void fax_session_release(struct ast_fax_session *s, struct ast_fax_tech_token *token)
  994. {
  995. if (token) {
  996. s->tech->release_token(token);
  997. }
  998. if (s->state == AST_FAX_STATE_RESERVED) {
  999. ast_atomic_fetchadd_int(&faxregistry.reserved_sessions, -1);
  1000. s->state = AST_FAX_STATE_INACTIVE;
  1001. }
  1002. }
  1003. /*! \brief destroy a FAX session structure */
  1004. static void destroy_session(void *session)
  1005. {
  1006. struct ast_fax_session *s = session;
  1007. if (s->tech) {
  1008. fax_session_release(s, NULL);
  1009. if (s->tech_pvt) {
  1010. s->tech->destroy_session(s);
  1011. }
  1012. ast_module_unref(s->tech->module);
  1013. }
  1014. if (s->details) {
  1015. if (s->details->caps & AST_FAX_TECH_GATEWAY) {
  1016. s->details->caps &= ~AST_FAX_TECH_GATEWAY;
  1017. }
  1018. ao2_ref(s->details, -1);
  1019. }
  1020. if (s->debug_info) {
  1021. ast_dsp_free(s->debug_info->dsp);
  1022. ast_free(s->debug_info);
  1023. }
  1024. if (s->smoother) {
  1025. ast_smoother_free(s->smoother);
  1026. }
  1027. if (s->state != AST_FAX_STATE_INACTIVE) {
  1028. ast_atomic_fetchadd_int(&faxregistry.active_sessions, -1);
  1029. }
  1030. ast_free(s->channame);
  1031. ast_free(s->chan_uniqueid);
  1032. }
  1033. /*! \brief Reserve a fax session.
  1034. * \param details the fax session details
  1035. * \param token a pointer to a place to store a token to be passed to fax_session_new() later
  1036. *
  1037. * This function reserves a fax session for use later. If the selected fax
  1038. * technology does not support reserving sessions a session will still be
  1039. * returned but token will not be set.
  1040. *
  1041. * \note The reference returned by this function does not get consumed by
  1042. * fax_session_new() and must always be dereferenced separately.
  1043. *
  1044. * \return NULL or an uninitialized and possibly reserved session
  1045. */
  1046. static struct ast_fax_session *fax_session_reserve(struct ast_fax_session_details *details, struct ast_fax_tech_token **token)
  1047. {
  1048. struct ast_fax_session *s;
  1049. struct fax_module *faxmod;
  1050. if (!(s = ao2_alloc(sizeof(*s), destroy_session))) {
  1051. return NULL;
  1052. }
  1053. s->state = AST_FAX_STATE_INACTIVE;
  1054. s->details = details;
  1055. ao2_ref(s->details, 1);
  1056. /* locate a FAX technology module that can handle said requirements
  1057. * Note: the requirements have not yet been finalized as T.38
  1058. * negotiation has not yet occured. */
  1059. AST_RWLIST_RDLOCK(&faxmodules);
  1060. AST_RWLIST_TRAVERSE(&faxmodules, faxmod, list) {
  1061. if ((faxmod->tech->caps & details->caps) != details->caps) {
  1062. continue;
  1063. }
  1064. ast_debug(4, "Reserving a FAX session from '%s'.\n", faxmod->tech->description);
  1065. ast_module_ref(faxmod->tech->module);
  1066. s->tech = faxmod->tech;
  1067. break;
  1068. }
  1069. AST_RWLIST_UNLOCK(&faxmodules);
  1070. if (!faxmod) {
  1071. char caps[128] = "";
  1072. ast_log(LOG_ERROR, "Could not locate a FAX technology module with capabilities (%s)\n", ast_fax_caps_to_str(details->caps, caps, sizeof(caps)));
  1073. ao2_ref(s, -1);
  1074. return NULL;
  1075. }
  1076. if (!s->tech->reserve_session) {
  1077. ast_debug(1, "Selected FAX technology module (%s) does not support reserving sessions.\n", s->tech->description);
  1078. return s;
  1079. }
  1080. if (!(*token = s->tech->reserve_session(s))) {
  1081. ao2_ref(s, -1);
  1082. return NULL;
  1083. }
  1084. s->state = AST_FAX_STATE_RESERVED;
  1085. ast_atomic_fetchadd_int(&faxregistry.reserved_sessions, 1);
  1086. return s;
  1087. }
  1088. /*! \brief create a FAX session
  1089. *
  1090. * \param details details for the session
  1091. * \param chan the channel the session will run on
  1092. * \param reserved a reserved session to base this session on (can be NULL)
  1093. * \param token the token for a reserved session (can be NULL)
  1094. *
  1095. * Create a new fax session based on the given details structure.
  1096. *
  1097. * \note The given token is always consumed (by tech->new_session() or by
  1098. * fax_session_release() in the event of a failure). The given reference to a
  1099. * reserved session is never consumed and must be dereferenced separately from
  1100. * the reference returned by this function.
  1101. *
  1102. * \return NULL or a reference to a new fax session
  1103. */
  1104. static struct ast_fax_session *fax_session_new(struct ast_fax_session_details *details, struct ast_channel *chan, struct ast_fax_session *reserved, struct ast_fax_tech_token *token)
  1105. {
  1106. struct ast_fax_session *s = NULL;
  1107. struct fax_module *faxmod;
  1108. if (reserved) {
  1109. s = reserved;
  1110. ao2_ref(reserved, +1);
  1111. ao2_unlink(faxregistry.container, reserved);
  1112. /* NOTE: we don't consume the reference to the reserved
  1113. * session. The session returned from fax_session_new() is a
  1114. * new reference and must be derefed in addition to the
  1115. * reserved session.
  1116. */
  1117. if (s->state == AST_FAX_STATE_RESERVED) {
  1118. ast_atomic_fetchadd_int(&faxregistry.reserved_sessions, -1);
  1119. s->state = AST_FAX_STATE_UNINITIALIZED;
  1120. }
  1121. }
  1122. if (!s && !(s = ao2_alloc(sizeof(*s), destroy_session))) {
  1123. return NULL;
  1124. }
  1125. ast_atomic_fetchadd_int(&faxregistry.active_sessions, 1);
  1126. s->state = AST_FAX_STATE_UNINITIALIZED;
  1127. if (details->option.debug && (details->caps & AST_FAX_TECH_AUDIO)) {
  1128. if (!(s->debug_info = ast_calloc(1, sizeof(*(s->debug_info))))) {
  1129. fax_session_release(s, token);
  1130. ao2_ref(s, -1);
  1131. return NULL;
  1132. }
  1133. if (!(s->debug_info->dsp = ast_dsp_new())) {
  1134. ast_free(s->debug_info);
  1135. s->debug_info = NULL;
  1136. fax_session_release(s, token);
  1137. ao2_ref(s, -1);
  1138. return NULL;
  1139. }
  1140. ast_dsp_set_threshold(s->debug_info->dsp, 128);
  1141. }
  1142. if (!(s->channame = ast_strdup(ast_channel_name(chan)))) {
  1143. fax_session_release(s, token);
  1144. ao2_ref(s, -1);
  1145. return NULL;
  1146. }
  1147. if (!(s->chan_uniqueid = ast_strdup(ast_channel_uniqueid(chan)))) {
  1148. fax_session_release(s, token);
  1149. ao2_ref(s, -1);
  1150. return NULL;
  1151. }
  1152. s->chan = chan;
  1153. if (!s->details) {
  1154. s->details = details;
  1155. ao2_ref(s->details, 1);
  1156. }
  1157. details->id = s->id = ast_atomic_fetchadd_int(&faxregistry.nextsessionname, 1);
  1158. if (!token) {
  1159. /* locate a FAX technology module that can handle said requirements */
  1160. AST_RWLIST_RDLOCK(&faxmodules);
  1161. AST_RWLIST_TRAVERSE(&faxmodules, faxmod, list) {
  1162. if ((faxmod->tech->caps & details->caps) != details->caps) {
  1163. continue;
  1164. }
  1165. ast_debug(4, "Requesting a new FAX session from '%s'.\n", faxmod->tech->description);
  1166. ast_module_ref(faxmod->tech->module);
  1167. if (reserved) {
  1168. /* Balance module ref from reserved session */
  1169. ast_module_unref(reserved->tech->module);
  1170. }
  1171. s->tech = faxmod->tech;
  1172. break;
  1173. }
  1174. AST_RWLIST_UNLOCK(&faxmodules);
  1175. if (!faxmod) {
  1176. char caps[128] = "";
  1177. ast_log(LOG_ERROR, "Could not locate a FAX technology module with capabilities (%s)\n", ast_fax_caps_to_str(details->caps, caps, sizeof(caps)));
  1178. ao2_ref(s, -1);
  1179. return NULL;
  1180. }
  1181. }
  1182. if (!(s->tech_pvt = s->tech->new_session(s, token))) {
  1183. ast_log(LOG_ERROR, "FAX session failed to initialize.\n");
  1184. ao2_ref(s, -1);
  1185. return NULL;
  1186. }
  1187. /* link the session to the session container */
  1188. if (!(ao2_link(faxregistry.container, s))) {
  1189. ast_log(LOG_ERROR, "failed to add FAX session '%u' to container.\n", s->id);
  1190. ao2_ref(s, -1);
  1191. return NULL;
  1192. }
  1193. ast_debug(4, "channel '%s' using FAX session '%u'\n", s->channame, s->id);
  1194. return s;
  1195. }
  1196. /*!
  1197. * \internal
  1198. * \brief Convert the filenames in a fax session into a JSON array
  1199. * \retval NULL on error
  1200. * \retval A \ref ast_json array on success
  1201. */
  1202. static struct ast_json *generate_filenames_json(struct ast_fax_session_details *details)
  1203. {
  1204. RAII_VAR(struct ast_json *, json_array, ast_json_array_create(), ast_json_unref);
  1205. struct ast_fax_document *doc;
  1206. if (!details || !json_array) {
  1207. return NULL;
  1208. }
  1209. /* don't process empty lists */
  1210. if (AST_LIST_EMPTY(&details->documents)) {
  1211. return NULL;
  1212. }
  1213. AST_LIST_TRAVERSE(&details->documents, doc, next) {
  1214. struct ast_json *entry = ast_json_string_create(doc->filename);
  1215. if (!entry) {
  1216. return NULL;
  1217. }
  1218. if (ast_json_array_append(json_array, entry)) {
  1219. return NULL;
  1220. }
  1221. }
  1222. ast_json_ref(json_array);
  1223. return json_array;
  1224. }
  1225. /* \brief Generate a string of filenames using the given prefix and separator.
  1226. * \param details the fax session details
  1227. * \param prefix the prefix to each filename
  1228. * \param separator the separator between filenames
  1229. *
  1230. * This function generates a string of filenames from the given details
  1231. * structure and using the given prefix and separator.
  1232. *
  1233. * \retval NULL there was an error generating the string
  1234. * \return the string generated string
  1235. */
  1236. static char *generate_filenames_string(struct ast_fax_session_details *details, char *prefix, char *separator)
  1237. {
  1238. char *filenames, *c;
  1239. size_t size = 0;
  1240. int first = 1;
  1241. struct ast_fax_document *doc;
  1242. /* don't process empty lists */
  1243. if (AST_LIST_EMPTY(&details->documents)) {
  1244. return ast_strdup("");
  1245. }
  1246. /* Calculate the total length of all of the file names */
  1247. AST_LIST_TRAVERSE(&details->documents, doc, next) {
  1248. size += strlen(separator) + strlen(prefix) + strlen(doc->filename);
  1249. }
  1250. size += 1; /* add space for the terminating null */
  1251. if (!(filenames = ast_malloc(size))) {
  1252. return NULL;
  1253. }
  1254. c = filenames;
  1255. ast_build_string(&c, &size, "%s%s", prefix, AST_LIST_FIRST(&details->documents)->filename);
  1256. AST_LIST_TRAVERSE(&details->documents, doc, next) {
  1257. if (first) {
  1258. first = 0;
  1259. continue;
  1260. }
  1261. ast_build_string(&c, &size, "%s%s%s", separator, prefix, doc->filename);
  1262. }
  1263. return filenames;
  1264. }
  1265. /*! \brief send a FAX status manager event */
  1266. static int report_fax_status(struct ast_channel *chan, struct ast_fax_session_details *details, const char *status)
  1267. {
  1268. RAII_VAR(struct ast_json *, json_object, NULL, ast_json_unref);
  1269. RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
  1270. struct ast_json *json_filenames = NULL;
  1271. if (!details->option.statusevents) {
  1272. return 0;
  1273. }
  1274. json_filenames = generate_filenames_json(details);
  1275. if (!json_filenames) {
  1276. return -1;
  1277. }
  1278. json_object = ast_json_pack("{s: s, s: s, s: s, s: s, s: o}",
  1279. "type", "status",
  1280. "operation", (details->caps & AST_FAX_TECH_GATEWAY) ? "gateway" : (details->caps & AST_FAX_TECH_RECEIVE) ? "receive" : "send",
  1281. "status", status,
  1282. "local_station_id", details->localstationid,
  1283. "filenames", json_filenames);
  1284. if (!json_object) {
  1285. return -1;
  1286. }
  1287. {
  1288. SCOPED_CHANNELLOCK(lock, chan);
  1289. message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), ast_channel_fax_type(), json_object);
  1290. if (!message) {
  1291. return -1;
  1292. }
  1293. stasis_publish(ast_channel_topic(chan), message);
  1294. }
  1295. return 0;
  1296. }
  1297. /*! \brief Set fax related channel variables. */
  1298. static void set_channel_variables(struct ast_channel *chan, struct ast_fax_session_details *details)
  1299. {
  1300. char buf[10];
  1301. pbx_builtin_setvar_helper(chan, "FAXSTATUS", S_OR(details->result, NULL));
  1302. pbx_builtin_setvar_helper(chan, "FAXERROR", S_OR(details->error, NULL));
  1303. pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", S_OR(details->resultstr, NULL));
  1304. pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", S_OR(details->remotestationid, NULL));
  1305. pbx_builtin_setvar_helper(chan, "LOCALSTATIONID", S_OR(details->localstationid, NULL));
  1306. pbx_builtin_setvar_helper(chan, "FAXBITRATE", S_OR(details->transfer_rate, NULL));
  1307. pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", S_OR(details->resolution, NULL));
  1308. snprintf(buf, sizeof(buf), "%u", details->pages_transferred);
  1309. pbx_builtin_setvar_helper(chan, "FAXPAGES", buf);
  1310. }
  1311. #define GENERIC_FAX_EXEC_SET_VARS(fax, chan, errorstr, reason) \
  1312. do { \
  1313. if (ast_strlen_zero(fax->details->result)) \
  1314. ast_string_field_set(fax->details, result, "FAILED"); \
  1315. if (ast_strlen_zero(fax->details->resultstr)) \
  1316. ast_string_field_set(fax->details, resultstr, reason); \
  1317. if (ast_strlen_zero(fax->details->error)) \
  1318. ast_string_field_set(fax->details, error, errorstr); \
  1319. set_channel_variables(chan, fax->details); \
  1320. } while (0)
  1321. #define GENERIC_FAX_EXEC_ERROR_QUIET(fax, chan, errorstr, reason) \
  1322. do { \
  1323. GENERIC_FAX_EXEC_SET_VARS(fax, chan, errorstr, reason); \
  1324. } while (0)
  1325. #define GENERIC_FAX_EXEC_ERROR(fax, chan, errorstr, reason) \
  1326. do { \
  1327. ast_log(LOG_ERROR, "channel '%s' FAX session '%u' failure, reason: '%s' (%s)\n", ast_channel_name(chan), fax->id, reason, errorstr); \
  1328. GENERIC_FAX_EXEC_ERROR_QUIET(fax, chan, errorstr, reason); \
  1329. } while (0)
  1330. static int set_fax_t38_caps(struct ast_channel *chan, struct ast_fax_session_details *details)
  1331. {
  1332. switch (ast_channel_get_t38_state(chan)) {
  1333. case T38_STATE_UNKNOWN:
  1334. details->caps |= AST_FAX_TECH_T38;
  1335. break;
  1336. case T38_STATE_REJECTED:
  1337. case T38_STATE_UNAVAILABLE:
  1338. details->caps |= AST_FAX_TECH_AUDIO;
  1339. break;
  1340. case T38_STATE_NEGOTIATED:
  1341. /* already in T.38 mode? This should not happen. */
  1342. case T38_STATE_NEGOTIATING: {
  1343. /* the other end already sent us a T.38 reinvite, so we need to prod the channel
  1344. * driver into resending their parameters to us if it supports doing so... if
  1345. * not, we can't proceed, because we can't create a proper reply without them.
  1346. * if it does work, the channel driver will send an AST_CONTROL_T38_PARAMETERS
  1347. * with a request of AST_T38_REQUEST_NEGOTIATE, which will be read by the function
  1348. * that gets called after this one completes
  1349. */
  1350. struct ast_control_t38_parameters parameters = { .request_response = AST_T38_REQUEST_PARMS, };
  1351. if (ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters)) != AST_T38_REQUEST_PARMS) {
  1352. ast_log(LOG_ERROR, "channel '%s' is in an unsupported T.38 negotiation state, cannot continue.\n", ast_channel_name(chan));
  1353. return -1;
  1354. }
  1355. details->caps |= AST_FAX_TECH_T38;
  1356. break;
  1357. }
  1358. default:
  1359. ast_log(LOG_ERROR, "channel '%s' is in an unsupported T.38 negotiation state, cannot continue.\n", ast_channel_name(chan));
  1360. return -1;
  1361. }
  1362. return 0;
  1363. }
  1364. static int disable_t38(struct ast_channel *chan)
  1365. {
  1366. int timeout_ms;
  1367. struct ast_frame *frame = NULL;
  1368. struct ast_control_t38_parameters t38_parameters = { .request_response = AST_T38_REQUEST_TERMINATE, };
  1369. struct timeval start;
  1370. int ms;
  1371. ast_debug(1, "Shutting down T.38 on %s\n", ast_channel_name(chan));
  1372. if (ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0) {
  1373. ast_debug(1, "error while disabling T.38 on channel '%s'\n", ast_channel_name(chan));
  1374. return -1;
  1375. }
  1376. /* wait up to five seconds for negotiation to complete */
  1377. timeout_ms = 5000;
  1378. start = ast_tvnow();
  1379. while ((ms = ast_remaining_ms(start, timeout_ms))) {
  1380. ms = ast_waitfor(chan, ms);
  1381. if (ms == 0) {
  1382. break;
  1383. }
  1384. if (ms < 0) {
  1385. ast_debug(1, "error while disabling T.38 on channel '%s'\n", ast_channel_name(chan));
  1386. return -1;
  1387. }
  1388. if (!(frame = ast_read(chan))) {
  1389. return -1;
  1390. }
  1391. if ((frame->frametype == AST_FRAME_CONTROL) &&
  1392. (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
  1393. (frame->datalen == sizeof(t38_parameters))) {
  1394. struct ast_control_t38_parameters *parameters = frame->data.ptr;
  1395. switch (parameters->request_response) {
  1396. case AST_T38_TERMINATED:
  1397. ast_debug(1, "Shut down T.38 on %s\n", ast_channel_name(chan));
  1398. break;
  1399. case AST_T38_REFUSED:
  1400. ast_log(LOG_WARNING, "channel '%s' refused to disable T.38\n", ast_channel_name(chan));
  1401. ast_frfree(frame);
  1402. return -1;
  1403. default:
  1404. ast_log(LOG_ERROR, "channel '%s' failed to disable T.38\n", ast_channel_name(chan));
  1405. ast_frfree(frame);
  1406. return -1;
  1407. }
  1408. ast_frfree(frame);
  1409. break;
  1410. }
  1411. ast_frfree(frame);
  1412. }
  1413. if (ms == 0) { /* all done, nothing happened */
  1414. ast_debug(1, "channel '%s' timed-out during T.38 shutdown\n", ast_channel_name(chan));
  1415. }
  1416. return 0;
  1417. }
  1418. /*! \brief this is the generic FAX session handling function */
  1419. static int generic_fax_exec(struct ast_channel *chan, struct ast_fax_session_details *details, struct ast_fax_session *reserved, struct ast_fax_tech_token *token)
  1420. {
  1421. int ms;
  1422. int timeout = RES_FAX_TIMEOUT;
  1423. int chancount;
  1424. unsigned int expected_frametype = -1;
  1425. struct ast_frame_subclass expected_framesubclass = { .integer = 0, };
  1426. unsigned int t38negotiated = (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED);
  1427. struct ast_control_t38_parameters t38_parameters;
  1428. const char *tempvar;
  1429. struct ast_fax_session *fax = NULL;
  1430. struct ast_frame *frame = NULL;
  1431. struct ast_channel *c = chan;
  1432. RAII_VAR(struct ast_format *, orig_write_format, NULL, ao2_cleanup);
  1433. RAII_VAR(struct ast_format *, orig_read_format, NULL, ao2_cleanup);
  1434. int remaining_time;
  1435. struct timeval start;
  1436. chancount = 1;
  1437. /* create the FAX session */
  1438. if (!(fax = fax_session_new(details, chan, reserved, token))) {
  1439. ast_log(LOG_ERROR, "Can't create a FAX session, FAX attempt failed.\n");
  1440. report_fax_status(chan, details, "No Available Resource");
  1441. return -1;
  1442. }
  1443. ast_channel_lock(chan);
  1444. /* update session details */
  1445. if (ast_strlen_zero(details->headerinfo) && (tempvar = pbx_builtin_getvar_helper(chan, "LOCALHEADERINFO"))) {
  1446. ast_string_field_set(details, headerinfo, tempvar);
  1447. }
  1448. if (ast_strlen_zero(details->localstationid)) {
  1449. tempvar = pbx_builtin_getvar_helper(chan, "LOCALSTATIONID");
  1450. ast_string_field_set(details, localstationid, tempvar ? tempvar : "unknown");
  1451. }
  1452. ast_channel_unlock(chan);
  1453. report_fax_status(chan, details, "Allocating Resources");
  1454. if (details->caps & AST_FAX_TECH_AUDIO) {
  1455. expected_frametype = AST_FRAME_VOICE;
  1456. expected_framesubclass.format = ast_format_slin;
  1457. orig_write_format = ao2_bump(ast_channel_writeformat(chan));
  1458. if (ast_set_write_format(chan, ast_format_slin) < 0) {
  1459. ast_log(LOG_ERROR, "channel '%s' failed to set write format to signed linear'.\n", ast_channel_name(chan));
  1460. ao2_lock(faxregistry.container);
  1461. ao2_unlink(faxregistry.container, fax);
  1462. ao2_unlock(faxregistry.container);
  1463. ao2_ref(fax, -1);
  1464. ast_channel_unlock(chan);
  1465. return -1;
  1466. }
  1467. orig_read_format = ao2_bump(ast_channel_readformat(chan));
  1468. if (ast_set_read_format(chan, ast_format_slin) < 0) {
  1469. ast_log(LOG_ERROR, "channel '%s' failed to set read format to signed linear.\n", ast_channel_name(chan));
  1470. ao2_lock(faxregistry.container);
  1471. ao2_unlink(faxregistry.container, fax);
  1472. ao2_unlock(faxregistry.container);
  1473. ao2_ref(fax, -1);
  1474. ast_channel_unlock(chan);
  1475. return -1;
  1476. }
  1477. if (fax->smoother) {
  1478. ast_smoother_free(fax->smoother);
  1479. fax->smoother = NULL;
  1480. }
  1481. if (!(fax->smoother = ast_smoother_new(320))) {
  1482. ast_log(LOG_WARNING, "Channel '%s' FAX session '%u' failed to obtain a smoother.\n", ast_channel_name(chan), fax->id);
  1483. }
  1484. } else {
  1485. expected_frametype = AST_FRAME_MODEM;
  1486. expected_framesubclass.integer = AST_MODEM_T38;
  1487. }
  1488. if (fax->debug_info) {
  1489. fax->debug_info->base_tv = ast_tvnow();
  1490. }
  1491. /* reset our result fields just in case the fax tech driver wants to
  1492. * set custom error messages */
  1493. ast_string_field_set(details, result, "");
  1494. ast_string_field_set(details, resultstr, "");
  1495. ast_string_field_set(details, error, "");
  1496. set_channel_variables(chan, details);
  1497. if (fax->tech->start_session(fax) < 0) {
  1498. GENERIC_FAX_EXEC_ERROR(fax, chan, "INIT_ERROR", "failed to start FAX session");
  1499. }
  1500. report_fax_status(chan, details, "FAX Transmission In Progress");
  1501. ast_debug(5, "channel %s will wait on FAX fd %d\n", ast_channel_name(chan), fax->fd);
  1502. /* handle frames for the session */
  1503. remaining_time = timeout;
  1504. start = ast_tvnow();
  1505. while (remaining_time > 0) {
  1506. struct ast_channel *ready_chan;
  1507. int ofd, exception;
  1508. ms = 1000;
  1509. errno = 0;
  1510. ready_chan = ast_waitfor_nandfds(&c, chancount, &fax->fd, 1, &exception, &ofd, &ms);
  1511. if (ready_chan) {
  1512. if (!(frame = ast_read(chan))) {
  1513. /* the channel is probably gone, so lets stop polling on it and let the
  1514. * FAX session complete before we exit the application. if needed,
  1515. * send the FAX stack silence so the modems can finish their session without
  1516. * any problems */
  1517. ast_debug(1, "Channel '%s' did not return a frame; probably hung up.\n", ast_channel_name(chan));
  1518. GENERIC_FAX_EXEC_SET_VARS(fax, chan, "HANGUP", "remote channel hungup");
  1519. c = NULL;
  1520. chancount = 0;
  1521. remaining_time = ast_remaining_ms(start, timeout);
  1522. fax->tech->cancel_session(fax);
  1523. if (fax->tech->generate_silence) {
  1524. fax->tech->generate_silence(fax);
  1525. }
  1526. continue;
  1527. }
  1528. if ((frame->frametype == AST_FRAME_CONTROL) &&
  1529. (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
  1530. (frame->datalen == sizeof(t38_parameters))) {
  1531. unsigned int was_t38 = t38negotiated;
  1532. struct ast_control_t38_parameters *parameters = frame->data.ptr;
  1533. switch (parameters->request_response) {
  1534. case AST_T38_REQUEST_NEGOTIATE:
  1535. /* the other end has requested a switch to T.38, so reply that we are willing, if we can
  1536. * do T.38 as well
  1537. */
  1538. t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
  1539. t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
  1540. ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
  1541. break;
  1542. case AST_T38_NEGOTIATED:
  1543. t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
  1544. t38negotiated = 1;
  1545. break;
  1546. default:
  1547. break;
  1548. }
  1549. if (t38negotiated && !was_t38) {
  1550. fax->tech->switch_to_t38(fax);
  1551. details->caps &= ~AST_FAX_TECH_AUDIO;
  1552. expected_frametype = AST_FRAME_MODEM;
  1553. expected_framesubclass.integer = AST_MODEM_T38;
  1554. if (fax->smoother) {
  1555. ast_smoother_free(fax->smoother);
  1556. fax->smoother = NULL;
  1557. }
  1558. report_fax_status(chan, details, "T.38 Negotiated");
  1559. ast_verb(3, "Channel '%s' switched to T.38 FAX session '%u'.\n", ast_channel_name(chan), fax->id);
  1560. }
  1561. } else if ((frame->frametype == expected_frametype) && (expected_framesubclass.integer == frame->subclass.integer) &&
  1562. ((!frame->subclass.format && !expected_framesubclass.format) ||
  1563. (frame->subclass.format && expected_framesubclass.format &&
  1564. (ast_format_cmp(frame->subclass.format, expected_framesubclass.format) != AST_FORMAT_CMP_NOT_EQUAL)))) {
  1565. struct ast_frame *f;
  1566. if (fax->smoother) {
  1567. /* push the frame into a smoother */
  1568. if (ast_smoother_feed(fax->smoother, frame) < 0) {
  1569. GENERIC_FAX_EXEC_ERROR(fax, chan, "UNKNOWN", "Failed to feed the smoother");
  1570. }
  1571. while ((f = ast_smoother_read(fax->smoother)) && (f->data.ptr)) {
  1572. if (fax->debug_info) {
  1573. debug_check_frame_for_silence(fax, 1, f);
  1574. }
  1575. /* write the frame to the FAX stack */
  1576. fax->tech->write(fax, f);
  1577. fax->frames_received++;
  1578. if (f != frame) {
  1579. ast_frfree(f);
  1580. }
  1581. }
  1582. } else {
  1583. /* write the frame to the FAX stack */
  1584. fax->tech->write(fax, frame);
  1585. fax->frames_received++;
  1586. }
  1587. start = ast_tvnow();
  1588. }
  1589. ast_frfree(frame);
  1590. } else if (ofd == fax->fd) {
  1591. /* read a frame from the FAX stack and send it out the channel.
  1592. * the FAX stack will return a NULL if the FAX session has already completed */
  1593. if (!(frame = fax->tech->read(fax))) {
  1594. break;
  1595. }
  1596. if (fax->debug_info && (frame->frametype == AST_FRAME_VOICE)) {
  1597. debug_check_frame_for_silence(fax, 0, frame);
  1598. }
  1599. ast_write(chan, frame);
  1600. fax->frames_sent++;
  1601. ast_frfree(frame);
  1602. start = ast_tvnow();
  1603. } else {
  1604. if (ms && (ofd < 0)) {
  1605. if ((errno == 0) || (errno == EINTR)) {
  1606. remaining_time = ast_remaining_ms(start, timeout);
  1607. if (remaining_time <= 0)
  1608. GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
  1609. continue;
  1610. } else {
  1611. ast_log(LOG_WARNING, "something bad happened while channel '%s' was polling.\n", ast_channel_name(chan));
  1612. GENERIC_FAX_EXEC_ERROR(fax, chan, "UNKNOWN", "error polling data");
  1613. break;
  1614. }
  1615. } else {
  1616. /* nothing happened */
  1617. remaining_time = ast_remaining_ms(start, timeout);
  1618. if (remaining_time <= 0) {
  1619. GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
  1620. break;
  1621. }
  1622. }
  1623. }
  1624. }
  1625. ast_debug(3, "channel '%s' - event loop stopped { timeout: %d, remaining_time: %d }\n", ast_channel_name(chan), timeout, remaining_time);
  1626. set_channel_variables(chan, details);
  1627. ast_atomic_fetchadd_int(&faxregistry.fax_complete, 1);
  1628. if (!strcasecmp(details->result, "FAILED")) {
  1629. ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
  1630. }
  1631. if (fax) {
  1632. ao2_lock(faxregistry.container);
  1633. ao2_unlink(faxregistry.container, fax);
  1634. ao2_unlock(faxregistry.container);
  1635. ao2_ref(fax, -1);
  1636. }
  1637. /* if the channel is still alive, and we changed its read/write formats,
  1638. * restore them now
  1639. */
  1640. if (chancount) {
  1641. if (orig_read_format) {
  1642. ast_set_read_format(chan, orig_read_format);
  1643. }
  1644. if (orig_write_format) {
  1645. ast_set_write_format(chan, orig_write_format);
  1646. }
  1647. }
  1648. /* return the chancount so the calling function can determine if the channel hungup during this FAX session or not */
  1649. return chancount;
  1650. }
  1651. static int receivefax_t38_init(struct ast_channel *chan, struct ast_fax_session_details *details)
  1652. {
  1653. int timeout_ms;
  1654. struct ast_frame *frame = NULL;
  1655. struct ast_control_t38_parameters t38_parameters;
  1656. struct timeval start;
  1657. int ms;
  1658. /* don't send any audio if we've already received a T.38 reinvite */
  1659. if (ast_channel_get_t38_state(chan) != T38_STATE_NEGOTIATING) {
  1660. /* generate 3 seconds of CED */
  1661. if (ast_playtones_start(chan, 1024, "!2100/3000", 1)) {
  1662. ast_log(LOG_ERROR, "error generating CED tone on %s\n", ast_channel_name(chan));
  1663. return -1;
  1664. }
  1665. timeout_ms = 3000;
  1666. start = ast_tvnow();
  1667. while ((ms = ast_remaining_ms(start, timeout_ms))) {
  1668. ms = ast_waitfor(chan, ms);
  1669. if (ms < 0) {
  1670. ast_log(LOG_ERROR, "error while generating CED tone on %s\n", ast_channel_name(chan));
  1671. ast_playtones_stop(chan);
  1672. return -1;
  1673. }
  1674. if (ms == 0) { /* all done, nothing happened */
  1675. break;
  1676. }
  1677. if (!(frame = ast_read(chan))) {
  1678. ast_log(LOG_ERROR, "error reading frame while generating CED tone on %s\n", ast_channel_name(chan));
  1679. ast_playtones_stop(chan);
  1680. return -1;
  1681. }
  1682. if ((frame->frametype == AST_FRAME_CONTROL) &&
  1683. (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
  1684. (frame->datalen == sizeof(t38_parameters))) {
  1685. struct ast_control_t38_parameters *parameters = frame->data.ptr;
  1686. switch (parameters->request_response) {
  1687. case AST_T38_REQUEST_NEGOTIATE:
  1688. /* the other end has requested a switch to T.38, so reply that we are willing, if we can
  1689. * do T.38 as well
  1690. */
  1691. t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
  1692. t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
  1693. ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
  1694. ast_playtones_stop(chan);
  1695. break;
  1696. case AST_T38_NEGOTIATED:
  1697. ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
  1698. t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
  1699. details->caps &= ~AST_FAX_TECH_AUDIO;
  1700. report_fax_status(chan, details, "T.38 Negotiated");
  1701. break;
  1702. default:
  1703. break;
  1704. }
  1705. }
  1706. ast_frfree(frame);
  1707. }
  1708. ast_playtones_stop(chan);
  1709. }
  1710. /* if T.38 was negotiated, we are done initializing */
  1711. if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
  1712. return 0;
  1713. }
  1714. /* request T.38 */
  1715. ast_debug(1, "Negotiating T.38 for receive on %s\n", ast_channel_name(chan));
  1716. /* wait up to five seconds for negotiation to complete */
  1717. timeout_ms = 5000;
  1718. /* set parameters based on the session's parameters */
  1719. t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
  1720. t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
  1721. if ((ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0)) {
  1722. return -1;
  1723. }
  1724. start = ast_tvnow();
  1725. while ((ms = ast_remaining_ms(start, timeout_ms))) {
  1726. int break_loop = 0;
  1727. ms = ast_waitfor(chan, ms);
  1728. if (ms < 0) {
  1729. ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
  1730. return -1;
  1731. }
  1732. if (ms == 0) { /* all done, nothing happened */
  1733. ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", ast_channel_name(chan));
  1734. details->caps &= ~AST_FAX_TECH_T38;
  1735. break;
  1736. }
  1737. if (!(frame = ast_read(chan))) {
  1738. ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
  1739. return -1;
  1740. }
  1741. if ((frame->frametype == AST_FRAME_CONTROL) &&
  1742. (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
  1743. (frame->datalen == sizeof(t38_parameters))) {
  1744. struct ast_control_t38_parameters *parameters = frame->data.ptr;
  1745. switch (parameters->request_response) {
  1746. case AST_T38_REQUEST_NEGOTIATE:
  1747. t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
  1748. t38_parameters.request_response = AST_T38_NEGOTIATED;
  1749. ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
  1750. break;
  1751. case AST_T38_NEGOTIATED:
  1752. ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
  1753. t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
  1754. details->caps &= ~AST_FAX_TECH_AUDIO;
  1755. report_fax_status(chan, details, "T.38 Negotiated");
  1756. break_loop = 1;
  1757. break;
  1758. case AST_T38_REFUSED:
  1759. ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", ast_channel_name(chan));
  1760. details->caps &= ~AST_FAX_TECH_T38;
  1761. break_loop = 1;
  1762. break;
  1763. default:
  1764. ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", ast_channel_name(chan));
  1765. details->caps &= ~AST_FAX_TECH_T38;
  1766. break_loop = 1;
  1767. break;
  1768. }
  1769. }
  1770. ast_frfree(frame);
  1771. if (break_loop) {
  1772. break;
  1773. }
  1774. }
  1775. /* if T.38 was negotiated, we are done initializing */
  1776. if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
  1777. return 0;
  1778. }
  1779. /* if we made it here, then T.38 failed, check the 'f' flag */
  1780. if (details->option.allow_audio != AST_FAX_OPTFLAG_TRUE) {
  1781. ast_log(LOG_WARNING, "Audio FAX not allowed on channel '%s' and T.38 negotiation failed; aborting.\n", ast_channel_name(chan));
  1782. return -1;
  1783. }
  1784. /* ok, audio fallback is allowed */
  1785. details->caps |= AST_FAX_TECH_AUDIO;
  1786. return 0;
  1787. }
  1788. /*! \brief Report on the final state of a receive fax operation
  1789. * \note This will lock the \ref ast_channel
  1790. */
  1791. static int report_receive_fax_status(struct ast_channel *chan, const char *filename)
  1792. {
  1793. RAII_VAR(struct ast_json *, json_object, NULL, ast_json_unref);
  1794. RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
  1795. RAII_VAR(struct ast_json *, json_array, ast_json_array_create(), ast_json_unref);
  1796. struct ast_json *json_filename = ast_json_string_create(filename);
  1797. if (!json_array || !json_filename) {
  1798. ast_json_unref(json_filename);
  1799. return -1;
  1800. }
  1801. ast_json_array_append(json_array, json_filename);
  1802. {
  1803. const char *remote_station_id;
  1804. const char *local_station_id;
  1805. const char *fax_pages;
  1806. const char *fax_resolution;
  1807. const char *fax_bitrate;
  1808. SCOPED_CHANNELLOCK(lock, chan);
  1809. remote_station_id = S_OR(pbx_builtin_getvar_helper(chan, "REMOTESTATIONID"), "");
  1810. if (!ast_strlen_zero(remote_station_id)) {
  1811. remote_station_id = ast_strdupa(remote_station_id);
  1812. }
  1813. local_station_id = S_OR(pbx_builtin_getvar_helper(chan, "LOCALSTATIONID"), "");
  1814. if (!ast_strlen_zero(local_station_id)) {
  1815. local_station_id = ast_strdupa(local_station_id);
  1816. }
  1817. fax_pages = S_OR(pbx_builtin_getvar_helper(chan, "FAXPAGES"), "");
  1818. if (!ast_strlen_zero(fax_pages)) {
  1819. fax_pages = ast_strdupa(fax_pages);
  1820. }
  1821. fax_resolution = S_OR(pbx_builtin_getvar_helper(chan, "FAXRESOLUTION"), "");
  1822. if (!ast_strlen_zero(fax_resolution)) {
  1823. fax_resolution = ast_strdupa(fax_resolution);
  1824. }
  1825. fax_bitrate = S_OR(pbx_builtin_getvar_helper(chan, "FAXBITRATE"), "");
  1826. if (!ast_strlen_zero(fax_bitrate)) {
  1827. fax_bitrate = ast_strdupa(fax_bitrate);
  1828. }
  1829. json_object = ast_json_pack("{s: s, s: s, s: s, s: s, s: s, s: s, s: O}",
  1830. "type", "receive",
  1831. "remote_station_id", S_OR(remote_station_id, ""),
  1832. "local_station_id", S_OR(local_station_id, ""),
  1833. "fax_pages", S_OR(fax_pages, ""),
  1834. "fax_resolution", S_OR(fax_resolution, ""),
  1835. "fax_bitrate", S_OR(fax_bitrate, ""),
  1836. "filenames", json_array);
  1837. if (!json_object) {
  1838. return -1;
  1839. }
  1840. message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), ast_channel_fax_type(), json_object);
  1841. if (!message) {
  1842. return -1;
  1843. }
  1844. stasis_publish(ast_channel_topic(chan), message);
  1845. }
  1846. return 0;
  1847. }
  1848. /*! \brief initiate a receive FAX session */
  1849. static int receivefax_exec(struct ast_channel *chan, const char *data)
  1850. {
  1851. char *parse, modems[128] = "";
  1852. int channel_alive;
  1853. RAII_VAR(struct ast_fax_session *, s, NULL, ao2_cleanup);
  1854. RAII_VAR(struct ast_fax_session_details *, details, NULL, ao2_cleanup);
  1855. struct ast_fax_tech_token *token = NULL;
  1856. struct ast_fax_document *doc;
  1857. AST_DECLARE_APP_ARGS(args,
  1858. AST_APP_ARG(filename);
  1859. AST_APP_ARG(options);
  1860. );
  1861. struct ast_flags opts = { 0, };
  1862. enum ast_t38_state t38state;
  1863. /* initialize output channel variables */
  1864. pbx_builtin_setvar_helper(chan, "FAXSTATUS", "FAILED");
  1865. pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", NULL);
  1866. pbx_builtin_setvar_helper(chan, "FAXPAGES", "0");
  1867. pbx_builtin_setvar_helper(chan, "FAXBITRATE", NULL);
  1868. pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", NULL);
  1869. /* Get a FAX session details structure from the channel's FAX datastore and create one if
  1870. * it does not already exist. */
  1871. if (!(details = find_or_create_details(chan))) {
  1872. pbx_builtin_setvar_helper(chan, "FAXERROR", "MEMORY_ERROR");
  1873. pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "error allocating memory");
  1874. ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
  1875. return -1;
  1876. }
  1877. ast_string_field_set(details, result, "FAILED");
  1878. ast_string_field_set(details, resultstr, "error starting fax session");
  1879. ast_string_field_set(details, error, "INIT_ERROR");
  1880. set_channel_variables(chan, details);
  1881. if (details->gateway_id > 0) {
  1882. ast_string_field_set(details, resultstr, "can't receive a fax on a channel with a T.38 gateway");
  1883. set_channel_variables(chan, details);
  1884. ast_log(LOG_ERROR, "executing ReceiveFAX on a channel with a T.38 Gateway is not supported\n");
  1885. return -1;
  1886. }
  1887. if (details->maxrate < details->minrate) {
  1888. ast_string_field_set(details, error, "INVALID_ARGUMENTS");
  1889. ast_string_field_set(details, resultstr, "maxrate is less than minrate");
  1890. set_channel_variables(chan, details);
  1891. ast_log(LOG_ERROR, "maxrate %u is less than minrate %u\n", details->maxrate, details->minrate);
  1892. return -1;
  1893. }
  1894. if (check_modem_rate(details->modems, details->minrate)) {
  1895. ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
  1896. ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'minrate' setting %u\n", modems, details->minrate);
  1897. ast_string_field_set(details, error, "INVALID_ARGUMENTS");
  1898. ast_string_field_set(details, resultstr, "incompatible 'modems' and 'minrate' settings");
  1899. set_channel_variables(chan, details);
  1900. return -1;
  1901. }
  1902. if (check_modem_rate(details->modems, details->maxrate)) {
  1903. ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
  1904. ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'maxrate' setting %u\n", modems, details->maxrate);
  1905. ast_string_field_set(details, error, "INVALID_ARGUMENTS");
  1906. ast_string_field_set(details, resultstr, "incompatible 'modems' and 'maxrate' settings");
  1907. set_channel_variables(chan, details);
  1908. return -1;
  1909. }
  1910. if (ast_strlen_zero(data)) {
  1911. ast_string_field_set(details, error, "INVALID_ARGUMENTS");
  1912. ast_string_field_set(details, resultstr, "invalid arguments");
  1913. set_channel_variables(chan, details);
  1914. ast_log(LOG_WARNING, "%s requires an argument (filename[,options])\n", app_receivefax);
  1915. return -1;
  1916. }
  1917. parse = ast_strdupa(data);
  1918. AST_STANDARD_APP_ARGS(args, parse);
  1919. if (!ast_strlen_zero(args.options) &&
  1920. ast_app_parse_options(fax_exec_options, &opts, NULL, args.options)) {
  1921. ast_string_field_set(details, error, "INVALID_ARGUMENTS");
  1922. ast_string_field_set(details, resultstr, "invalid arguments");
  1923. set_channel_variables(chan, details);
  1924. return -1;
  1925. }
  1926. if (ast_strlen_zero(args.filename)) {
  1927. ast_string_field_set(details, error, "INVALID_ARGUMENTS");
  1928. ast_string_field_set(details, resultstr, "invalid arguments");
  1929. set_channel_variables(chan, details);
  1930. ast_log(LOG_WARNING, "%s requires an argument (filename[,options])\n", app_receivefax);
  1931. return -1;
  1932. }
  1933. /* check for unsupported FAX application options */
  1934. if (ast_test_flag(&opts, OPT_CALLERMODE) || ast_test_flag(&opts, OPT_CALLEDMODE)) {
  1935. ast_string_field_set(details, error, "INVALID_ARGUMENTS");
  1936. ast_string_field_set(details, resultstr, "invalid arguments");
  1937. set_channel_variables(chan, details);
  1938. ast_log(LOG_WARNING, "%s does not support polling\n", app_receivefax);
  1939. return -1;
  1940. }
  1941. ast_atomic_fetchadd_int(&faxregistry.fax_rx_attempts, 1);
  1942. pbx_builtin_setvar_helper(chan, "FAXERROR", "Channel Problems");
  1943. pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "Error before FAX transmission started.");
  1944. if (!(doc = ast_calloc(1, sizeof(*doc) + strlen(args.filename) + 1))) {
  1945. ast_string_field_set(details, error, "MEMORY_ERROR");
  1946. ast_string_field_set(details, resultstr, "error allocating memory");
  1947. set_channel_variables(chan, details);
  1948. ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
  1949. return -1;
  1950. }
  1951. strcpy(doc->filename, args.filename);
  1952. AST_LIST_INSERT_TAIL(&details->documents, doc, next);
  1953. ast_verb(3, "Channel '%s' receiving FAX '%s'\n", ast_channel_name(chan), args.filename);
  1954. details->caps = AST_FAX_TECH_RECEIVE;
  1955. details->option.send_ced = AST_FAX_OPTFLAG_TRUE;
  1956. /* check for debug */
  1957. if (ast_test_flag(&opts, OPT_DEBUG) || global_fax_debug) {
  1958. details->option.debug = AST_FAX_OPTFLAG_TRUE;
  1959. }
  1960. /* check for request for status events */
  1961. if (ast_test_flag(&opts, OPT_STATUS)) {
  1962. details->option.statusevents = AST_FAX_OPTFLAG_TRUE;
  1963. }
  1964. t38state = ast_channel_get_t38_state(chan);
  1965. if ((t38state == T38_STATE_UNAVAILABLE) || (t38state == T38_STATE_REJECTED) ||
  1966. ast_test_flag(&opts, OPT_ALLOWAUDIO) ||
  1967. ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
  1968. details->option.allow_audio = AST_FAX_OPTFLAG_TRUE;
  1969. }
  1970. if (!(s = fax_session_reserve(details, &token))) {
  1971. ast_string_field_set(details, resultstr, "error reserving fax session");
  1972. set_channel_variables(chan, details);
  1973. ast_log(LOG_ERROR, "Unable to reserve FAX session.\n");
  1974. return -1;
  1975. }
  1976. /* make sure the channel is up */
  1977. if (ast_channel_state(chan) != AST_STATE_UP) {
  1978. if (ast_answer(chan)) {
  1979. ast_string_field_set(details, resultstr, "error answering channel");
  1980. set_channel_variables(chan, details);
  1981. ast_log(LOG_WARNING, "Channel '%s' failed answer attempt.\n", ast_channel_name(chan));
  1982. fax_session_release(s, token);
  1983. return -1;
  1984. }
  1985. }
  1986. if (!ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
  1987. if (set_fax_t38_caps(chan, details)) {
  1988. ast_string_field_set(details, error, "T38_NEG_ERROR");
  1989. ast_string_field_set(details, resultstr, "error negotiating T.38");
  1990. set_channel_variables(chan, details);
  1991. fax_session_release(s, token);
  1992. return -1;
  1993. }
  1994. } else {
  1995. details->caps |= AST_FAX_TECH_AUDIO;
  1996. }
  1997. if (!ast_test_flag(&opts, OPT_FORCE_AUDIO) && (details->caps & AST_FAX_TECH_T38)) {
  1998. if (receivefax_t38_init(chan, details)) {
  1999. ast_string_field_set(details, error, "T38_NEG_ERROR");
  2000. ast_string_field_set(details, resultstr, "error negotiating T.38");
  2001. set_channel_variables(chan, details);
  2002. fax_session_release(s, token);
  2003. ast_log(LOG_ERROR, "error initializing channel '%s' in T.38 mode\n", ast_channel_name(chan));
  2004. return -1;
  2005. }
  2006. }
  2007. if ((channel_alive = generic_fax_exec(chan, details, s, token)) < 0) {
  2008. ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
  2009. }
  2010. if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
  2011. if (disable_t38(chan)) {
  2012. ast_debug(1, "error disabling T.38 mode on %s\n", ast_channel_name(chan));
  2013. }
  2014. }
  2015. if (report_receive_fax_status(chan, args.filename)) {
  2016. ast_log(AST_LOG_ERROR, "Error publishing ReceiveFax status message\n");
  2017. }
  2018. /* If the channel hungup return -1; otherwise, return 0 to continue in the dialplan */
  2019. return (!channel_alive) ? -1 : 0;
  2020. }
  2021. static int sendfax_t38_init(struct ast_channel *chan, struct ast_fax_session_details *details)
  2022. {
  2023. int timeout_ms;
  2024. struct ast_frame *frame = NULL;
  2025. struct ast_control_t38_parameters t38_parameters;
  2026. struct timeval start;
  2027. int ms;
  2028. /* send CNG tone while listening for the receiver to initiate a switch
  2029. * to T.38 mode; if they do, stop sending the CNG tone and proceed with
  2030. * the switch.
  2031. *
  2032. * 10500 is enough time for 3 CNG tones
  2033. */
  2034. timeout_ms = 10500;
  2035. /* don't send any audio if we've already received a T.38 reinvite */
  2036. if (ast_channel_get_t38_state(chan) != T38_STATE_NEGOTIATING) {
  2037. if (ast_playtones_start(chan, 1024, "!1100/500,!0/3000,!1100/500,!0/3000,!1100/500,!0/3000", 1)) {
  2038. ast_log(LOG_ERROR, "error generating CNG tone on %s\n", ast_channel_name(chan));
  2039. return -1;
  2040. }
  2041. }
  2042. start = ast_tvnow();
  2043. while ((ms = ast_remaining_ms(start, timeout_ms))) {
  2044. int break_loop = 0;
  2045. ms = ast_waitfor(chan, ms);
  2046. if (ms < 0) {
  2047. ast_log(LOG_ERROR, "error while generating CNG tone on %s\n", ast_channel_name(chan));
  2048. ast_playtones_stop(chan);
  2049. return -1;
  2050. }
  2051. if (ms == 0) { /* all done, nothing happened */
  2052. break;
  2053. }
  2054. if (!(frame = ast_read(chan))) {
  2055. ast_log(LOG_ERROR, "error reading frame while generating CNG tone on %s\n", ast_channel_name(chan));
  2056. ast_playtones_stop(chan);
  2057. return -1;
  2058. }
  2059. if ((frame->frametype == AST_FRAME_CONTROL) &&
  2060. (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
  2061. (frame->datalen == sizeof(t38_parameters))) {
  2062. struct ast_control_t38_parameters *parameters = frame->data.ptr;
  2063. switch (parameters->request_response) {
  2064. case AST_T38_REQUEST_NEGOTIATE:
  2065. /* the other end has requested a switch to T.38, so reply that we are willing, if we can
  2066. * do T.38 as well
  2067. */
  2068. t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
  2069. t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
  2070. ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
  2071. ast_playtones_stop(chan);
  2072. break;
  2073. case AST_T38_NEGOTIATED:
  2074. ast_debug(1, "Negotiated T.38 for send on %s\n", ast_channel_name(chan));
  2075. t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
  2076. details->caps &= ~AST_FAX_TECH_AUDIO;
  2077. report_fax_status(chan, details, "T.38 Negotiated");
  2078. break_loop = 1;
  2079. break;
  2080. default:
  2081. break;
  2082. }
  2083. }
  2084. ast_frfree(frame);
  2085. if (break_loop) {
  2086. break;
  2087. }
  2088. }
  2089. ast_playtones_stop(chan);
  2090. if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
  2091. return 0;
  2092. }
  2093. /* T.38 negotiation did not happen, initiate a switch if requested */
  2094. if (details->option.request_t38 == AST_FAX_OPTFLAG_TRUE) {
  2095. ast_debug(1, "Negotiating T.38 for send on %s\n", ast_channel_name(chan));
  2096. /* wait up to five seconds for negotiation to complete */
  2097. timeout_ms = 5000;
  2098. /* set parameters based on the session's parameters */
  2099. t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
  2100. t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
  2101. if ((ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0)) {
  2102. return -1;
  2103. }
  2104. start = ast_tvnow();
  2105. while ((ms = ast_remaining_ms(start, timeout_ms))) {
  2106. int break_loop = 0;
  2107. ms = ast_waitfor(chan, ms);
  2108. if (ms < 0) {
  2109. ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
  2110. return -1;
  2111. }
  2112. if (ms == 0) { /* all done, nothing happened */
  2113. ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", ast_channel_name(chan));
  2114. details->caps &= ~AST_FAX_TECH_T38;
  2115. break;
  2116. }
  2117. if (!(frame = ast_read(chan))) {
  2118. ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
  2119. return -1;
  2120. }
  2121. if ((frame->frametype == AST_FRAME_CONTROL) &&
  2122. (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
  2123. (frame->datalen == sizeof(t38_parameters))) {
  2124. struct ast_control_t38_parameters *parameters = frame->data.ptr;
  2125. switch (parameters->request_response) {
  2126. case AST_T38_REQUEST_NEGOTIATE:
  2127. t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
  2128. t38_parameters.request_response = AST_T38_NEGOTIATED;
  2129. ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
  2130. break;
  2131. case AST_T38_NEGOTIATED:
  2132. ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
  2133. t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
  2134. details->caps &= ~AST_FAX_TECH_AUDIO;
  2135. report_fax_status(chan, details, "T.38 Negotiated");
  2136. break_loop = 1;
  2137. break;
  2138. case AST_T38_REFUSED:
  2139. ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", ast_channel_name(chan));
  2140. details->caps &= ~AST_FAX_TECH_T38;
  2141. break_loop = 1;
  2142. break;
  2143. default:
  2144. ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", ast_channel_name(chan));
  2145. details->caps &= ~AST_FAX_TECH_T38;
  2146. break_loop = 1;
  2147. break;
  2148. }
  2149. }
  2150. ast_frfree(frame);
  2151. if (break_loop) {
  2152. break;
  2153. }
  2154. }
  2155. /* if T.38 was negotiated, we are done initializing */
  2156. if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
  2157. return 0;
  2158. }
  2159. /* send one more CNG tone to get audio going again for some
  2160. * carriers if we are going to fall back to audio mode */
  2161. if (details->option.allow_audio == AST_FAX_OPTFLAG_TRUE) {
  2162. if (ast_playtones_start(chan, 1024, "!1100/500,!0/3000", 1)) {
  2163. ast_log(LOG_ERROR, "error generating second CNG tone on %s\n", ast_channel_name(chan));
  2164. return -1;
  2165. }
  2166. timeout_ms = 3500;
  2167. start = ast_tvnow();
  2168. while ((ms = ast_remaining_ms(start, timeout_ms))) {
  2169. int break_loop = 0;
  2170. ms = ast_waitfor(chan, ms);
  2171. if (ms < 0) {
  2172. ast_log(LOG_ERROR, "error while generating second CNG tone on %s\n", ast_channel_name(chan));
  2173. ast_playtones_stop(chan);
  2174. return -1;
  2175. }
  2176. if (ms == 0) { /* all done, nothing happened */
  2177. break;
  2178. }
  2179. if (!(frame = ast_read(chan))) {
  2180. ast_log(LOG_ERROR, "error reading frame while generating second CNG tone on %s\n", ast_channel_name(chan));
  2181. ast_playtones_stop(chan);
  2182. return -1;
  2183. }
  2184. if ((frame->frametype == AST_FRAME_CONTROL) &&
  2185. (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
  2186. (frame->datalen == sizeof(t38_parameters))) {
  2187. struct ast_control_t38_parameters *parameters = frame->data.ptr;
  2188. switch (parameters->request_response) {
  2189. case AST_T38_REQUEST_NEGOTIATE:
  2190. /* the other end has requested a switch to T.38, so reply that we are willing, if we can
  2191. * do T.38 as well
  2192. */
  2193. t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
  2194. t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
  2195. ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
  2196. ast_playtones_stop(chan);
  2197. break;
  2198. case AST_T38_NEGOTIATED:
  2199. ast_debug(1, "Negotiated T.38 for send on %s\n", ast_channel_name(chan));
  2200. t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
  2201. details->caps &= ~AST_FAX_TECH_AUDIO;
  2202. report_fax_status(chan, details, "T.38 Negotiated");
  2203. break_loop = 1;
  2204. break;
  2205. default:
  2206. break;
  2207. }
  2208. }
  2209. ast_frfree(frame);
  2210. if (break_loop) {
  2211. break;
  2212. }
  2213. }
  2214. ast_playtones_stop(chan);
  2215. /* if T.38 was negotiated, we are done initializing */
  2216. if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
  2217. return 0;
  2218. }
  2219. }
  2220. }
  2221. /* if we made it here, then T.38 failed, check the 'f' flag */
  2222. if (details->option.allow_audio == AST_FAX_OPTFLAG_FALSE) {
  2223. ast_log(LOG_WARNING, "Audio FAX not allowed on channel '%s' and T.38 negotiation failed; aborting.\n", ast_channel_name(chan));
  2224. return -1;
  2225. }
  2226. /* ok, audio fallback is allowed */
  2227. details->caps |= AST_FAX_TECH_AUDIO;
  2228. return 0;
  2229. }
  2230. /*!
  2231. * \brief Report on the status of a completed fax send attempt
  2232. * \note This will lock the \ref ast_channel
  2233. */
  2234. static int report_send_fax_status(struct ast_channel *chan, struct ast_fax_session_details *details)
  2235. {
  2236. RAII_VAR(struct ast_json *, json_obj, NULL, ast_json_unref);
  2237. RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
  2238. struct ast_json *json_filenames;
  2239. json_filenames = generate_filenames_json(details);
  2240. if (!json_filenames) {
  2241. return -1;
  2242. }
  2243. {
  2244. const char *remote_station_id;
  2245. const char *local_station_id;
  2246. const char *fax_pages;
  2247. const char *fax_resolution;
  2248. const char *fax_bitrate;
  2249. SCOPED_CHANNELLOCK(lock, chan);
  2250. remote_station_id = S_OR(pbx_builtin_getvar_helper(chan, "REMOTESTATIONID"), "");
  2251. if (!ast_strlen_zero(remote_station_id)) {
  2252. remote_station_id = ast_strdupa(remote_station_id);
  2253. }
  2254. local_station_id = S_OR(pbx_builtin_getvar_helper(chan, "LOCALSTATIONID"), "");
  2255. if (!ast_strlen_zero(local_station_id)) {
  2256. local_station_id = ast_strdupa(local_station_id);
  2257. }
  2258. fax_pages = S_OR(pbx_builtin_getvar_helper(chan, "FAXPAGES"), "");
  2259. if (!ast_strlen_zero(fax_pages)) {
  2260. fax_pages = ast_strdupa(fax_pages);
  2261. }
  2262. fax_resolution = S_OR(pbx_builtin_getvar_helper(chan, "FAXRESOLUTION"), "");
  2263. if (!ast_strlen_zero(fax_resolution)) {
  2264. fax_resolution = ast_strdupa(fax_resolution);
  2265. }
  2266. fax_bitrate = S_OR(pbx_builtin_getvar_helper(chan, "FAXBITRATE"), "");
  2267. if (!ast_strlen_zero(fax_bitrate)) {
  2268. fax_bitrate = ast_strdupa(fax_bitrate);
  2269. }
  2270. json_obj = ast_json_pack("{s: s, s: s, s: s, s: s, s: s, s: s, s: o}",
  2271. "type", "send",
  2272. "remote_station_id", S_OR(remote_station_id, ""),
  2273. "local_station_id", S_OR(local_station_id, ""),
  2274. "fax_pages", S_OR(fax_pages, ""),
  2275. "fax_resolution", S_OR(fax_resolution, ""),
  2276. "fax_bitrate", S_OR(fax_bitrate, ""),
  2277. "filenames", json_filenames);
  2278. if (!json_obj) {
  2279. return -1;
  2280. }
  2281. message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), ast_channel_fax_type(), json_obj);
  2282. if (!message) {
  2283. return -1;
  2284. }
  2285. stasis_publish(ast_channel_topic(chan), message);
  2286. }
  2287. return 0;
  2288. }
  2289. /*! \brief initiate a send FAX session */
  2290. static int sendfax_exec(struct ast_channel *chan, const char *data)
  2291. {
  2292. char *parse, *filenames, *c, modems[128] = "";
  2293. int channel_alive, file_count;
  2294. RAII_VAR(struct ast_fax_session_details *, details, NULL, ao2_cleanup);
  2295. RAII_VAR(struct ast_fax_session *, s, NULL, ao2_cleanup);
  2296. struct ast_fax_tech_token *token = NULL;
  2297. struct ast_fax_document *doc;
  2298. AST_DECLARE_APP_ARGS(args,
  2299. AST_APP_ARG(filenames);
  2300. AST_APP_ARG(options);
  2301. );
  2302. struct ast_flags opts = { 0, };
  2303. enum ast_t38_state t38state;
  2304. /* initialize output channel variables */
  2305. pbx_builtin_setvar_helper(chan, "FAXSTATUS", "FAILED");
  2306. pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", NULL);
  2307. pbx_builtin_setvar_helper(chan, "FAXPAGES", "0");
  2308. pbx_builtin_setvar_helper(chan, "FAXBITRATE", NULL);
  2309. pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", NULL);
  2310. /* Get a requirement structure and set it. This structure is used
  2311. * to tell the FAX technology module about the higher level FAX session */
  2312. if (!(details = find_or_create_details(chan))) {
  2313. pbx_builtin_setvar_helper(chan, "FAXERROR", "MEMORY_ERROR");
  2314. pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "error allocating memory");
  2315. ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
  2316. return -1;
  2317. }
  2318. ast_string_field_set(details, result, "FAILED");
  2319. ast_string_field_set(details, resultstr, "error starting fax session");
  2320. ast_string_field_set(details, error, "INIT_ERROR");
  2321. set_channel_variables(chan, details);
  2322. if (details->gateway_id > 0) {
  2323. ast_string_field_set(details, resultstr, "can't send a fax on a channel with a T.38 gateway");
  2324. set_channel_variables(chan, details);
  2325. ast_log(LOG_ERROR, "executing SendFAX on a channel with a T.38 Gateway is not supported\n");
  2326. return -1;
  2327. }
  2328. if (details->maxrate < details->minrate) {
  2329. ast_string_field_set(details, error, "INVALID_ARGUMENTS");
  2330. ast_string_field_set(details, resultstr, "maxrate is less than minrate");
  2331. set_channel_variables(chan, details);
  2332. ast_log(LOG_ERROR, "maxrate %u is less than minrate %u\n", details->maxrate, details->minrate);
  2333. return -1;
  2334. }
  2335. if (check_modem_rate(details->modems, details->minrate)) {
  2336. ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
  2337. ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'minrate' setting %u\n", modems, details->minrate);
  2338. ast_string_field_set(details, error, "INVALID_ARGUMENTS");
  2339. ast_string_field_set(details, resultstr, "incompatible 'modems' and 'minrate' settings");
  2340. set_channel_variables(chan, details);
  2341. return -1;
  2342. }
  2343. if (check_modem_rate(details->modems, details->maxrate)) {
  2344. ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
  2345. ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'maxrate' setting %u\n", modems, details->maxrate);
  2346. ast_string_field_set(details, error, "INVALID_ARGUMENTS");
  2347. ast_string_field_set(details, resultstr, "incompatible 'modems' and 'maxrate' settings");
  2348. set_channel_variables(chan, details);
  2349. return -1;
  2350. }
  2351. if (ast_strlen_zero(data)) {
  2352. ast_string_field_set(details, error, "INVALID_ARGUMENTS");
  2353. ast_string_field_set(details, resultstr, "invalid arguments");
  2354. set_channel_variables(chan, details);
  2355. ast_log(LOG_WARNING, "%s requires an argument (filename[&filename[&filename]][,options])\n", app_sendfax);
  2356. return -1;
  2357. }
  2358. parse = ast_strdupa(data);
  2359. AST_STANDARD_APP_ARGS(args, parse);
  2360. if (!ast_strlen_zero(args.options) &&
  2361. ast_app_parse_options(fax_exec_options, &opts, NULL, args.options)) {
  2362. ast_string_field_set(details, error, "INVALID_ARGUMENTS");
  2363. ast_string_field_set(details, resultstr, "invalid arguments");
  2364. set_channel_variables(chan, details);
  2365. return -1;
  2366. }
  2367. if (ast_strlen_zero(args.filenames)) {
  2368. ast_string_field_set(details, error, "INVALID_ARGUMENTS");
  2369. ast_string_field_set(details, resultstr, "invalid arguments");
  2370. set_channel_variables(chan, details);
  2371. ast_log(LOG_WARNING, "%s requires an argument (filename[&filename[&filename]],options])\n", app_sendfax);
  2372. return -1;
  2373. }
  2374. /* check for unsupported FAX application options */
  2375. if (ast_test_flag(&opts, OPT_CALLERMODE) || ast_test_flag(&opts, OPT_CALLEDMODE)) {
  2376. ast_string_field_set(details, error, "INVALID_ARGUMENTS");
  2377. ast_string_field_set(details, resultstr, "invalid arguments");
  2378. set_channel_variables(chan, details);
  2379. ast_log(LOG_WARNING, "%s does not support polling\n", app_sendfax);
  2380. return -1;
  2381. }
  2382. ast_atomic_fetchadd_int(&faxregistry.fax_tx_attempts, 1);
  2383. file_count = 0;
  2384. filenames = args.filenames;
  2385. while ((c = strsep(&filenames, "&"))) {
  2386. if (access(c, (F_OK | R_OK)) < 0) {
  2387. ast_string_field_set(details, error, "FILE_ERROR");
  2388. ast_string_field_set(details, resultstr, "error reading file");
  2389. set_channel_variables(chan, details);
  2390. ast_log(LOG_ERROR, "access failure. Verify '%s' exists and check permissions.\n", args.filenames);
  2391. return -1;
  2392. }
  2393. if (!(doc = ast_calloc(1, sizeof(*doc) + strlen(c) + 1))) {
  2394. ast_string_field_set(details, error, "MEMORY_ERROR");
  2395. ast_string_field_set(details, resultstr, "error allocating memory");
  2396. set_channel_variables(chan, details);
  2397. ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
  2398. return -1;
  2399. }
  2400. strcpy(doc->filename, c);
  2401. AST_LIST_INSERT_TAIL(&details->documents, doc, next);
  2402. file_count++;
  2403. }
  2404. ast_verb(3, "Channel '%s' sending FAX:\n", ast_channel_name(chan));
  2405. AST_LIST_TRAVERSE(&details->documents, doc, next) {
  2406. ast_verb(3, " %s\n", doc->filename);
  2407. }
  2408. details->caps = AST_FAX_TECH_SEND;
  2409. if (file_count > 1) {
  2410. details->caps |= AST_FAX_TECH_MULTI_DOC;
  2411. }
  2412. /* check for debug */
  2413. if (ast_test_flag(&opts, OPT_DEBUG) || global_fax_debug) {
  2414. details->option.debug = AST_FAX_OPTFLAG_TRUE;
  2415. }
  2416. /* check for request for status events */
  2417. if (ast_test_flag(&opts, OPT_STATUS)) {
  2418. details->option.statusevents = AST_FAX_OPTFLAG_TRUE;
  2419. }
  2420. t38state = ast_channel_get_t38_state(chan);
  2421. if ((t38state == T38_STATE_UNAVAILABLE) || (t38state == T38_STATE_REJECTED) ||
  2422. ast_test_flag(&opts, OPT_ALLOWAUDIO) ||
  2423. ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
  2424. details->option.allow_audio = AST_FAX_OPTFLAG_TRUE;
  2425. }
  2426. if (ast_test_flag(&opts, OPT_REQUEST_T38)) {
  2427. details->option.request_t38 = AST_FAX_OPTFLAG_TRUE;
  2428. }
  2429. if (!(s = fax_session_reserve(details, &token))) {
  2430. ast_string_field_set(details, resultstr, "error reserving fax session");
  2431. set_channel_variables(chan, details);
  2432. ast_log(LOG_ERROR, "Unable to reserve FAX session.\n");
  2433. return -1;
  2434. }
  2435. /* make sure the channel is up */
  2436. if (ast_channel_state(chan) != AST_STATE_UP) {
  2437. if (ast_answer(chan)) {
  2438. ast_string_field_set(details, resultstr, "error answering channel");
  2439. set_channel_variables(chan, details);
  2440. ast_log(LOG_WARNING, "Channel '%s' failed answer attempt.\n", ast_channel_name(chan));
  2441. fax_session_release(s, token);
  2442. return -1;
  2443. }
  2444. }
  2445. if (!ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
  2446. if (set_fax_t38_caps(chan, details)) {
  2447. ast_string_field_set(details, error, "T38_NEG_ERROR");
  2448. ast_string_field_set(details, resultstr, "error negotiating T.38");
  2449. set_channel_variables(chan, details);
  2450. fax_session_release(s, token);
  2451. return -1;
  2452. }
  2453. } else {
  2454. details->caps |= AST_FAX_TECH_AUDIO;
  2455. }
  2456. if (!ast_test_flag(&opts, OPT_FORCE_AUDIO) && (details->caps & AST_FAX_TECH_T38)) {
  2457. if (sendfax_t38_init(chan, details)) {
  2458. ast_string_field_set(details, error, "T38_NEG_ERROR");
  2459. ast_string_field_set(details, resultstr, "error negotiating T.38");
  2460. set_channel_variables(chan, details);
  2461. fax_session_release(s, token);
  2462. ast_log(LOG_ERROR, "error initializing channel '%s' in T.38 mode\n", ast_channel_name(chan));
  2463. return -1;
  2464. }
  2465. } else {
  2466. details->option.send_cng = 1;
  2467. }
  2468. if ((channel_alive = generic_fax_exec(chan, details, s, token)) < 0) {
  2469. ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
  2470. }
  2471. if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
  2472. if (disable_t38(chan)) {
  2473. ast_debug(1, "error disabling T.38 mode on %s\n", ast_channel_name(chan));
  2474. }
  2475. }
  2476. if (!(filenames = generate_filenames_string(details, "FileName: ", "\r\n"))) {
  2477. ast_log(LOG_ERROR, "Error generating SendFAX manager event\n");
  2478. return (!channel_alive) ? -1 : 0;
  2479. }
  2480. /* send out the AMI completion event */
  2481. if (report_send_fax_status(chan, details)) {
  2482. ast_log(AST_LOG_ERROR, "Error publishing SendFAX status message\n");
  2483. }
  2484. /* If the channel hungup return -1; otherwise, return 0 to continue in the dialplan */
  2485. return (!channel_alive) ? -1 : 0;
  2486. }
  2487. /*! \brief destroy the v21 detection parts of a fax gateway session */
  2488. static void destroy_v21_sessions(struct fax_gateway *gateway)
  2489. {
  2490. if (gateway->chan_v21_session) {
  2491. ao2_lock(faxregistry.container);
  2492. ao2_unlink(faxregistry.container, gateway->chan_v21_session);
  2493. ao2_unlock(faxregistry.container);
  2494. ao2_ref(gateway->chan_v21_session, -1);
  2495. gateway->chan_v21_session = NULL;
  2496. }
  2497. if (gateway->peer_v21_session) {
  2498. ao2_lock(faxregistry.container);
  2499. ao2_unlink(faxregistry.container, gateway->peer_v21_session);
  2500. ao2_unlock(faxregistry.container);
  2501. ao2_ref(gateway->peer_v21_session, -1);
  2502. gateway->peer_v21_session = NULL;
  2503. }
  2504. }
  2505. /*! \brief destroy a FAX gateway session structure */
  2506. static void destroy_gateway(void *data)
  2507. {
  2508. struct fax_gateway *gateway = data;
  2509. destroy_v21_sessions(gateway);
  2510. if (gateway->s) {
  2511. fax_session_release(gateway->s, gateway->token);
  2512. gateway->token = NULL;
  2513. ao2_lock(faxregistry.container);
  2514. ao2_unlink(faxregistry.container, gateway->s);
  2515. ao2_unlock(faxregistry.container);
  2516. ao2_ref(gateway->s, -1);
  2517. gateway->s = NULL;
  2518. }
  2519. ao2_cleanup(gateway->chan_read_format);
  2520. ao2_cleanup(gateway->chan_write_format);
  2521. ao2_cleanup(gateway->peer_read_format);
  2522. ao2_cleanup(gateway->peer_write_format);
  2523. }
  2524. /*! \brief Create a new fax gateway object.
  2525. * \param chan the channel the gateway object will be attached to
  2526. * \param details the fax session details
  2527. * \return NULL or a fax gateway object
  2528. */
  2529. static struct fax_gateway *fax_gateway_new(struct ast_channel *chan, struct ast_fax_session_details *details)
  2530. {
  2531. struct fax_gateway *gateway = ao2_alloc(sizeof(*gateway), destroy_gateway);
  2532. struct ast_fax_session_details *v21_details;
  2533. if (!gateway) {
  2534. return NULL;
  2535. }
  2536. if (!(v21_details = session_details_new())) {
  2537. ao2_ref(gateway, -1);
  2538. return NULL;
  2539. }
  2540. v21_details->caps = AST_FAX_TECH_V21_DETECT;
  2541. if (!(gateway->chan_v21_session = fax_session_new(v21_details, chan, NULL, NULL))) {
  2542. ao2_ref(v21_details, -1);
  2543. ao2_ref(gateway, -1);
  2544. return NULL;
  2545. }
  2546. if (!(gateway->peer_v21_session = fax_session_new(v21_details, chan, NULL, NULL))) {
  2547. ao2_ref(v21_details, -1);
  2548. ao2_ref(gateway, -1);
  2549. return NULL;
  2550. }
  2551. ao2_ref(v21_details, -1);
  2552. gateway->framehook = -1;
  2553. details->caps = AST_FAX_TECH_GATEWAY;
  2554. if (details->gateway_timeout && !(gateway->s = fax_session_reserve(details, &gateway->token))) {
  2555. details->caps &= ~AST_FAX_TECH_GATEWAY;
  2556. ast_log(LOG_ERROR, "Can't reserve a FAX session, gateway attempt failed.\n");
  2557. ao2_ref(gateway, -1);
  2558. return NULL;
  2559. }
  2560. return gateway;
  2561. }
  2562. /*! \brief Create a fax session and start T.30<->T.38 gateway mode
  2563. * \param gateway a fax gateway object
  2564. * \param details fax session details
  2565. * \param chan active channel
  2566. * \return 0 on error 1 on success*/
  2567. static int fax_gateway_start(struct fax_gateway *gateway, struct ast_fax_session_details *details, struct ast_channel *chan)
  2568. {
  2569. struct ast_fax_session *s;
  2570. /* create the FAX session */
  2571. if (!(s = fax_session_new(details, chan, gateway->s, gateway->token))) {
  2572. gateway->token = NULL;
  2573. ast_string_field_set(details, result, "FAILED");
  2574. ast_string_field_set(details, resultstr, "error starting gateway session");
  2575. ast_string_field_set(details, error, "INIT_ERROR");
  2576. set_channel_variables(chan, details);
  2577. report_fax_status(chan, details, "No Available Resource");
  2578. ast_log(LOG_ERROR, "Can't create a FAX session, gateway attempt failed.\n");
  2579. return -1;
  2580. }
  2581. /* release the reference for the reserved session and replace it with
  2582. * the real session */
  2583. if (gateway->s) {
  2584. ao2_ref(gateway->s, -1);
  2585. }
  2586. gateway->s = s;
  2587. gateway->token = NULL;
  2588. if (gateway->s->tech->start_session(gateway->s) < 0) {
  2589. ast_string_field_set(details, result, "FAILED");
  2590. ast_string_field_set(details, resultstr, "error starting gateway session");
  2591. ast_string_field_set(details, error, "INIT_ERROR");
  2592. set_channel_variables(chan, details);
  2593. return -1;
  2594. }
  2595. gateway->timeout_start.tv_sec = 0;
  2596. gateway->timeout_start.tv_usec = 0;
  2597. report_fax_status(chan, details, "FAX Transmission In Progress");
  2598. return 0;
  2599. }
  2600. static struct ast_frame *fax_gateway_request_t38(struct fax_gateway *gateway, struct ast_channel *chan, struct ast_frame *f)
  2601. {
  2602. struct ast_frame *fp;
  2603. struct ast_control_t38_parameters t38_parameters = {
  2604. .request_response = AST_T38_REQUEST_NEGOTIATE,
  2605. };
  2606. struct ast_frame control_frame = {
  2607. .src = "res_fax",
  2608. .frametype = AST_FRAME_CONTROL,
  2609. .datalen = sizeof(t38_parameters),
  2610. .subclass.integer = AST_CONTROL_T38_PARAMETERS,
  2611. .data.ptr = &t38_parameters,
  2612. };
  2613. struct ast_fax_session_details *details = find_details(chan);
  2614. if (!details) {
  2615. ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
  2616. ast_framehook_detach(chan, gateway->framehook);
  2617. return f;
  2618. }
  2619. t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
  2620. ao2_ref(details, -1);
  2621. if (!(fp = ast_frisolate(&control_frame))) {
  2622. ast_log(LOG_ERROR, "error generating T.38 request control frame on chan %s for T.38 gateway session\n", ast_channel_name(chan));
  2623. return f;
  2624. }
  2625. gateway->t38_state = T38_STATE_NEGOTIATING;
  2626. gateway->timeout_start = ast_tvnow();
  2627. details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
  2628. ast_debug(1, "requesting T.38 for gateway session for %s\n", ast_channel_name(chan));
  2629. return fp;
  2630. }
  2631. static struct ast_frame *fax_gateway_detect_v21(struct fax_gateway *gateway, struct ast_channel *chan, struct ast_channel *peer, struct ast_channel *active, struct ast_frame *f)
  2632. {
  2633. struct ast_channel *other = (active == chan) ? peer : chan;
  2634. struct ast_fax_session *active_v21_session = (active == chan) ? gateway->chan_v21_session : gateway->peer_v21_session;
  2635. if (!active_v21_session || gateway->detected_v21) {
  2636. return f;
  2637. }
  2638. if (active_v21_session->tech->write(active_v21_session, f) == 0 &&
  2639. active_v21_session->details->option.v21_detected) {
  2640. gateway->detected_v21 = 1;
  2641. }
  2642. if (gateway->detected_v21) {
  2643. destroy_v21_sessions(gateway);
  2644. if (ast_channel_get_t38_state(other) == T38_STATE_UNKNOWN) {
  2645. ast_debug(1, "detected v21 preamble from %s\n", ast_channel_name(active));
  2646. return fax_gateway_request_t38(gateway, chan, f);
  2647. } else {
  2648. ast_debug(1, "detected v21 preamble on %s, but %s does not support T.38 for T.38 gateway session\n", ast_channel_name(active), ast_channel_name(other));
  2649. }
  2650. }
  2651. return f;
  2652. }
  2653. static int fax_gateway_indicate_t38(struct ast_channel *chan, struct ast_channel *active, struct ast_control_t38_parameters *control_params)
  2654. {
  2655. if (active == chan) {
  2656. return ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, control_params, sizeof(*control_params));
  2657. } else {
  2658. return ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, control_params, sizeof(*control_params));
  2659. }
  2660. }
  2661. /*! \brief T38 Gateway Negotiate t38 parameters
  2662. * \param gateway gateway object
  2663. * \param chan channel running the gateway
  2664. * \param peer channel im bridged too
  2665. * \param active channel the frame originated on
  2666. * \param f the control frame to process
  2667. * \return processed control frame or null frame
  2668. */
  2669. static struct ast_frame *fax_gateway_detect_t38(struct fax_gateway *gateway, struct ast_channel *chan, struct ast_channel *peer, struct ast_channel *active, struct ast_frame *f)
  2670. {
  2671. struct ast_control_t38_parameters *control_params = f->data.ptr;
  2672. struct ast_channel *other = (active == chan) ? peer : chan;
  2673. struct ast_fax_session_details *details;
  2674. if (f->datalen != sizeof(struct ast_control_t38_parameters)) {
  2675. /* invalaid AST_CONTROL_T38_PARAMETERS frame, we can't
  2676. * do anything with it, pass it on */
  2677. return f;
  2678. }
  2679. /* ignore frames from ourselves */
  2680. if ((gateway->t38_state == T38_STATE_NEGOTIATED && control_params->request_response == AST_T38_NEGOTIATED)
  2681. || (gateway->t38_state == T38_STATE_REJECTED && control_params->request_response == AST_T38_REFUSED)
  2682. || (gateway->t38_state == T38_STATE_NEGOTIATING && control_params->request_response == AST_T38_REQUEST_TERMINATE)) {
  2683. return f;
  2684. }
  2685. if (!(details = find_details(chan))) {
  2686. ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
  2687. ast_framehook_detach(chan, gateway->framehook);
  2688. return f;
  2689. }
  2690. if (control_params->request_response == AST_T38_REQUEST_NEGOTIATE) {
  2691. enum ast_t38_state state = ast_channel_get_t38_state(other);
  2692. if (state == T38_STATE_UNKNOWN) {
  2693. /* we detected a request to negotiate T.38 and the
  2694. * other channel appears to support T.38, we'll pass
  2695. * the request through and only step in if the other
  2696. * channel rejects the request */
  2697. ast_debug(1, "%s is attempting to negotiate T.38 with %s, we'll see what happens\n", ast_channel_name(active), ast_channel_name(other));
  2698. t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
  2699. gateway->t38_state = T38_STATE_UNKNOWN;
  2700. gateway->timeout_start = ast_tvnow();
  2701. details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
  2702. ao2_ref(details, -1);
  2703. return f;
  2704. } else if (state == T38_STATE_UNAVAILABLE || state == T38_STATE_REJECTED) {
  2705. /* the other channel does not support T.38, we need to
  2706. * step in here */
  2707. ast_debug(1, "%s is attempting to negotiate T.38 but %s does not support it\n", ast_channel_name(active), ast_channel_name(other));
  2708. ast_debug(1, "starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(active), ast_channel_name(other));
  2709. t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
  2710. t38_parameters_fax_to_ast(control_params, &details->our_t38_parameters);
  2711. if (fax_gateway_start(gateway, details, chan)) {
  2712. ast_log(LOG_ERROR, "error starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(active), ast_channel_name(other));
  2713. gateway->t38_state = T38_STATE_REJECTED;
  2714. control_params->request_response = AST_T38_REFUSED;
  2715. ast_framehook_detach(chan, details->gateway_id);
  2716. details->gateway_id = -1;
  2717. } else {
  2718. gateway->t38_state = T38_STATE_NEGOTIATED;
  2719. control_params->request_response = AST_T38_NEGOTIATED;
  2720. report_fax_status(chan, details, "T.38 Negotiated");
  2721. }
  2722. fax_gateway_indicate_t38(chan, active, control_params);
  2723. ao2_ref(details, -1);
  2724. return &ast_null_frame;
  2725. } else if (gateway->t38_state == T38_STATE_NEGOTIATING) {
  2726. /* we got a request to negotiate T.38 after we already
  2727. * sent one to the other party based on v21 preamble
  2728. * detection. We'll just pretend we passed this request
  2729. * through in the first place. */
  2730. t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
  2731. gateway->t38_state = T38_STATE_UNKNOWN;
  2732. gateway->timeout_start = ast_tvnow();
  2733. details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
  2734. ast_debug(1, "%s is attempting to negotiate T.38 after we already sent a negotiation request based on v21 preamble detection\n", ast_channel_name(active));
  2735. ao2_ref(details, -1);
  2736. return &ast_null_frame;
  2737. } else if (gateway->t38_state == T38_STATE_NEGOTIATED) {
  2738. /* we got a request to negotiate T.38 after we already
  2739. * sent one to the other party based on v21 preamble
  2740. * detection and received a response. We need to
  2741. * respond to this and shut down the gateway. */
  2742. t38_parameters_fax_to_ast(control_params, &details->their_t38_parameters);
  2743. ast_framehook_detach(chan, details->gateway_id);
  2744. details->gateway_id = -1;
  2745. control_params->request_response = AST_T38_NEGOTIATED;
  2746. fax_gateway_indicate_t38(chan, active, control_params);
  2747. ast_string_field_set(details, result, "SUCCESS");
  2748. ast_string_field_set(details, resultstr, "no gateway necessary");
  2749. ast_string_field_set(details, error, "NATIVE_T38");
  2750. set_channel_variables(chan, details);
  2751. ast_debug(1, "%s is attempting to negotiate T.38 after we already negotiated T.38 with %s, disabling the gateway\n", ast_channel_name(active), ast_channel_name(other));
  2752. ao2_ref(details, -1);
  2753. return &ast_null_frame;
  2754. } else {
  2755. ast_log(LOG_WARNING, "%s is attempting to negotiate T.38 while %s is in an unsupported state\n", ast_channel_name(active), ast_channel_name(other));
  2756. ao2_ref(details, -1);
  2757. return f;
  2758. }
  2759. } else if (gateway->t38_state == T38_STATE_NEGOTIATING
  2760. && control_params->request_response == AST_T38_REFUSED) {
  2761. ast_debug(1, "unable to negotiate T.38 on %s for fax gateway\n", ast_channel_name(active));
  2762. /* our request to negotiate T.38 was refused, if the other
  2763. * channel supports T.38, they might still reinvite and save
  2764. * the day. Otherwise disable the gateway. */
  2765. if (ast_channel_get_t38_state(other) == T38_STATE_UNKNOWN) {
  2766. gateway->t38_state = T38_STATE_UNAVAILABLE;
  2767. } else {
  2768. ast_framehook_detach(chan, details->gateway_id);
  2769. details->gateway_id = -1;
  2770. ast_string_field_set(details, result, "FAILED");
  2771. ast_string_field_set(details, resultstr, "unable to negotiate T.38");
  2772. ast_string_field_set(details, error, "T38_NEG_ERROR");
  2773. set_channel_variables(chan, details);
  2774. }
  2775. ao2_ref(details, -1);
  2776. return &ast_null_frame;
  2777. } else if (gateway->t38_state == T38_STATE_NEGOTIATING
  2778. && control_params->request_response == AST_T38_NEGOTIATED) {
  2779. ast_debug(1, "starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(active), ast_channel_name(other));
  2780. t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
  2781. if (fax_gateway_start(gateway, details, chan)) {
  2782. ast_log(LOG_ERROR, "error starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(active), ast_channel_name(other));
  2783. gateway->t38_state = T38_STATE_NEGOTIATING;
  2784. control_params->request_response = AST_T38_REQUEST_TERMINATE;
  2785. fax_gateway_indicate_t38(chan, active, control_params);
  2786. } else {
  2787. gateway->t38_state = T38_STATE_NEGOTIATED;
  2788. report_fax_status(chan, details, "T.38 Negotiated");
  2789. }
  2790. ao2_ref(details, -1);
  2791. return &ast_null_frame;
  2792. } else if (control_params->request_response == AST_T38_REFUSED) {
  2793. /* the other channel refused the request to negotiate T.38,
  2794. * we'll step in here and pretend the request was accepted */
  2795. ast_debug(1, "%s attempted to negotiate T.38 but %s refused the request\n", ast_channel_name(other), ast_channel_name(active));
  2796. ast_debug(1, "starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(other), ast_channel_name(active));
  2797. t38_parameters_fax_to_ast(control_params, &details->our_t38_parameters);
  2798. if (fax_gateway_start(gateway, details, chan)) {
  2799. ast_log(LOG_ERROR, "error starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(active), ast_channel_name(other));
  2800. gateway->t38_state = T38_STATE_REJECTED;
  2801. control_params->request_response = AST_T38_REFUSED;
  2802. ast_framehook_detach(chan, details->gateway_id);
  2803. details->gateway_id = -1;
  2804. } else {
  2805. gateway->t38_state = T38_STATE_NEGOTIATED;
  2806. control_params->request_response = AST_T38_NEGOTIATED;
  2807. }
  2808. ao2_ref(details, -1);
  2809. return f;
  2810. } else if (control_params->request_response == AST_T38_REQUEST_TERMINATE) {
  2811. /* the channel wishes to end our short relationship, we shall
  2812. * oblige */
  2813. ast_debug(1, "T.38 channel %s is requesting a shutdown of T.38, disabling the gateway\n", ast_channel_name(active));
  2814. ast_framehook_detach(chan, details->gateway_id);
  2815. details->gateway_id = -1;
  2816. gateway->t38_state = T38_STATE_REJECTED;
  2817. control_params->request_response = AST_T38_TERMINATED;
  2818. fax_gateway_indicate_t38(chan, active, control_params);
  2819. ao2_ref(details, -1);
  2820. return &ast_null_frame;
  2821. } else if (control_params->request_response == AST_T38_NEGOTIATED) {
  2822. ast_debug(1, "T.38 successfully negotiated between %s and %s, no gateway necessary\n", ast_channel_name(active), ast_channel_name(other));
  2823. ast_framehook_detach(chan, details->gateway_id);
  2824. details->gateway_id = -1;
  2825. ast_string_field_set(details, result, "SUCCESS");
  2826. ast_string_field_set(details, resultstr, "no gateway necessary");
  2827. ast_string_field_set(details, error, "NATIVE_T38");
  2828. set_channel_variables(chan, details);
  2829. ao2_ref(details, -1);
  2830. return f;
  2831. } else if (control_params->request_response == AST_T38_TERMINATED) {
  2832. ast_debug(1, "T.38 disabled on channel %s\n", ast_channel_name(active));
  2833. ast_framehook_detach(chan, details->gateway_id);
  2834. details->gateway_id = -1;
  2835. ao2_ref(details, -1);
  2836. return &ast_null_frame;
  2837. }
  2838. ao2_ref(details, -1);
  2839. return f;
  2840. }
  2841. /*! \brief Destroy the gateway data structure when the framehook is detached
  2842. * \param data framehook data (gateway data)*/
  2843. static void fax_gateway_framehook_destroy(void *data) {
  2844. struct fax_gateway *gateway = data;
  2845. if (gateway->s) {
  2846. switch (gateway->s->state) {
  2847. case AST_FAX_STATE_INITIALIZED:
  2848. case AST_FAX_STATE_OPEN:
  2849. case AST_FAX_STATE_ACTIVE:
  2850. case AST_FAX_STATE_COMPLETE:
  2851. if (gateway->s->tech->cancel_session) {
  2852. gateway->s->tech->cancel_session(gateway->s);
  2853. }
  2854. /* fall through */
  2855. default:
  2856. break;
  2857. }
  2858. }
  2859. ao2_ref(gateway, -1);
  2860. }
  2861. /*! \brief T.30<->T.38 gateway framehook.
  2862. *
  2863. * Intercept packets on bridged channels and determine if a T.38 gateway is
  2864. * required. If a gateway is required, start a gateway and handle T.38
  2865. * negotiation if necessary.
  2866. *
  2867. * \param chan channel running the gateway
  2868. * \param f frame to handle may be NULL
  2869. * \param event framehook event
  2870. * \param data framehook data (struct fax_gateway *)
  2871. *
  2872. * \return processed frame or NULL when f is NULL or a null frame
  2873. */
  2874. static struct ast_frame *fax_gateway_framehook(struct ast_channel *chan, struct ast_frame *f, enum ast_framehook_event event, void *data) {
  2875. struct fax_gateway *gateway = data;
  2876. struct ast_channel *active;
  2877. RAII_VAR(struct ast_fax_session_details *, details, NULL, ao2_cleanup);
  2878. RAII_VAR(struct ast_channel *, peer, NULL, ao2_cleanup);
  2879. RAII_VAR(struct ast_channel *, chan_ref, chan, ao2_cleanup);
  2880. /* Ref bump channel for when we have to unlock it */
  2881. ao2_ref(chan_ref, 1);
  2882. if (gateway->s) {
  2883. details = gateway->s->details;
  2884. ao2_ref(details, 1);
  2885. } else {
  2886. if (!(details = find_details(chan))) {
  2887. ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
  2888. ast_framehook_detach(chan, gateway->framehook);
  2889. return f;
  2890. }
  2891. }
  2892. /* restore audio formats when we are detached */
  2893. if (event == AST_FRAMEHOOK_EVENT_DETACHED) {
  2894. set_channel_variables(chan, details);
  2895. if (gateway->bridged) {
  2896. ast_set_read_format(chan, gateway->chan_read_format);
  2897. ast_set_read_format(chan, gateway->chan_write_format);
  2898. ast_channel_unlock(chan);
  2899. peer = ast_channel_bridge_peer(chan);
  2900. if (peer) {
  2901. ast_set_read_format(peer, gateway->peer_read_format);
  2902. ast_set_read_format(peer, gateway->peer_write_format);
  2903. ast_channel_make_compatible(chan, peer);
  2904. }
  2905. ast_channel_lock(chan);
  2906. }
  2907. return NULL;
  2908. }
  2909. if (!f || (event == AST_FRAMEHOOK_EVENT_ATTACHED)) {
  2910. return NULL;
  2911. };
  2912. /* this frame was generated by the fax gateway, pass it on */
  2913. if (ast_test_flag(f, AST_FAX_FRFLAG_GATEWAY)) {
  2914. return f;
  2915. }
  2916. /* If we aren't bridged or we don't have a peer, don't do anything */
  2917. ast_channel_unlock(chan);
  2918. peer = ast_channel_bridge_peer(chan);
  2919. ast_channel_lock(chan);
  2920. if (!peer) {
  2921. return f;
  2922. }
  2923. if (!gateway->bridged) {
  2924. /* don't start a gateway if neither channel can handle T.38 */
  2925. if (ast_channel_get_t38_state(chan) == T38_STATE_UNAVAILABLE && ast_channel_get_t38_state(peer) == T38_STATE_UNAVAILABLE) {
  2926. ast_debug(1, "not starting gateway for %s and %s; neither channel supports T.38\n", ast_channel_name(chan), ast_channel_name(peer));
  2927. ast_framehook_detach(chan, gateway->framehook);
  2928. details->gateway_id = -1;
  2929. ast_string_field_set(details, result, "FAILED");
  2930. ast_string_field_set(details, resultstr, "neither channel supports T.38");
  2931. ast_string_field_set(details, error, "T38_NEG_ERROR");
  2932. set_channel_variables(chan, details);
  2933. return f;
  2934. }
  2935. if (details->gateway_timeout) {
  2936. gateway->timeout_start = ast_tvnow();
  2937. }
  2938. /* we are bridged, change r/w formats to SLIN for v21 preamble
  2939. * detection and T.30 */
  2940. ao2_replace(gateway->chan_read_format, ast_channel_readformat(chan));
  2941. ao2_replace(gateway->chan_write_format, ast_channel_readformat(chan));
  2942. ao2_replace(gateway->peer_read_format, ast_channel_readformat(peer));
  2943. ao2_replace(gateway->peer_write_format, ast_channel_readformat(peer));
  2944. ast_set_read_format(chan, ast_format_slin);
  2945. ast_set_write_format(chan, ast_format_slin);
  2946. ast_channel_unlock(chan);
  2947. ast_set_read_format(peer, ast_format_slin);
  2948. ast_set_write_format(peer, ast_format_slin);
  2949. ast_channel_make_compatible(chan, peer);
  2950. ast_channel_lock(chan);
  2951. gateway->bridged = 1;
  2952. }
  2953. if (gateway->bridged && !ast_tvzero(gateway->timeout_start)) {
  2954. if (ast_tvdiff_ms(ast_tvnow(), gateway->timeout_start) > details->gateway_timeout) {
  2955. ast_debug(1, "no fax activity between %s and %s after %d ms, disabling gateway\n", ast_channel_name(chan), ast_channel_name(peer), details->gateway_timeout);
  2956. ast_framehook_detach(chan, gateway->framehook);
  2957. details->gateway_id = -1;
  2958. ast_string_field_set(details, result, "FAILED");
  2959. ast_string_field_build(details, resultstr, "no fax activity after %d ms", details->gateway_timeout);
  2960. ast_string_field_set(details, error, "TIMEOUT");
  2961. set_channel_variables(chan, details);
  2962. return f;
  2963. }
  2964. }
  2965. /* only handle VOICE, MODEM, and CONTROL frames*/
  2966. switch (f->frametype) {
  2967. case AST_FRAME_VOICE:
  2968. if ((ast_format_cmp(f->subclass.format, ast_format_slin) != AST_FORMAT_CMP_EQUAL) &&
  2969. (ast_format_cmp(f->subclass.format, ast_format_alaw) != AST_FORMAT_CMP_EQUAL) &&
  2970. (ast_format_cmp(f->subclass.format, ast_format_ulaw) != AST_FORMAT_CMP_EQUAL)) {
  2971. return f;
  2972. }
  2973. break;
  2974. case AST_FRAME_MODEM:
  2975. if (f->subclass.integer == AST_MODEM_T38) {
  2976. break;
  2977. }
  2978. return f;
  2979. case AST_FRAME_CONTROL:
  2980. if (f->subclass.integer == AST_CONTROL_T38_PARAMETERS) {
  2981. break;
  2982. }
  2983. return f;
  2984. default:
  2985. return f;
  2986. }
  2987. /* detect the active channel */
  2988. switch (event) {
  2989. case AST_FRAMEHOOK_EVENT_WRITE:
  2990. active = peer;
  2991. break;
  2992. case AST_FRAMEHOOK_EVENT_READ:
  2993. active = chan;
  2994. break;
  2995. default:
  2996. ast_log(LOG_WARNING, "unhandled framehook event %u\n", event);
  2997. return f;
  2998. }
  2999. /* handle control frames */
  3000. if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_T38_PARAMETERS) {
  3001. return fax_gateway_detect_t38(gateway, chan, peer, active, f);
  3002. }
  3003. if (!gateway->detected_v21 && gateway->t38_state == T38_STATE_UNAVAILABLE && f->frametype == AST_FRAME_VOICE) {
  3004. /* not in gateway mode and have not detected v21 yet, listen
  3005. * for v21 */
  3006. return fax_gateway_detect_v21(gateway, chan, peer, active, f);
  3007. }
  3008. /* in gateway mode, gateway some packets */
  3009. if (gateway->t38_state == T38_STATE_NEGOTIATED) {
  3010. /* framehooks are called in __ast_read() before frame format
  3011. * translation is done, so we need to translate here */
  3012. if ((f->frametype == AST_FRAME_VOICE) && (ast_format_cmp(f->subclass.format, ast_format_slin) != AST_FORMAT_CMP_EQUAL)) {
  3013. if (ast_channel_readtrans(active) && (f = ast_translate(ast_channel_readtrans(active), f, 1)) == NULL) {
  3014. f = &ast_null_frame;
  3015. return f;
  3016. }
  3017. }
  3018. /* XXX we ignore the return value here, perhaps we should
  3019. * disable the gateway if a write fails. I am not sure how a
  3020. * write would fail, or even if a failure would be fatal so for
  3021. * now we'll just ignore the return value. */
  3022. gateway->s->tech->write(gateway->s, f);
  3023. if ((f->frametype == AST_FRAME_VOICE) && (ast_format_cmp(f->subclass.format, ast_format_slin) != AST_FORMAT_CMP_EQUAL) &&
  3024. ast_channel_readtrans(active)) {
  3025. /* Only free the frame if we translated / duplicated it - otherwise,
  3026. * let whatever is outside the frame hook do it */
  3027. ast_frfree(f);
  3028. }
  3029. f = &ast_null_frame;
  3030. return f;
  3031. }
  3032. /* force silence on the line if T.38 negotiation might be taking place */
  3033. if (gateway->t38_state != T38_STATE_UNAVAILABLE && gateway->t38_state != T38_STATE_REJECTED) {
  3034. if (f->frametype == AST_FRAME_VOICE &&
  3035. (ast_format_cmp(f->subclass.format, ast_format_slin) == AST_FORMAT_CMP_EQUAL)) {
  3036. short silence_buf[f->samples];
  3037. struct ast_frame silence_frame = {
  3038. .frametype = AST_FRAME_VOICE,
  3039. .subclass.format = ast_format_slin,
  3040. .data.ptr = silence_buf,
  3041. .samples = f->samples,
  3042. .datalen = sizeof(silence_buf),
  3043. };
  3044. memset(silence_buf, 0, sizeof(silence_buf));
  3045. return ast_frisolate(&silence_frame);
  3046. } else {
  3047. return &ast_null_frame;
  3048. }
  3049. }
  3050. return f;
  3051. }
  3052. /*! \brief Attach a gateway framehook object to a channel.
  3053. * \param chan the channel to attach to
  3054. * \param details fax session details
  3055. * \return the framehook id of the attached framehook or -1 on error
  3056. * \retval -1 error
  3057. */
  3058. static int fax_gateway_attach(struct ast_channel *chan, struct ast_fax_session_details *details)
  3059. {
  3060. struct fax_gateway *gateway;
  3061. struct ast_framehook_interface fr_hook = {
  3062. .version = AST_FRAMEHOOK_INTERFACE_VERSION,
  3063. .event_cb = fax_gateway_framehook,
  3064. .destroy_cb = fax_gateway_framehook_destroy,
  3065. .disable_inheritance = 1, /* Masquerade inheritance is handled through the datastore fixup */
  3066. };
  3067. ast_string_field_set(details, result, "SUCCESS");
  3068. ast_string_field_set(details, resultstr, "gateway operation started successfully");
  3069. ast_string_field_set(details, error, "NO_ERROR");
  3070. set_channel_variables(chan, details);
  3071. /* set up the frame hook*/
  3072. gateway = fax_gateway_new(chan, details);
  3073. if (!gateway) {
  3074. ast_string_field_set(details, result, "FAILED");
  3075. ast_string_field_set(details, resultstr, "error initializing gateway session");
  3076. ast_string_field_set(details, error, "INIT_ERROR");
  3077. set_channel_variables(chan, details);
  3078. report_fax_status(chan, details, "No Available Resource");
  3079. return -1;
  3080. }
  3081. fr_hook.data = gateway;
  3082. ast_channel_lock(chan);
  3083. gateway->framehook = ast_framehook_attach(chan, &fr_hook);
  3084. ast_channel_unlock(chan);
  3085. if (gateway->framehook < 0) {
  3086. ao2_ref(gateway, -1);
  3087. ast_string_field_set(details, result, "FAILED");
  3088. ast_string_field_set(details, resultstr, "error attaching gateway to channel");
  3089. ast_string_field_set(details, error, "INIT_ERROR");
  3090. set_channel_variables(chan, details);
  3091. return -1;
  3092. }
  3093. return gateway->framehook;
  3094. }
  3095. /*! \brief destroy a FAX detect structure */
  3096. static void destroy_faxdetect(void *data)
  3097. {
  3098. struct fax_detect *faxdetect = data;
  3099. if (faxdetect->dsp) {
  3100. ast_dsp_free(faxdetect->dsp);
  3101. faxdetect->dsp = NULL;
  3102. }
  3103. ao2_ref(faxdetect->details, -1);
  3104. ao2_cleanup(faxdetect->orig_format);
  3105. }
  3106. /*! \brief Create a new fax detect object.
  3107. * \param chan the channel attaching to
  3108. * \param timeout remove framehook in this time if set
  3109. * \param flags required options
  3110. * \return NULL or a fax gateway object
  3111. */
  3112. static struct fax_detect *fax_detect_new(struct ast_channel *chan, int timeout, int flags)
  3113. {
  3114. struct fax_detect *faxdetect = ao2_alloc(sizeof(*faxdetect), destroy_faxdetect);
  3115. if (!faxdetect) {
  3116. return NULL;
  3117. }
  3118. faxdetect->flags = flags;
  3119. if (timeout) {
  3120. faxdetect->timeout_start = ast_tvnow();
  3121. } else {
  3122. faxdetect->timeout_start.tv_sec = 0;
  3123. faxdetect->timeout_start.tv_usec = 0;
  3124. }
  3125. if (faxdetect->flags & FAX_DETECT_MODE_CNG) {
  3126. faxdetect->dsp = ast_dsp_new();
  3127. if (!faxdetect->dsp) {
  3128. ao2_ref(faxdetect, -1);
  3129. return NULL;
  3130. }
  3131. ast_dsp_set_features(faxdetect->dsp, DSP_FEATURE_FAX_DETECT);
  3132. ast_dsp_set_faxmode(faxdetect->dsp, DSP_FAXMODE_DETECT_CNG | DSP_FAXMODE_DETECT_SQUELCH);
  3133. } else {
  3134. faxdetect->dsp = NULL;
  3135. }
  3136. return faxdetect;
  3137. }
  3138. /*! \brief Deref the faxdetect data structure when the faxdetect framehook is detached
  3139. * \param data framehook data (faxdetect data)*/
  3140. static void fax_detect_framehook_destroy(void *data) {
  3141. struct fax_detect *faxdetect = data;
  3142. ao2_ref(faxdetect, -1);
  3143. }
  3144. /*! \brief Fax Detect Framehook
  3145. *
  3146. * Listen for fax tones in audio path and enable jumping to a extension when detected.
  3147. *
  3148. * \param chan channel
  3149. * \param f frame to handle may be NULL
  3150. * \param event framehook event
  3151. * \param data framehook data (struct fax_detect *)
  3152. *
  3153. * \return processed frame or NULL when f is NULL or a null frame
  3154. */
  3155. static struct ast_frame *fax_detect_framehook(struct ast_channel *chan, struct ast_frame *f, enum ast_framehook_event event, void *data) {
  3156. struct fax_detect *faxdetect = data;
  3157. struct ast_fax_session_details *details;
  3158. struct ast_control_t38_parameters *control_params;
  3159. RAII_VAR(struct ast_channel *, peer, NULL, ao2_cleanup);
  3160. RAII_VAR(struct ast_channel *, chan_ref, chan, ao2_cleanup);
  3161. int result = 0;
  3162. /* Ref bump the channel for when we have to unlock it */
  3163. ao2_ref(chan, 1);
  3164. details = faxdetect->details;
  3165. switch (event) {
  3166. case AST_FRAMEHOOK_EVENT_ATTACHED:
  3167. /* Setup format for DSP on ATTACH*/
  3168. ao2_replace(faxdetect->orig_format, ast_channel_readformat(chan));
  3169. if ((ast_format_cmp(ast_channel_readformat(chan), ast_format_slin) != AST_FORMAT_CMP_EQUAL) &&
  3170. (ast_format_cmp(ast_channel_readformat(chan), ast_format_alaw) != AST_FORMAT_CMP_EQUAL) &&
  3171. (ast_format_cmp(ast_channel_readformat(chan), ast_format_ulaw) != AST_FORMAT_CMP_EQUAL)) {
  3172. if (ast_set_read_format(chan, ast_format_slin)) {
  3173. ast_framehook_detach(chan, details->faxdetect_id);
  3174. details->faxdetect_id = -1;
  3175. return f;
  3176. }
  3177. }
  3178. return NULL;
  3179. case AST_FRAMEHOOK_EVENT_DETACHED:
  3180. /* restore audio formats when we are detached */
  3181. ast_set_read_format(chan, faxdetect->orig_format);
  3182. ast_channel_unlock(chan);
  3183. peer = ast_channel_bridge_peer(chan);
  3184. if (peer) {
  3185. ast_channel_make_compatible(chan, peer);
  3186. }
  3187. ast_channel_lock(chan);
  3188. return NULL;
  3189. case AST_FRAMEHOOK_EVENT_READ:
  3190. if (f) {
  3191. break;
  3192. }
  3193. default:
  3194. return f;
  3195. };
  3196. if (details->faxdetect_id < 0) {
  3197. return f;
  3198. }
  3199. if ((!ast_tvzero(faxdetect->timeout_start) &&
  3200. (ast_tvdiff_ms(ast_tvnow(), faxdetect->timeout_start) > faxdetect->timeout))) {
  3201. ast_framehook_detach(chan, details->faxdetect_id);
  3202. details->faxdetect_id = -1;
  3203. return f;
  3204. }
  3205. /* only handle VOICE and CONTROL frames*/
  3206. switch (f->frametype) {
  3207. case AST_FRAME_VOICE:
  3208. /* we have no DSP this means we not detecting CNG */
  3209. if (!faxdetect->dsp) {
  3210. return f;
  3211. }
  3212. /* We can only process some formats*/
  3213. if ((ast_format_cmp(f->subclass.format, ast_format_slin) != AST_FORMAT_CMP_EQUAL) &&
  3214. (ast_format_cmp(f->subclass.format, ast_format_alaw) != AST_FORMAT_CMP_EQUAL) &&
  3215. (ast_format_cmp(f->subclass.format, ast_format_ulaw) != AST_FORMAT_CMP_EQUAL)) {
  3216. return f;
  3217. }
  3218. break;
  3219. case AST_FRAME_CONTROL:
  3220. if ((f->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
  3221. (faxdetect->flags & FAX_DETECT_MODE_T38)) {
  3222. break;
  3223. }
  3224. return f;
  3225. default:
  3226. return f;
  3227. }
  3228. if (f->frametype == AST_FRAME_VOICE) {
  3229. f = ast_dsp_process(chan, faxdetect->dsp, f);
  3230. if (f->frametype == AST_FRAME_DTMF) {
  3231. result = f->subclass.integer;
  3232. }
  3233. } else if ((f->frametype == AST_FRAME_CONTROL) && (f->datalen == sizeof(struct ast_control_t38_parameters))) {
  3234. control_params = f->data.ptr;
  3235. switch (control_params->request_response) {
  3236. case AST_T38_NEGOTIATED:
  3237. case AST_T38_REQUEST_NEGOTIATE:
  3238. result = 't';
  3239. break;
  3240. default:
  3241. break;
  3242. }
  3243. }
  3244. if (result) {
  3245. const char *target_context = S_OR(ast_channel_macrocontext(chan), ast_channel_context(chan));
  3246. switch (result) {
  3247. case 'f':
  3248. case 't':
  3249. ast_channel_unlock(chan);
  3250. if (ast_exists_extension(chan, target_context, "fax", 1,
  3251. S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
  3252. ast_channel_lock(chan);
  3253. ast_verb(2, "Redirecting '%s' to fax extension due to %s detection\n",
  3254. ast_channel_name(chan), (result == 'f') ? "CNG" : "T38");
  3255. pbx_builtin_setvar_helper(chan, "FAXEXTEN", ast_channel_exten(chan));
  3256. if (ast_async_goto(chan, target_context, "fax", 1)) {
  3257. ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(chan), target_context);
  3258. }
  3259. ast_frfree(f);
  3260. f = &ast_null_frame;
  3261. } else {
  3262. ast_channel_lock(chan);
  3263. ast_log(LOG_NOTICE, "FAX %s detected but no fax extension in context (%s)\n",
  3264. (result == 'f') ? "CNG" : "T38", target_context);
  3265. }
  3266. }
  3267. ast_framehook_detach(chan, details->faxdetect_id);
  3268. details->faxdetect_id = -1;
  3269. }
  3270. return f;
  3271. }
  3272. /*! \brief Attach a faxdetect framehook object to a channel.
  3273. * \param chan the channel to attach to
  3274. * \param timeout remove framehook in this time if set
  3275. * \return the faxdetect structure or NULL on error
  3276. * \param flags required options
  3277. * \retval -1 error
  3278. */
  3279. static int fax_detect_attach(struct ast_channel *chan, int timeout, int flags)
  3280. {
  3281. struct fax_detect *faxdetect;
  3282. struct ast_fax_session_details *details;
  3283. struct ast_framehook_interface fr_hook = {
  3284. .version = AST_FRAMEHOOK_INTERFACE_VERSION,
  3285. .event_cb = fax_detect_framehook,
  3286. .destroy_cb = fax_detect_framehook_destroy,
  3287. };
  3288. if (!(details = find_or_create_details(chan))) {
  3289. ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
  3290. return -1;
  3291. }
  3292. /* set up the frame hook*/
  3293. faxdetect = fax_detect_new(chan, timeout, flags);
  3294. if (!faxdetect) {
  3295. ao2_ref(details, -1);
  3296. return -1;
  3297. }
  3298. fr_hook.data = faxdetect;
  3299. faxdetect->details = details;
  3300. ast_channel_lock(chan);
  3301. details->faxdetect_id = ast_framehook_attach(chan, &fr_hook);
  3302. details->faxdetect_timeout = timeout;
  3303. details->faxdetect_flags = flags;
  3304. ast_channel_unlock(chan);
  3305. if (details->faxdetect_id < 0) {
  3306. ao2_ref(faxdetect, -1);
  3307. }
  3308. return details->faxdetect_id;
  3309. }
  3310. /*! \brief hash callback for ao2 */
  3311. static int session_hash_cb(const void *obj, const int flags)
  3312. {
  3313. const struct ast_fax_session *s = obj;
  3314. return s->id;
  3315. }
  3316. /*! \brief compare callback for ao2 */
  3317. static int session_cmp_cb(void *obj, void *arg, int flags)
  3318. {
  3319. struct ast_fax_session *lhs = obj, *rhs = arg;
  3320. return (lhs->id == rhs->id) ? CMP_MATCH | CMP_STOP : 0;
  3321. }
  3322. /*! \brief fax session tab completion */
  3323. static char *fax_session_tab_complete(struct ast_cli_args *a)
  3324. {
  3325. int tklen;
  3326. int wordnum = 0;
  3327. char *name = NULL;
  3328. struct ao2_iterator i;
  3329. struct ast_fax_session *s;
  3330. char tbuf[5];
  3331. if (a->pos != 3) {
  3332. return NULL;
  3333. }
  3334. tklen = strlen(a->word);
  3335. i = ao2_iterator_init(faxregistry.container, 0);
  3336. while ((s = ao2_iterator_next(&i))) {
  3337. snprintf(tbuf, sizeof(tbuf), "%u", s->id);
  3338. if (!strncasecmp(a->word, tbuf, tklen) && ++wordnum > a->n) {
  3339. name = ast_strdup(tbuf);
  3340. ao2_ref(s, -1);
  3341. break;
  3342. }
  3343. ao2_ref(s, -1);
  3344. }
  3345. ao2_iterator_destroy(&i);
  3346. return name;
  3347. }
  3348. static char *cli_fax_show_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3349. {
  3350. struct fax_module *fax;
  3351. switch(cmd) {
  3352. case CLI_INIT:
  3353. e->command = "fax show version";
  3354. e->usage =
  3355. "Usage: fax show version\n"
  3356. " Show versions of FAX For Asterisk components.\n";
  3357. return NULL;
  3358. case CLI_GENERATE:
  3359. return NULL;
  3360. }
  3361. if (a->argc != 3) {
  3362. return CLI_SHOWUSAGE;
  3363. }
  3364. ast_cli(a->fd, "FAX For Asterisk Components:\n");
  3365. ast_cli(a->fd, "\tApplications: %s\n", ast_get_version());
  3366. AST_RWLIST_RDLOCK(&faxmodules);
  3367. AST_RWLIST_TRAVERSE(&faxmodules, fax, list) {
  3368. ast_cli(a->fd, "\t%s: %s\n", fax->tech->description, fax->tech->version);
  3369. }
  3370. AST_RWLIST_UNLOCK(&faxmodules);
  3371. ast_cli(a->fd, "\n");
  3372. return CLI_SUCCESS;
  3373. }
  3374. /*! \brief enable FAX debugging */
  3375. static char *cli_fax_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3376. {
  3377. int flag;
  3378. const char *what;
  3379. switch (cmd) {
  3380. case CLI_INIT:
  3381. e->command = "fax set debug {on|off}";
  3382. e->usage =
  3383. "Usage: fax set debug { on | off }\n"
  3384. " Enable/Disable FAX debugging on new FAX sessions. The basic FAX debugging will result in\n"
  3385. " additional events sent to manager sessions with 'call' class permissions. When\n"
  3386. " verbosity is greater than '5' events will be displayed to the console and audio versus\n"
  3387. " energy analysis will be performed and displayed to the console.\n";
  3388. return NULL;
  3389. case CLI_GENERATE:
  3390. return NULL;
  3391. }
  3392. what = a->argv[e->args-1]; /* guaranteed to exist */
  3393. if (!strcasecmp(what, "on")) {
  3394. flag = 1;
  3395. } else if (!strcasecmp(what, "off")) {
  3396. flag = 0;
  3397. } else {
  3398. return CLI_SHOWUSAGE;
  3399. }
  3400. global_fax_debug = flag;
  3401. ast_cli(a->fd, "\n\nFAX Debug %s\n\n", (flag) ? "Enabled" : "Disabled");
  3402. return CLI_SUCCESS;
  3403. }
  3404. /*! \brief display registered FAX capabilities */
  3405. static char *cli_fax_show_capabilities(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3406. {
  3407. struct fax_module *fax;
  3408. unsigned int num_modules = 0;
  3409. switch (cmd) {
  3410. case CLI_INIT:
  3411. e->command = "fax show capabilities";
  3412. e->usage =
  3413. "Usage: fax show capabilities\n"
  3414. " Shows the capabilities of the registered FAX technology modules\n";
  3415. return NULL;
  3416. case CLI_GENERATE:
  3417. return NULL;
  3418. }
  3419. ast_cli(a->fd, "\n\nRegistered FAX Technology Modules:\n\n");
  3420. AST_RWLIST_RDLOCK(&faxmodules);
  3421. AST_RWLIST_TRAVERSE(&faxmodules, fax, list) {
  3422. ast_cli(a->fd, "%-15s : %s\n%-15s : %s\n%-15s : ", "Type", fax->tech->type, "Description", fax->tech->description, "Capabilities");
  3423. fax->tech->cli_show_capabilities(a->fd);
  3424. num_modules++;
  3425. }
  3426. AST_RWLIST_UNLOCK(&faxmodules);
  3427. ast_cli(a->fd, "%u registered modules\n\n", num_modules);
  3428. return CLI_SUCCESS;
  3429. }
  3430. /*! \brief display global defaults and settings */
  3431. static char *cli_fax_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3432. {
  3433. struct fax_module *fax;
  3434. char modems[128] = "";
  3435. struct fax_options options;
  3436. switch (cmd) {
  3437. case CLI_INIT:
  3438. e->command = "fax show settings";
  3439. e->usage =
  3440. "Usage: fax show settings\n"
  3441. " Show the global settings and defaults of both the FAX core and technology modules\n";
  3442. return NULL;
  3443. case CLI_GENERATE:
  3444. return NULL;
  3445. }
  3446. get_general_options(&options);
  3447. ast_cli(a->fd, "FAX For Asterisk Settings:\n");
  3448. ast_cli(a->fd, "\tECM: %s\n", options.ecm ? "Enabled" : "Disabled");
  3449. ast_cli(a->fd, "\tStatus Events: %s\n", options.statusevents ? "On" : "Off");
  3450. ast_cli(a->fd, "\tMinimum Bit Rate: %u\n", options.minrate);
  3451. ast_cli(a->fd, "\tMaximum Bit Rate: %u\n", options.maxrate);
  3452. ast_fax_modem_to_str(options.modems, modems, sizeof(modems));
  3453. ast_cli(a->fd, "\tModem Modulations Allowed: %s\n", modems);
  3454. ast_cli(a->fd, "\n\nFAX Technology Modules:\n\n");
  3455. AST_RWLIST_RDLOCK(&faxmodules);
  3456. AST_RWLIST_TRAVERSE(&faxmodules, fax, list) {
  3457. ast_cli(a->fd, "%s (%s) Settings:\n", fax->tech->type, fax->tech->description);
  3458. fax->tech->cli_show_settings(a->fd);
  3459. }
  3460. AST_RWLIST_UNLOCK(&faxmodules);
  3461. return CLI_SUCCESS;
  3462. }
  3463. /*! \brief display details of a specified fax session */
  3464. static char *cli_fax_show_session(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3465. {
  3466. struct ast_fax_session *s, tmp;
  3467. switch (cmd) {
  3468. case CLI_INIT:
  3469. e->command = "fax show session";
  3470. e->usage =
  3471. "Usage: fax show session <session number>\n"
  3472. " Shows status of the named FAX session\n";
  3473. return NULL;
  3474. case CLI_GENERATE:
  3475. return fax_session_tab_complete(a);
  3476. }
  3477. if (a->argc != 4) {
  3478. return CLI_SHOWUSAGE;
  3479. }
  3480. if (sscanf(a->argv[3], "%u", &tmp.id) != 1) {
  3481. ast_log(LOG_ERROR, "invalid session id: '%s'\n", a->argv[3]);
  3482. return RESULT_SUCCESS;
  3483. }
  3484. ast_cli(a->fd, "\nFAX Session Details:\n--------------------\n\n");
  3485. s = ao2_find(faxregistry.container, &tmp, OBJ_POINTER);
  3486. if (s) {
  3487. s->tech->cli_show_session(s, a->fd);
  3488. ao2_ref(s, -1);
  3489. }
  3490. ast_cli(a->fd, "\n\n");
  3491. return CLI_SUCCESS;
  3492. }
  3493. static int manager_fax_session(struct mansession *s, const struct message *m)
  3494. {
  3495. const char *action_id = astman_get_header(m, "ActionID");
  3496. const char *session_number = astman_get_header(m, "SessionNumber");
  3497. char id_text[256] = "";
  3498. struct ast_fax_session *session;
  3499. struct ast_fax_session find_session;
  3500. if (sscanf(session_number, "%30u", &find_session.id) != 1) {
  3501. astman_send_error(s, m, "Invalid session ID");
  3502. return 0;
  3503. }
  3504. session = ao2_find(faxregistry.container, &find_session, OBJ_POINTER);
  3505. if (!session) {
  3506. astman_send_error(s, m, "Session not found");
  3507. return 0;
  3508. }
  3509. if (!session->tech->manager_fax_session) {
  3510. astman_send_error(s, m, "Fax technology doesn't provide a handler for FAXSession");
  3511. ao2_ref(session, -1);
  3512. return 0;
  3513. }
  3514. if (!ast_strlen_zero(action_id)) {
  3515. snprintf(id_text, sizeof(id_text), "ActionID: %s\r\n", action_id);
  3516. }
  3517. astman_send_ack(s, m, "FAXSession event will follow");
  3518. session->tech->manager_fax_session(s, id_text, session);
  3519. ao2_ref(session, -1);
  3520. return 0;
  3521. }
  3522. /*! \brief display fax stats */
  3523. static char *cli_fax_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3524. {
  3525. struct fax_module *fax;
  3526. switch (cmd) {
  3527. case CLI_INIT:
  3528. e->command = "fax show stats";
  3529. e->usage =
  3530. "Usage: fax show stats\n"
  3531. " Shows a statistical summary of FAX transmissions\n";
  3532. return NULL;
  3533. case CLI_GENERATE:
  3534. return NULL;
  3535. }
  3536. ast_cli(a->fd, "\nFAX Statistics:\n---------------\n\n");
  3537. ast_cli(a->fd, "%-20.20s : %d\n", "Current Sessions", faxregistry.active_sessions);
  3538. ast_cli(a->fd, "%-20.20s : %d\n", "Reserved Sessions", faxregistry.reserved_sessions);
  3539. ast_cli(a->fd, "%-20.20s : %d\n", "Transmit Attempts", faxregistry.fax_tx_attempts);
  3540. ast_cli(a->fd, "%-20.20s : %d\n", "Receive Attempts", faxregistry.fax_rx_attempts);
  3541. ast_cli(a->fd, "%-20.20s : %d\n", "Completed FAXes", faxregistry.fax_complete);
  3542. ast_cli(a->fd, "%-20.20s : %d\n", "Failed FAXes", faxregistry.fax_failures);
  3543. AST_RWLIST_RDLOCK(&faxmodules);
  3544. AST_RWLIST_TRAVERSE(&faxmodules, fax, list) {
  3545. fax->tech->cli_show_stats(a->fd);
  3546. }
  3547. AST_RWLIST_UNLOCK(&faxmodules);
  3548. ast_cli(a->fd, "\n\n");
  3549. return CLI_SUCCESS;
  3550. }
  3551. static int manager_fax_stats(struct mansession *s, const struct message *m)
  3552. {
  3553. const char *action_id = astman_get_header(m, "ActionID");
  3554. char id_text[256] = "";
  3555. astman_send_ack(s, m, "FAXStats event will follow");
  3556. if (!ast_strlen_zero(action_id)) {
  3557. snprintf(id_text, sizeof(id_text), "ActionID: %s\r\n", action_id);
  3558. }
  3559. astman_append(s, "Event: FAXStats\r\n"
  3560. "%s"
  3561. "CurrentSessions: %d\r\n"
  3562. "ReservedSessions: %d\r\n"
  3563. "TransmitAttempts: %d\r\n"
  3564. "ReceiveAttempts: %d\r\n"
  3565. "CompletedFAXes: %d\r\n"
  3566. "FailedFAXes: %d\r\n"
  3567. "\r\n",
  3568. id_text,
  3569. faxregistry.active_sessions, faxregistry.reserved_sessions,
  3570. faxregistry.fax_tx_attempts, faxregistry.fax_rx_attempts,
  3571. faxregistry.fax_complete, faxregistry.fax_failures);
  3572. return 0;
  3573. }
  3574. static const char *fax_session_type(struct ast_fax_session *s)
  3575. {
  3576. if (s->details->caps & AST_FAX_TECH_AUDIO) {
  3577. return "G.711";
  3578. }
  3579. if (s->details->caps & AST_FAX_TECH_T38) {
  3580. return "T.38";
  3581. }
  3582. return "none";
  3583. }
  3584. const char *ast_fax_session_operation_str(struct ast_fax_session *s)
  3585. {
  3586. if (s->details->caps & AST_FAX_TECH_GATEWAY) {
  3587. return "gateway";
  3588. }
  3589. if (s->details->caps & AST_FAX_TECH_SEND) {
  3590. return "send";
  3591. }
  3592. if (s->details->caps & AST_FAX_TECH_RECEIVE) {
  3593. return "receive";
  3594. }
  3595. if (s->details->caps & AST_FAX_TECH_V21_DETECT) {
  3596. return "V.21";
  3597. }
  3598. return "none";
  3599. }
  3600. /*! \brief display fax sessions */
  3601. static char *cli_fax_show_sessions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3602. {
  3603. struct ast_fax_session *s;
  3604. struct ao2_iterator i;
  3605. int session_count;
  3606. char *filenames;
  3607. switch (cmd) {
  3608. case CLI_INIT:
  3609. e->command = "fax show sessions";
  3610. e->usage =
  3611. "Usage: fax show sessions\n"
  3612. " Shows the current FAX sessions\n";
  3613. return NULL;
  3614. case CLI_GENERATE:
  3615. return NULL;
  3616. }
  3617. ast_cli(a->fd, "\nCurrent FAX Sessions:\n\n");
  3618. ast_cli(a->fd, "%-20.20s %-10.10s %-10.10s %-5.5s %-10.10s %-15.15s %-30.30s\n",
  3619. "Channel", "Tech", "FAXID", "Type", "Operation", "State", "File(s)");
  3620. i = ao2_iterator_init(faxregistry.container, 0);
  3621. while ((s = ao2_iterator_next(&i))) {
  3622. ao2_lock(s);
  3623. filenames = generate_filenames_string(s->details, "", ", ");
  3624. ast_cli(a->fd, "%-20.20s %-10.10s %-10u %-5.5s %-10.10s %-15.15s %-30s\n",
  3625. s->channame, s->tech->type, s->id,
  3626. fax_session_type(s),
  3627. ast_fax_session_operation_str(s),
  3628. ast_fax_state_to_str(s->state), S_OR(filenames, ""));
  3629. ast_free(filenames);
  3630. ao2_unlock(s);
  3631. ao2_ref(s, -1);
  3632. }
  3633. ao2_iterator_destroy(&i);
  3634. session_count = ao2_container_count(faxregistry.container);
  3635. ast_cli(a->fd, "\n%d FAX sessions\n\n", session_count);
  3636. return CLI_SUCCESS;
  3637. }
  3638. static int manager_fax_sessions_entry(struct mansession *s,
  3639. struct ast_fax_session *session, const char *id_text)
  3640. {
  3641. char *filenames;
  3642. ao2_lock(session);
  3643. filenames = generate_filenames_string(session->details, "", ",");
  3644. if (!filenames) {
  3645. ast_log(LOG_ERROR, "Error generating Files string");
  3646. ao2_unlock(session);
  3647. return -1;
  3648. }
  3649. astman_append(s, "Event: FAXSessionsEntry\r\n"
  3650. "%s" /* ActionID if present */
  3651. "Channel: %s\r\n" /* Channel name */
  3652. "Technology: %s\r\n" /* Fax session technology */
  3653. "SessionNumber: %u\r\n" /* Session ID */
  3654. "SessionType: %s\r\n" /* G711 or T38 */
  3655. "Operation: %s\r\n"
  3656. "State: %s\r\n"
  3657. "Files: %s\r\n"
  3658. "\r\n",
  3659. id_text, session->channame, session->tech->type, session->id,
  3660. fax_session_type(session), ast_fax_session_operation_str(session),
  3661. ast_fax_state_to_str(session->state), S_OR(filenames, ""));
  3662. ast_free(filenames);
  3663. ao2_unlock(session);
  3664. return 0;
  3665. }
  3666. static int manager_fax_sessions(struct mansession *s, const struct message *m)
  3667. {
  3668. const char *action_id = astman_get_header(m, "ActionID");
  3669. char id_text[256] = "";
  3670. struct ast_fax_session *session;
  3671. struct ao2_iterator iter;
  3672. int session_count = 0;
  3673. astman_send_listack(s, m, "FAXSessionsEntry event list will follow", "Start");
  3674. if (!ast_strlen_zero(action_id)) {
  3675. snprintf(id_text, sizeof(id_text), "ActionID: %s\r\n", action_id);
  3676. }
  3677. iter = ao2_iterator_init(faxregistry.container, 0);
  3678. while ((session = ao2_iterator_next(&iter))) {
  3679. if (!manager_fax_sessions_entry(s, session, id_text)) {
  3680. session_count++;
  3681. }
  3682. ao2_ref(session, -1);
  3683. }
  3684. ao2_iterator_destroy(&iter);
  3685. astman_append(s, "Event: FAXSessionsComplete\r\n"
  3686. "%s"
  3687. "EventList: Complete\r\n"
  3688. "Total: %d\r\n"
  3689. "\r\n",
  3690. id_text,
  3691. session_count);
  3692. return 0;
  3693. }
  3694. static struct ast_cli_entry fax_cli[] = {
  3695. AST_CLI_DEFINE(cli_fax_show_version, "Show versions of FAX For Asterisk components"),
  3696. AST_CLI_DEFINE(cli_fax_set_debug, "Enable/Disable FAX debugging on new FAX sessions"),
  3697. AST_CLI_DEFINE(cli_fax_show_capabilities, "Show the capabilities of the registered FAX technology modules"),
  3698. AST_CLI_DEFINE(cli_fax_show_settings, "Show the global settings and defaults of both the FAX core and technology modules"),
  3699. AST_CLI_DEFINE(cli_fax_show_session, "Show the status of the named FAX sessions"),
  3700. AST_CLI_DEFINE(cli_fax_show_sessions, "Show the current FAX sessions"),
  3701. AST_CLI_DEFINE(cli_fax_show_stats, "Summarize FAX session history"),
  3702. };
  3703. static void set_general_options(const struct fax_options *options)
  3704. {
  3705. ast_rwlock_wrlock(&options_lock);
  3706. general_options = *options;
  3707. ast_rwlock_unlock(&options_lock);
  3708. }
  3709. static void get_general_options(struct fax_options *options)
  3710. {
  3711. ast_rwlock_rdlock(&options_lock);
  3712. *options = general_options;
  3713. ast_rwlock_unlock(&options_lock);
  3714. }
  3715. /*! \brief configure res_fax */
  3716. static int set_config(int reload)
  3717. {
  3718. struct ast_config *cfg;
  3719. struct ast_variable *v;
  3720. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  3721. char modems[128] = "";
  3722. struct fax_options options;
  3723. int res = 0;
  3724. options = default_options;
  3725. /* When we're not reloading, we have to be certain to set the general options
  3726. * to the defaults in case config loading goes wrong at some point. On a reload,
  3727. * the general options need to stay the same as what they were prior to the
  3728. * reload rather than being reset to the defaults.
  3729. */
  3730. if (!reload) {
  3731. set_general_options(&options);
  3732. }
  3733. /* read configuration */
  3734. if (!(cfg = ast_config_load2(config, "res_fax", config_flags))) {
  3735. ast_log(LOG_NOTICE, "Configuration file '%s' not found, %s options.\n",
  3736. config, reload ? "not changing" : "using default");
  3737. return 0;
  3738. }
  3739. if (cfg == CONFIG_STATUS_FILEINVALID) {
  3740. ast_log(LOG_NOTICE, "Configuration file '%s' is invalid, %s options.\n",
  3741. config, reload ? "not changing" : "using default");
  3742. return 0;
  3743. }
  3744. if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  3745. return 0;
  3746. }
  3747. if (reload) {
  3748. options = default_options;
  3749. }
  3750. /* create configuration */
  3751. for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
  3752. int rate;
  3753. if (!strcasecmp(v->name, "minrate")) {
  3754. ast_debug(3, "reading minrate '%s' from configuration file\n", v->value);
  3755. if ((rate = fax_rate_str_to_int(v->value)) == 0) {
  3756. res = -1;
  3757. goto end;
  3758. }
  3759. options.minrate = rate;
  3760. } else if (!strcasecmp(v->name, "maxrate")) {
  3761. ast_debug(3, "reading maxrate '%s' from configuration file\n", v->value);
  3762. if ((rate = fax_rate_str_to_int(v->value)) == 0) {
  3763. res = -1;
  3764. goto end;
  3765. }
  3766. options.maxrate = rate;
  3767. } else if (!strcasecmp(v->name, "statusevents")) {
  3768. ast_debug(3, "reading statusevents '%s' from configuration file\n", v->value);
  3769. options.statusevents = ast_true(v->value);
  3770. } else if (!strcasecmp(v->name, "ecm")) {
  3771. ast_debug(3, "reading ecm '%s' from configuration file\n", v->value);
  3772. options.ecm = ast_true(v->value);
  3773. } else if ((!strcasecmp(v->name, "modem")) || (!strcasecmp(v->name, "modems"))) {
  3774. options.modems = 0;
  3775. update_modem_bits(&options.modems, v->value);
  3776. }
  3777. }
  3778. if (options.maxrate < options.minrate) {
  3779. ast_log(LOG_ERROR, "maxrate %u is less than minrate %u\n", options.maxrate, options.minrate);
  3780. res = -1;
  3781. goto end;
  3782. }
  3783. if (check_modem_rate(options.modems, options.minrate)) {
  3784. ast_fax_modem_to_str(options.modems, modems, sizeof(modems));
  3785. ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'minrate' setting %u\n", modems, options.minrate);
  3786. res = -1;
  3787. goto end;
  3788. }
  3789. if (check_modem_rate(options.modems, options.maxrate)) {
  3790. ast_fax_modem_to_str(options.modems, modems, sizeof(modems));
  3791. ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'maxrate' setting %u\n", modems, options.maxrate);
  3792. res = -1;
  3793. goto end;
  3794. }
  3795. set_general_options(&options);
  3796. end:
  3797. ast_config_destroy(cfg);
  3798. return res;
  3799. }
  3800. /*! \brief FAXOPT read function returns the contents of a FAX option */
  3801. static int acf_faxopt_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  3802. {
  3803. struct ast_fax_session_details *details = find_details(chan);
  3804. int res = 0;
  3805. char *filenames;
  3806. if (!details) {
  3807. ast_log(LOG_ERROR, "channel '%s' can't read FAXOPT(%s) because it has never been written.\n", ast_channel_name(chan), data);
  3808. return -1;
  3809. }
  3810. if (!strcasecmp(data, "ecm")) {
  3811. ast_copy_string(buf, details->option.ecm ? "yes" : "no", len);
  3812. } else if (!strcasecmp(data, "t38gateway") || !strcasecmp(data, "gateway") ||
  3813. !strcasecmp(data, "t38_gateway") || !strcasecmp(data, "faxgateway")) {
  3814. ast_copy_string(buf, details->gateway_id != -1 ? "yes" : "no", len);
  3815. } else if (!strcasecmp(data, "faxdetect")) {
  3816. ast_copy_string(buf, details->faxdetect_id != -1 ? "yes" : "no", len);
  3817. } else if (!strcasecmp(data, "error")) {
  3818. ast_copy_string(buf, details->error, len);
  3819. } else if (!strcasecmp(data, "filename")) {
  3820. if (AST_LIST_EMPTY(&details->documents)) {
  3821. ast_log(LOG_ERROR, "channel '%s' can't read FAXOPT(%s) because it has never been written.\n", ast_channel_name(chan), data);
  3822. res = -1;
  3823. } else {
  3824. ast_copy_string(buf, AST_LIST_FIRST(&details->documents)->filename, len);
  3825. }
  3826. } else if (!strcasecmp(data, "filenames")) {
  3827. if (AST_LIST_EMPTY(&details->documents)) {
  3828. ast_log(LOG_ERROR, "channel '%s' can't read FAXOPT(%s) because it has never been written.\n", ast_channel_name(chan), data);
  3829. res = -1;
  3830. } else if ((filenames = generate_filenames_string(details, "", ","))) {
  3831. ast_copy_string(buf, filenames, len);
  3832. ast_free(filenames);
  3833. } else {
  3834. ast_log(LOG_ERROR, "channel '%s' can't read FAXOPT(%s), there was an error generating the filenames list.\n", ast_channel_name(chan), data);
  3835. res = -1;
  3836. }
  3837. } else if (!strcasecmp(data, "headerinfo")) {
  3838. ast_copy_string(buf, details->headerinfo, len);
  3839. } else if (!strcasecmp(data, "localstationid")) {
  3840. ast_copy_string(buf, details->localstationid, len);
  3841. } else if (!strcasecmp(data, "maxrate")) {
  3842. snprintf(buf, len, "%u", details->maxrate);
  3843. } else if (!strcasecmp(data, "minrate")) {
  3844. snprintf(buf, len, "%u", details->minrate);
  3845. } else if (!strcasecmp(data, "pages")) {
  3846. snprintf(buf, len, "%u", details->pages_transferred);
  3847. } else if (!strcasecmp(data, "rate")) {
  3848. ast_copy_string(buf, details->transfer_rate, len);
  3849. } else if (!strcasecmp(data, "remotestationid")) {
  3850. ast_copy_string(buf, details->remotestationid, len);
  3851. } else if (!strcasecmp(data, "resolution")) {
  3852. ast_copy_string(buf, details->resolution, len);
  3853. } else if (!strcasecmp(data, "sessionid")) {
  3854. snprintf(buf, len, "%u", details->id);
  3855. } else if (!strcasecmp(data, "status")) {
  3856. ast_copy_string(buf, details->result, len);
  3857. } else if (!strcasecmp(data, "statusstr")) {
  3858. ast_copy_string(buf, details->resultstr, len);
  3859. } else if ((!strcasecmp(data, "modem")) || (!strcasecmp(data, "modems"))) {
  3860. ast_fax_modem_to_str(details->modems, buf, len);
  3861. } else {
  3862. ast_log(LOG_WARNING, "channel '%s' can't read FAXOPT(%s) because it is unhandled!\n", ast_channel_name(chan), data);
  3863. res = -1;
  3864. }
  3865. ao2_ref(details, -1);
  3866. return res;
  3867. }
  3868. /*! \brief FAXOPT write function modifies the contents of a FAX option */
  3869. static int acf_faxopt_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
  3870. {
  3871. int res = 0;
  3872. struct ast_fax_session_details *details;
  3873. if (!(details = find_or_create_details(chan))) {
  3874. ast_log(LOG_WARNING, "channel '%s' can't set FAXOPT(%s) to '%s' because it failed to create a datastore.\n", ast_channel_name(chan), data, value);
  3875. return -1;
  3876. }
  3877. ast_debug(3, "channel '%s' setting FAXOPT(%s) to '%s'\n", ast_channel_name(chan), data, value);
  3878. if (!strcasecmp(data, "ecm")) {
  3879. const char *val = ast_skip_blanks(value);
  3880. if (ast_true(val)) {
  3881. details->option.ecm = AST_FAX_OPTFLAG_TRUE;
  3882. } else if (ast_false(val)) {
  3883. details->option.ecm = AST_FAX_OPTFLAG_FALSE;
  3884. } else {
  3885. ast_log(LOG_WARNING, "Unsupported value '%s' passed to FAXOPT(ecm).\n", value);
  3886. }
  3887. } else if (!strcasecmp(data, "t38gateway") || !strcasecmp(data, "gateway") ||
  3888. !strcasecmp(data, "t38_gateway") || !strcasecmp(data, "faxgateway")) {
  3889. const char *val = ast_skip_blanks(value);
  3890. char *timeout = strchr(val, ',');
  3891. if (timeout) {
  3892. *timeout++ = '\0';
  3893. }
  3894. if (ast_true(val)) {
  3895. if (details->gateway_id < 0) {
  3896. details->gateway_timeout = 0;
  3897. if (timeout) {
  3898. unsigned int gwtimeout;
  3899. if (sscanf(timeout, "%u", &gwtimeout) == 1) {
  3900. details->gateway_timeout = gwtimeout * 1000;
  3901. } else {
  3902. ast_log(LOG_WARNING, "Unsupported timeout '%s' passed to FAXOPT(%s).\n", timeout, data);
  3903. }
  3904. }
  3905. details->gateway_id = fax_gateway_attach(chan, details);
  3906. if (details->gateway_id < 0) {
  3907. ast_log(LOG_ERROR, "Error attaching T.38 gateway to channel %s.\n", ast_channel_name(chan));
  3908. res = -1;
  3909. } else {
  3910. ast_debug(1, "Attached T.38 gateway to channel %s.\n", ast_channel_name(chan));
  3911. }
  3912. } else {
  3913. ast_log(LOG_WARNING, "Attempt to attach a T.38 gateway on channel (%s) with gateway already running.\n", ast_channel_name(chan));
  3914. }
  3915. } else if (ast_false(val)) {
  3916. ast_framehook_detach(chan, details->gateway_id);
  3917. details->gateway_id = -1;
  3918. } else {
  3919. ast_log(LOG_WARNING, "Unsupported value '%s' passed to FAXOPT(%s).\n", value, data);
  3920. }
  3921. } else if (!strcasecmp(data, "faxdetect")) {
  3922. const char *val = ast_skip_blanks(value);
  3923. char *timeout = strchr(val, ',');
  3924. unsigned int fdtimeout = 0;
  3925. int flags;
  3926. int faxdetect;
  3927. if (timeout) {
  3928. *timeout++ = '\0';
  3929. }
  3930. if (ast_true(val) || !strcasecmp(val, "t38") || !strcasecmp(val, "cng")) {
  3931. if (details->faxdetect_id < 0) {
  3932. if (timeout && (sscanf(timeout, "%u", &fdtimeout) == 1)) {
  3933. if (fdtimeout > 0) {
  3934. fdtimeout = fdtimeout * 1000;
  3935. } else {
  3936. ast_log(LOG_WARNING, "Timeout cannot be negative ignoring timeout\n");
  3937. }
  3938. }
  3939. if (!strcasecmp(val, "t38")) {
  3940. flags = FAX_DETECT_MODE_T38;
  3941. } else if (!strcasecmp(val, "cng")) {
  3942. flags = FAX_DETECT_MODE_CNG;
  3943. } else {
  3944. flags = FAX_DETECT_MODE_BOTH;
  3945. }
  3946. faxdetect = fax_detect_attach(chan, fdtimeout, flags);
  3947. if (faxdetect < 0) {
  3948. ast_log(LOG_ERROR, "Error attaching FAX detect to channel %s.\n", ast_channel_name(chan));
  3949. res = -1;
  3950. } else {
  3951. ast_debug(1, "Attached FAX detect to channel %s.\n", ast_channel_name(chan));
  3952. }
  3953. } else {
  3954. ast_log(LOG_WARNING, "Attempt to attach a FAX detect on channel (%s) with FAX detect already running.\n", ast_channel_name(chan));
  3955. }
  3956. } else if (ast_false(val)) {
  3957. ast_framehook_detach(chan, details->faxdetect_id);
  3958. details->faxdetect_id = -1;
  3959. } else {
  3960. ast_log(LOG_WARNING, "Unsupported value '%s' passed to FAXOPT(%s).\n", value, data);
  3961. }
  3962. } else if (!strcasecmp(data, "headerinfo")) {
  3963. ast_string_field_set(details, headerinfo, value);
  3964. } else if (!strcasecmp(data, "localstationid")) {
  3965. ast_string_field_set(details, localstationid, value);
  3966. } else if (!strcasecmp(data, "maxrate")) {
  3967. details->maxrate = fax_rate_str_to_int(value);
  3968. if (!details->maxrate) {
  3969. details->maxrate = ast_fax_maxrate();
  3970. }
  3971. } else if (!strcasecmp(data, "minrate")) {
  3972. details->minrate = fax_rate_str_to_int(value);
  3973. if (!details->minrate) {
  3974. details->minrate = ast_fax_minrate();
  3975. }
  3976. } else if ((!strcasecmp(data, "modem")) || (!strcasecmp(data, "modems"))) {
  3977. update_modem_bits(&details->modems, value);
  3978. } else {
  3979. ast_log(LOG_WARNING, "channel '%s' set FAXOPT(%s) to '%s' is unhandled!\n", ast_channel_name(chan), data, value);
  3980. res = -1;
  3981. }
  3982. ao2_ref(details, -1);
  3983. return res;
  3984. }
  3985. /*! \brief FAXOPT dialplan function */
  3986. struct ast_custom_function acf_faxopt = {
  3987. .name = "FAXOPT",
  3988. .read = acf_faxopt_read,
  3989. .write = acf_faxopt_write,
  3990. };
  3991. /*! \brief unload res_fax */
  3992. static int unload_module(void)
  3993. {
  3994. ast_cli_unregister_multiple(fax_cli, ARRAY_LEN(fax_cli));
  3995. if (ast_custom_function_unregister(&acf_faxopt) < 0) {
  3996. ast_log(LOG_WARNING, "failed to unregister function '%s'\n", acf_faxopt.name);
  3997. }
  3998. if (ast_unregister_application(app_sendfax) < 0) {
  3999. ast_log(LOG_WARNING, "failed to unregister '%s'\n", app_sendfax);
  4000. }
  4001. if (ast_unregister_application(app_receivefax) < 0) {
  4002. ast_log(LOG_WARNING, "failed to unregister '%s'\n", app_receivefax);
  4003. }
  4004. ast_manager_unregister("FAXSessions");
  4005. ast_manager_unregister("FAXSession");
  4006. ast_manager_unregister("FAXStats");
  4007. if (fax_logger_level != -1) {
  4008. ast_logger_unregister_level("FAX");
  4009. }
  4010. ao2_ref(faxregistry.container, -1);
  4011. return 0;
  4012. }
  4013. /*!
  4014. * \brief Load the module
  4015. *
  4016. * Module loading including tests for configuration or dependencies.
  4017. * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
  4018. * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
  4019. * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
  4020. * configuration file or other non-critical problem return
  4021. * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
  4022. */
  4023. static int load_module(void)
  4024. {
  4025. int res;
  4026. /* initialize the registry */
  4027. faxregistry.active_sessions = 0;
  4028. faxregistry.reserved_sessions = 0;
  4029. if (!(faxregistry.container = ao2_container_alloc(FAX_MAXBUCKETS, session_hash_cb, session_cmp_cb))) {
  4030. return AST_MODULE_LOAD_DECLINE;
  4031. }
  4032. if (set_config(0) < 0) {
  4033. ast_log(LOG_ERROR, "failed to load configuration file '%s'\n", config);
  4034. ao2_ref(faxregistry.container, -1);
  4035. return AST_MODULE_LOAD_DECLINE;
  4036. }
  4037. /* register CLI operations and applications */
  4038. if (ast_register_application_xml(app_sendfax, sendfax_exec) < 0) {
  4039. ast_log(LOG_WARNING, "failed to register '%s'.\n", app_sendfax);
  4040. ao2_ref(faxregistry.container, -1);
  4041. return AST_MODULE_LOAD_DECLINE;
  4042. }
  4043. if (ast_register_application_xml(app_receivefax, receivefax_exec) < 0) {
  4044. ast_log(LOG_WARNING, "failed to register '%s'.\n", app_receivefax);
  4045. ast_unregister_application(app_sendfax);
  4046. ao2_ref(faxregistry.container, -1);
  4047. return AST_MODULE_LOAD_DECLINE;
  4048. }
  4049. if (ast_manager_register_xml("FAXSessions", EVENT_FLAG_CALL, manager_fax_sessions)) {
  4050. ast_log(LOG_WARNING, "failed to register 'FAXSessions' AMI command.\n");
  4051. ast_unregister_application(app_receivefax);
  4052. ast_unregister_application(app_sendfax);
  4053. ao2_ref(faxregistry.container, -1);
  4054. return AST_MODULE_LOAD_DECLINE;
  4055. }
  4056. if (ast_manager_register_xml("FAXSession", EVENT_FLAG_CALL, manager_fax_session)) {
  4057. ast_log(LOG_WARNING, "failed to register 'FAXSession' AMI command.\n");
  4058. ast_manager_unregister("FAXSession");
  4059. ast_unregister_application(app_receivefax);
  4060. ast_unregister_application(app_sendfax);
  4061. ao2_ref(faxregistry.container, -1);
  4062. return AST_MODULE_LOAD_DECLINE;
  4063. }
  4064. if (ast_manager_register_xml("FAXStats", EVENT_FLAG_REPORTING, manager_fax_stats)) {
  4065. ast_log(LOG_WARNING, "failed to register 'FAXStats' AMI command.\n");
  4066. ast_manager_unregister("FAXSession");
  4067. ast_manager_unregister("FAXSessions");
  4068. ast_unregister_application(app_receivefax);
  4069. ast_unregister_application(app_sendfax);
  4070. ao2_ref(faxregistry.container, -1);
  4071. return AST_MODULE_LOAD_DECLINE;
  4072. }
  4073. ast_cli_register_multiple(fax_cli, ARRAY_LEN(fax_cli));
  4074. res = ast_custom_function_register(&acf_faxopt);
  4075. fax_logger_level = ast_logger_register_level("FAX");
  4076. return res;
  4077. }
  4078. static int reload_module(void)
  4079. {
  4080. set_config(1);
  4081. return 0;
  4082. }
  4083. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Generic FAX Applications",
  4084. .support_level = AST_MODULE_SUPPORT_CORE,
  4085. .load = load_module,
  4086. .unload = unload_module,
  4087. .reload = reload_module,
  4088. .load_pri = AST_MODPRI_APP_DEPEND,
  4089. );