res_fax.c 150 KB

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