pbx_dundi.c 155 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2006, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*! \file
  19. *
  20. * \brief Distributed Universal Number Discovery (DUNDi)
  21. */
  22. /*! \li \ref pbx_dundi.c uses configuration file \ref dundi.conf
  23. * \addtogroup configuration_file Configuration Files
  24. */
  25. /*!
  26. * \page dundi.conf dundi.conf
  27. * \verbinclude dundi.conf.sample
  28. */
  29. /*** MODULEINFO
  30. <depend>zlib</depend>
  31. <use type="module">res_crypto</use>
  32. <use type="external">crypto</use>
  33. <support_level>extended</support_level>
  34. ***/
  35. #include "asterisk.h"
  36. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  37. #include "asterisk/network.h"
  38. #include <sys/ioctl.h>
  39. #include <zlib.h>
  40. #include <sys/signal.h>
  41. #include <pthread.h>
  42. #include <net/if.h>
  43. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__Darwin__)
  44. #include <net/if_dl.h>
  45. #include <ifaddrs.h>
  46. #include <signal.h>
  47. #endif
  48. #include "asterisk/file.h"
  49. #include "asterisk/logger.h"
  50. #include "asterisk/channel.h"
  51. #include "asterisk/config.h"
  52. #include "asterisk/pbx.h"
  53. #include "asterisk/module.h"
  54. #include "asterisk/frame.h"
  55. #include "asterisk/cli.h"
  56. #include "asterisk/lock.h"
  57. #include "asterisk/md5.h"
  58. #include "asterisk/dundi.h"
  59. #include "asterisk/sched.h"
  60. #include "asterisk/io.h"
  61. #include "asterisk/utils.h"
  62. #include "asterisk/netsock2.h"
  63. #include "asterisk/crypto.h"
  64. #include "asterisk/astdb.h"
  65. #include "asterisk/acl.h"
  66. #include "asterisk/app.h"
  67. #include "dundi-parser.h"
  68. /*** DOCUMENTATION
  69. <function name="DUNDILOOKUP" language="en_US">
  70. <synopsis>
  71. Do a DUNDi lookup of a phone number.
  72. </synopsis>
  73. <syntax>
  74. <parameter name="number" required="true"/>
  75. <parameter name="context">
  76. <para>If not specified the default will be <literal>e164</literal>.</para>
  77. </parameter>
  78. <parameter name="options">
  79. <optionlist>
  80. <option name="b">
  81. <para>Bypass the internal DUNDi cache</para>
  82. </option>
  83. </optionlist>
  84. </parameter>
  85. </syntax>
  86. <description>
  87. <para>This will do a DUNDi lookup of the given phone number.</para>
  88. <para>This function will return the Technology/Resource found in the first result
  89. in the DUNDi lookup. If no results were found, the result will be blank.</para>
  90. </description>
  91. </function>
  92. <function name="DUNDIQUERY" language="en_US">
  93. <synopsis>
  94. Initiate a DUNDi query.
  95. </synopsis>
  96. <syntax>
  97. <parameter name="number" required="true"/>
  98. <parameter name="context">
  99. <para>If not specified the default will be <literal>e164</literal>.</para>
  100. </parameter>
  101. <parameter name="options">
  102. <optionlist>
  103. <option name="b">
  104. <para>Bypass the internal DUNDi cache</para>
  105. </option>
  106. </optionlist>
  107. </parameter>
  108. </syntax>
  109. <description>
  110. <para>This will do a DUNDi lookup of the given phone number.</para>
  111. <para>The result of this function will be a numeric ID that can be used to retrieve
  112. the results with the <literal>DUNDIRESULT</literal> function.</para>
  113. </description>
  114. </function>
  115. <function name="DUNDIRESULT" language="en_US">
  116. <synopsis>
  117. Retrieve results from a DUNDIQUERY.
  118. </synopsis>
  119. <syntax>
  120. <parameter name="id" required="true">
  121. <para>The identifier returned by the <literal>DUNDIQUERY</literal> function.</para>
  122. </parameter>
  123. <parameter name="resultnum">
  124. <optionlist>
  125. <option name="number">
  126. <para>The number of the result that you want to retrieve, this starts at <literal>1</literal></para>
  127. </option>
  128. <option name="getnum">
  129. <para>The total number of results that are available.</para>
  130. </option>
  131. </optionlist>
  132. </parameter>
  133. </syntax>
  134. <description>
  135. <para>This function will retrieve results from a previous use\n"
  136. of the <literal>DUNDIQUERY</literal> function.</para>
  137. </description>
  138. </function>
  139. ***/
  140. #define MAX_RESULTS 64
  141. #define MAX_PACKET_SIZE 8192
  142. #define MAX_WEIGHT 59999
  143. #define DUNDI_MODEL_INBOUND (1 << 0)
  144. #define DUNDI_MODEL_OUTBOUND (1 << 1)
  145. #define DUNDI_MODEL_SYMMETRIC (DUNDI_MODEL_INBOUND | DUNDI_MODEL_OUTBOUND)
  146. /*! Keep times of last 10 lookups */
  147. #define DUNDI_TIMING_HISTORY 10
  148. enum {
  149. FLAG_ISREG = (1 << 0), /*!< Transaction is register request */
  150. FLAG_DEAD = (1 << 1), /*!< Transaction is dead */
  151. FLAG_FINAL = (1 << 2), /*!< Transaction has final message sent */
  152. FLAG_ISQUAL = (1 << 3), /*!< Transaction is a qualification */
  153. FLAG_ENCRYPT = (1 << 4), /*!< Transaction is encrypted wiht ECX/DCX */
  154. FLAG_SENDFULLKEY = (1 << 5), /*!< Send full key on transaction */
  155. FLAG_STOREHIST = (1 << 6), /*!< Record historic performance */
  156. };
  157. #define DUNDI_FLAG_INTERNAL_NOPARTIAL (1 << 17)
  158. #if 0
  159. #define DUNDI_SECRET_TIME 15 /* Testing only */
  160. #else
  161. #define DUNDI_SECRET_TIME DUNDI_DEFAULT_CACHE_TIME
  162. #endif
  163. static struct io_context *io;
  164. static struct ast_sched_context *sched;
  165. static int netsocket = -1;
  166. static pthread_t netthreadid = AST_PTHREADT_NULL;
  167. static pthread_t precachethreadid = AST_PTHREADT_NULL;
  168. static pthread_t clearcachethreadid = AST_PTHREADT_NULL;
  169. static unsigned int tos = 0;
  170. static int dundidebug = 0;
  171. static int authdebug = 0;
  172. static int dundi_ttl = DUNDI_DEFAULT_TTL;
  173. static int dundi_key_ttl = DUNDI_DEFAULT_KEY_EXPIRE;
  174. static int dundi_cache_time = DUNDI_DEFAULT_CACHE_TIME;
  175. static int global_autokilltimeout = 0;
  176. static dundi_eid global_eid;
  177. static int default_expiration = 60;
  178. static int global_storehistory = 0;
  179. static char dept[80];
  180. static char org[80];
  181. static char locality[80];
  182. static char stateprov[80];
  183. static char country[80];
  184. static char email[80];
  185. static char phone[80];
  186. static char secretpath[80];
  187. static char cursecret[80];
  188. static char ipaddr[80];
  189. static time_t rotatetime;
  190. static dundi_eid empty_eid = { { 0, 0, 0, 0, 0, 0 } };
  191. static int dundi_shutdown = 0;
  192. struct permission {
  193. AST_LIST_ENTRY(permission) list;
  194. int allow;
  195. char name[0];
  196. };
  197. struct dundi_packet {
  198. AST_LIST_ENTRY(dundi_packet) list;
  199. struct dundi_hdr *h;
  200. int datalen;
  201. struct dundi_transaction *parent;
  202. int retransid;
  203. int retrans;
  204. unsigned char data[0];
  205. };
  206. struct dundi_hint_metadata {
  207. unsigned short flags;
  208. char exten[AST_MAX_EXTENSION];
  209. };
  210. struct dundi_precache_queue {
  211. AST_LIST_ENTRY(dundi_precache_queue) list;
  212. char *context;
  213. time_t expiration;
  214. char number[0];
  215. };
  216. struct dundi_request;
  217. struct dundi_transaction {
  218. struct sockaddr_in addr; /*!< Other end of transaction */
  219. struct timeval start; /*!< When this transaction was created */
  220. dundi_eid eids[DUNDI_MAX_STACK + 1];
  221. int eidcount; /*!< Number of eids in eids */
  222. dundi_eid us_eid; /*!< Our EID, to them */
  223. dundi_eid them_eid; /*!< Their EID, to us */
  224. ast_aes_encrypt_key ecx; /*!< AES 128 Encryption context */
  225. ast_aes_decrypt_key dcx; /*!< AES 128 Decryption context */
  226. unsigned int flags; /*!< Has final packet been sent */
  227. int ttl; /*!< Remaining TTL for queries on this one */
  228. int thread; /*!< We have a calling thread */
  229. int retranstimer; /*!< How long to wait before retransmissions */
  230. int autokillid; /*!< ID to kill connection if answer doesn't come back fast enough */
  231. int autokilltimeout; /*!< Recommended timeout for autokill */
  232. unsigned short strans; /*!< Our transaction identifier */
  233. unsigned short dtrans; /*!< Their transaction identifer */
  234. unsigned char iseqno; /*!< Next expected received seqno */
  235. unsigned char oiseqno; /*!< Last received incoming seqno */
  236. unsigned char oseqno; /*!< Next transmitted seqno */
  237. unsigned char aseqno; /*!< Last acknowledge seqno */
  238. AST_LIST_HEAD_NOLOCK(packetlist, dundi_packet) packets; /*!< Packets to be retransmitted */
  239. struct packetlist lasttrans; /*!< Last transmitted / ACK'd packet */
  240. struct dundi_request *parent; /*!< Parent request (if there is one) */
  241. AST_LIST_ENTRY(dundi_transaction) parentlist; /*!< Next with respect to the parent */
  242. AST_LIST_ENTRY(dundi_transaction) all; /*!< Next with respect to all DUNDi transactions */
  243. };
  244. struct dundi_request {
  245. char dcontext[AST_MAX_EXTENSION];
  246. char number[AST_MAX_EXTENSION];
  247. dundi_eid query_eid;
  248. dundi_eid root_eid;
  249. struct dundi_result *dr;
  250. struct dundi_entity_info *dei;
  251. struct dundi_hint_metadata *hmd;
  252. int maxcount;
  253. int respcount;
  254. int expiration;
  255. int cbypass;
  256. int pfds[2];
  257. uint32_t crc32; /*!< CRC-32 of all but root EID's in avoid list */
  258. AST_LIST_HEAD_NOLOCK(, dundi_transaction) trans; /*!< Transactions */
  259. AST_LIST_ENTRY(dundi_request) list;
  260. };
  261. struct dundi_mapping {
  262. char dcontext[AST_MAX_EXTENSION];
  263. char lcontext[AST_MAX_EXTENSION];
  264. int _weight;
  265. char *weightstr;
  266. int options;
  267. int tech;
  268. int dead;
  269. char dest[512];
  270. AST_LIST_ENTRY(dundi_mapping) list;
  271. };
  272. struct dundi_peer {
  273. dundi_eid eid;
  274. struct sockaddr_in addr; /*!< Address of DUNDi peer */
  275. AST_LIST_HEAD_NOLOCK(permissionlist, permission) permit;
  276. struct permissionlist include;
  277. dundi_eid us_eid;
  278. char inkey[80];
  279. char outkey[80];
  280. int dead;
  281. int registerid;
  282. int qualifyid;
  283. int sentfullkey;
  284. int order;
  285. unsigned char txenckey[256]; /*!< Transmitted encrypted key + sig */
  286. unsigned char rxenckey[256]; /*!< Cache received encrypted key + sig */
  287. uint32_t us_keycrc32; /*!< CRC-32 of our key */
  288. ast_aes_encrypt_key us_ecx; /*!< Cached AES 128 Encryption context */
  289. ast_aes_decrypt_key us_dcx; /*!< Cached AES 128 Decryption context */
  290. uint32_t them_keycrc32; /*!< CRC-32 of our key */
  291. ast_aes_encrypt_key them_ecx; /*!< Cached AES 128 Encryption context */
  292. ast_aes_decrypt_key them_dcx; /*!< Cached AES 128 Decryption context */
  293. time_t keyexpire; /*!< When to expire/recreate key */
  294. int registerexpire;
  295. int lookuptimes[DUNDI_TIMING_HISTORY];
  296. char *lookups[DUNDI_TIMING_HISTORY];
  297. int avgms;
  298. struct dundi_transaction *regtrans; /*!< Registration transaction */
  299. struct dundi_transaction *qualtrans; /*!< Qualify transaction */
  300. int model; /*!< Pull model */
  301. int pcmodel; /*!< Push/precache model */
  302. /*! Dynamic peers register with us */
  303. unsigned int dynamic:1;
  304. int lastms; /*!< Last measured latency */
  305. int maxms; /*!< Max permissible latency */
  306. struct timeval qualtx; /*!< Time of transmit */
  307. AST_LIST_ENTRY(dundi_peer) list;
  308. };
  309. static AST_LIST_HEAD_STATIC(peers, dundi_peer);
  310. static AST_LIST_HEAD_STATIC(pcq, dundi_precache_queue);
  311. static AST_LIST_HEAD_NOLOCK_STATIC(mappings, dundi_mapping);
  312. static AST_LIST_HEAD_NOLOCK_STATIC(requests, dundi_request);
  313. static AST_LIST_HEAD_NOLOCK_STATIC(alltrans, dundi_transaction);
  314. /*!
  315. * \brief Wildcard peer
  316. *
  317. * This peer is created if the [*] entry is specified in dundi.conf
  318. */
  319. static struct dundi_peer *any_peer;
  320. static int dundi_xmit(struct dundi_packet *pack);
  321. static void dundi_debug_output(const char *data)
  322. {
  323. if (dundidebug)
  324. ast_verbose("%s", data);
  325. }
  326. static void dundi_error_output(const char *data)
  327. {
  328. ast_log(LOG_WARNING, "%s", data);
  329. }
  330. static int has_permission(struct permissionlist *permlist, char *cont)
  331. {
  332. struct permission *perm;
  333. int res = 0;
  334. AST_LIST_TRAVERSE(permlist, perm, list) {
  335. if (!strcasecmp(perm->name, "all") || !strcasecmp(perm->name, cont))
  336. res = perm->allow;
  337. }
  338. return res;
  339. }
  340. static char *tech2str(int tech)
  341. {
  342. switch(tech) {
  343. case DUNDI_PROTO_NONE:
  344. return "None";
  345. case DUNDI_PROTO_IAX:
  346. return "IAX2";
  347. case DUNDI_PROTO_SIP:
  348. return "SIP";
  349. case DUNDI_PROTO_H323:
  350. return "H323";
  351. default:
  352. return "Unknown";
  353. }
  354. }
  355. static int str2tech(char *str)
  356. {
  357. if (!strcasecmp(str, "IAX") || !strcasecmp(str, "IAX2"))
  358. return DUNDI_PROTO_IAX;
  359. else if (!strcasecmp(str, "SIP"))
  360. return DUNDI_PROTO_SIP;
  361. else if (!strcasecmp(str, "H323"))
  362. return DUNDI_PROTO_H323;
  363. else
  364. return -1;
  365. }
  366. static int dundi_lookup_internal(struct dundi_result *result, int maxret, struct ast_channel *chan, const char *dcontext, const char *number, int ttl, int blockempty, struct dundi_hint_metadata *md, int *expiration, int cybpass, int modeselect, dundi_eid *skip, dundi_eid *avoid[], int direct[]);
  367. static int dundi_precache_internal(const char *context, const char *number, int ttl, dundi_eid *avoids[]);
  368. static struct dundi_transaction *create_transaction(struct dundi_peer *p);
  369. static struct dundi_transaction *find_transaction(struct dundi_hdr *hdr, struct sockaddr_in *sin)
  370. {
  371. struct dundi_transaction *trans;
  372. /* Look for an exact match first */
  373. AST_LIST_TRAVERSE(&alltrans, trans, all) {
  374. if (!inaddrcmp(&trans->addr, sin) &&
  375. ((trans->strans == (ntohs(hdr->dtrans) & 32767)) /* Matches our destination */ ||
  376. ((trans->dtrans == (ntohs(hdr->strans) & 32767)) && (!hdr->dtrans))) /* We match their destination */) {
  377. if (hdr->strans)
  378. trans->dtrans = ntohs(hdr->strans) & 32767;
  379. return trans;
  380. }
  381. }
  382. switch(hdr->cmdresp & 0x7f) {
  383. case DUNDI_COMMAND_DPDISCOVER:
  384. case DUNDI_COMMAND_EIDQUERY:
  385. case DUNDI_COMMAND_PRECACHERQ:
  386. case DUNDI_COMMAND_REGREQ:
  387. case DUNDI_COMMAND_NULL:
  388. case DUNDI_COMMAND_ENCRYPT:
  389. if (!hdr->strans)
  390. break;
  391. /* Create new transaction */
  392. if (!(trans = create_transaction(NULL)))
  393. break;
  394. memcpy(&trans->addr, sin, sizeof(trans->addr));
  395. trans->dtrans = ntohs(hdr->strans) & 32767;
  396. default:
  397. break;
  398. }
  399. return trans;
  400. }
  401. static int dundi_send(struct dundi_transaction *trans, int cmdresp, int flags, int final, struct dundi_ie_data *ied);
  402. static int dundi_ack(struct dundi_transaction *trans, int final)
  403. {
  404. return dundi_send(trans, DUNDI_COMMAND_ACK, 0, final, NULL);
  405. }
  406. static void dundi_reject(struct dundi_hdr *h, struct sockaddr_in *sin)
  407. {
  408. struct {
  409. struct dundi_packet pack;
  410. struct dundi_hdr hdr;
  411. } tmp;
  412. struct dundi_transaction trans;
  413. /* Never respond to an INVALID with another INVALID */
  414. if (h->cmdresp == DUNDI_COMMAND_INVALID)
  415. return;
  416. memset(&tmp, 0, sizeof(tmp));
  417. memset(&trans, 0, sizeof(trans));
  418. memcpy(&trans.addr, sin, sizeof(trans.addr));
  419. tmp.hdr.strans = h->dtrans;
  420. tmp.hdr.dtrans = h->strans;
  421. tmp.hdr.iseqno = h->oseqno;
  422. tmp.hdr.oseqno = h->iseqno;
  423. tmp.hdr.cmdresp = DUNDI_COMMAND_INVALID;
  424. tmp.hdr.cmdflags = 0;
  425. tmp.pack.h = (struct dundi_hdr *)tmp.pack.data;
  426. tmp.pack.datalen = sizeof(struct dundi_hdr);
  427. tmp.pack.parent = &trans;
  428. dundi_xmit(&tmp.pack);
  429. }
  430. static int get_trans_id(void)
  431. {
  432. struct dundi_transaction *t;
  433. int stid = (ast_random() % 32766) + 1;
  434. int tid = stid;
  435. do {
  436. AST_LIST_TRAVERSE(&alltrans, t, all) {
  437. if (t->strans == tid)
  438. break;
  439. }
  440. if (!t)
  441. return tid;
  442. tid = (tid % 32766) + 1;
  443. } while (tid != stid);
  444. return 0;
  445. }
  446. static int reset_transaction(struct dundi_transaction *trans)
  447. {
  448. int tid;
  449. tid = get_trans_id();
  450. if (tid < 1)
  451. return -1;
  452. trans->strans = tid;
  453. trans->dtrans = 0;
  454. trans->iseqno = 0;
  455. trans->oiseqno = 0;
  456. trans->oseqno = 0;
  457. trans->aseqno = 0;
  458. ast_clear_flag(trans, FLAG_FINAL);
  459. return 0;
  460. }
  461. static struct dundi_peer *find_peer(dundi_eid *eid)
  462. {
  463. struct dundi_peer *cur = NULL;
  464. if (!eid)
  465. eid = &empty_eid;
  466. AST_LIST_TRAVERSE(&peers, cur, list) {
  467. if (!ast_eid_cmp(&cur->eid,eid))
  468. break;
  469. }
  470. if (!cur && any_peer)
  471. cur = any_peer;
  472. return cur;
  473. }
  474. static void build_iv(unsigned char *iv)
  475. {
  476. /* XXX Would be nice to be more random XXX */
  477. unsigned int *fluffy;
  478. int x;
  479. fluffy = (unsigned int *)(iv);
  480. for (x=0;x<4;x++)
  481. fluffy[x] = ast_random();
  482. }
  483. struct dundi_query_state {
  484. dundi_eid *eids[DUNDI_MAX_STACK + 1];
  485. int directs[DUNDI_MAX_STACK + 1];
  486. dundi_eid reqeid;
  487. char called_context[AST_MAX_EXTENSION];
  488. char called_number[AST_MAX_EXTENSION];
  489. struct dundi_mapping *maps;
  490. int nummaps;
  491. int nocache;
  492. struct dundi_transaction *trans;
  493. void *chal;
  494. int challen;
  495. int ttl;
  496. char fluffy[0];
  497. };
  498. static int get_mapping_weight(struct dundi_mapping *map, struct varshead *headp)
  499. {
  500. char buf[32];
  501. buf[0] = 0;
  502. if (map->weightstr) {
  503. if (headp) {
  504. pbx_substitute_variables_varshead(headp, map->weightstr, buf, sizeof(buf) - 1);
  505. } else {
  506. pbx_substitute_variables_helper(NULL, map->weightstr, buf, sizeof(buf) - 1);
  507. }
  508. if (sscanf(buf, "%30d", &map->_weight) != 1)
  509. map->_weight = MAX_WEIGHT;
  510. }
  511. return map->_weight;
  512. }
  513. static int dundi_lookup_local(struct dundi_result *dr, struct dundi_mapping *map, char *called_number, dundi_eid *us_eid, int anscnt, struct dundi_hint_metadata *hmd)
  514. {
  515. struct ast_flags flags = {0};
  516. int x;
  517. if (!ast_strlen_zero(map->lcontext)) {
  518. if (ast_exists_extension(NULL, map->lcontext, called_number, 1, NULL))
  519. ast_set_flag(&flags, DUNDI_FLAG_EXISTS);
  520. if (ast_canmatch_extension(NULL, map->lcontext, called_number, 1, NULL))
  521. ast_set_flag(&flags, DUNDI_FLAG_CANMATCH);
  522. if (ast_matchmore_extension(NULL, map->lcontext, called_number, 1, NULL))
  523. ast_set_flag(&flags, DUNDI_FLAG_MATCHMORE);
  524. if (ast_ignore_pattern(map->lcontext, called_number))
  525. ast_set_flag(&flags, DUNDI_FLAG_IGNOREPAT);
  526. /* Clearly we can't say 'don't ask' anymore if we found anything... */
  527. if (ast_test_flag(&flags, AST_FLAGS_ALL))
  528. ast_clear_flag_nonstd(hmd, DUNDI_HINT_DONT_ASK);
  529. if (map->options & DUNDI_FLAG_INTERNAL_NOPARTIAL) {
  530. /* Skip partial answers */
  531. ast_clear_flag(&flags, DUNDI_FLAG_MATCHMORE|DUNDI_FLAG_CANMATCH);
  532. }
  533. if (ast_test_flag(&flags, AST_FLAGS_ALL)) {
  534. struct varshead headp;
  535. struct ast_var_t *newvariable;
  536. ast_set_flag(&flags, map->options & 0xffff);
  537. ast_copy_flags(dr + anscnt, &flags, AST_FLAGS_ALL);
  538. dr[anscnt].techint = map->tech;
  539. dr[anscnt].expiration = dundi_cache_time;
  540. ast_copy_string(dr[anscnt].tech, tech2str(map->tech), sizeof(dr[anscnt].tech));
  541. dr[anscnt].eid = *us_eid;
  542. ast_eid_to_str(dr[anscnt].eid_str, sizeof(dr[anscnt].eid_str), &dr[anscnt].eid);
  543. if (ast_test_flag(&flags, DUNDI_FLAG_EXISTS)) {
  544. AST_LIST_HEAD_INIT_NOLOCK(&headp);
  545. if ((newvariable = ast_var_assign("NUMBER", called_number))) {
  546. AST_LIST_INSERT_HEAD(&headp, newvariable, entries);
  547. }
  548. if ((newvariable = ast_var_assign("EID", dr[anscnt].eid_str))) {
  549. AST_LIST_INSERT_HEAD(&headp, newvariable, entries);
  550. }
  551. if ((newvariable = ast_var_assign("SECRET", cursecret))) {
  552. AST_LIST_INSERT_HEAD(&headp, newvariable, entries);
  553. }
  554. if ((newvariable = ast_var_assign("IPADDR", ipaddr))) {
  555. AST_LIST_INSERT_HEAD(&headp, newvariable, entries);
  556. }
  557. pbx_substitute_variables_varshead(&headp, map->dest, dr[anscnt].dest, sizeof(dr[anscnt].dest));
  558. dr[anscnt].weight = get_mapping_weight(map, &headp);
  559. while ((newvariable = AST_LIST_REMOVE_HEAD(&headp, entries)))
  560. ast_var_delete(newvariable);
  561. } else {
  562. dr[anscnt].dest[0] = '\0';
  563. dr[anscnt].weight = get_mapping_weight(map, NULL);
  564. }
  565. anscnt++;
  566. } else {
  567. /* No answers... Find the fewest number of digits from the
  568. number for which we have no answer. */
  569. char tmp[AST_MAX_EXTENSION + 1] = "";
  570. for (x = 0; x < (sizeof(tmp) - 1); x++) {
  571. tmp[x] = called_number[x];
  572. if (!tmp[x])
  573. break;
  574. if (!ast_canmatch_extension(NULL, map->lcontext, tmp, 1, NULL)) {
  575. /* Oops found something we can't match. If this is longer
  576. than the running hint, we have to consider it */
  577. if (strlen(tmp) > strlen(hmd->exten)) {
  578. ast_copy_string(hmd->exten, tmp, sizeof(hmd->exten));
  579. }
  580. break;
  581. }
  582. }
  583. }
  584. }
  585. return anscnt;
  586. }
  587. static void destroy_trans(struct dundi_transaction *trans, int fromtimeout);
  588. static void *dundi_lookup_thread(void *data)
  589. {
  590. struct dundi_query_state *st = data;
  591. struct dundi_result dr[MAX_RESULTS];
  592. struct dundi_ie_data ied;
  593. struct dundi_hint_metadata hmd;
  594. char eid_str[20];
  595. int res, x;
  596. int ouranswers=0;
  597. int max = 999999;
  598. int expiration = dundi_cache_time;
  599. ast_debug(1, "Whee, looking up '%s@%s' for '%s'\n", st->called_number, st->called_context,
  600. st->eids[0] ? ast_eid_to_str(eid_str, sizeof(eid_str), st->eids[0]) : "ourselves");
  601. memset(&ied, 0, sizeof(ied));
  602. memset(&dr, 0, sizeof(dr));
  603. memset(&hmd, 0, sizeof(hmd));
  604. /* Assume 'don't ask for anything' and 'unaffected', no TTL expired */
  605. hmd.flags = DUNDI_HINT_DONT_ASK | DUNDI_HINT_UNAFFECTED;
  606. for (x=0;x<st->nummaps;x++)
  607. ouranswers = dundi_lookup_local(dr, st->maps + x, st->called_number, &st->trans->us_eid, ouranswers, &hmd);
  608. if (ouranswers < 0)
  609. ouranswers = 0;
  610. for (x=0;x<ouranswers;x++) {
  611. if (dr[x].weight < max)
  612. max = dr[x].weight;
  613. }
  614. if (max) {
  615. /* If we do not have a canonical result, keep looking */
  616. res = dundi_lookup_internal(dr + ouranswers, MAX_RESULTS - ouranswers, NULL, st->called_context, st->called_number, st->ttl, 1, &hmd, &expiration, st->nocache, 0, NULL, st->eids, st->directs);
  617. if (res > 0) {
  618. /* Append answer in result */
  619. ouranswers += res;
  620. } else {
  621. if ((res < -1) && (!ouranswers))
  622. dundi_ie_append_cause(&ied, DUNDI_IE_CAUSE, DUNDI_CAUSE_DUPLICATE, "Duplicate Request Pending");
  623. }
  624. }
  625. AST_LIST_LOCK(&peers);
  626. /* Truncate if "don't ask" isn't present */
  627. if (!ast_test_flag_nonstd(&hmd, DUNDI_HINT_DONT_ASK))
  628. hmd.exten[0] = '\0';
  629. if (ast_test_flag(st->trans, FLAG_DEAD)) {
  630. ast_debug(1, "Our transaction went away!\n");
  631. st->trans->thread = 0;
  632. destroy_trans(st->trans, 0);
  633. } else {
  634. for (x=0;x<ouranswers;x++) {
  635. /* Add answers */
  636. if (dr[x].expiration && (expiration > dr[x].expiration))
  637. expiration = dr[x].expiration;
  638. dundi_ie_append_answer(&ied, DUNDI_IE_ANSWER, &dr[x].eid, dr[x].techint, dr[x].flags, dr[x].weight, dr[x].dest);
  639. }
  640. dundi_ie_append_hint(&ied, DUNDI_IE_HINT, hmd.flags, hmd.exten);
  641. dundi_ie_append_short(&ied, DUNDI_IE_EXPIRATION, expiration);
  642. dundi_send(st->trans, DUNDI_COMMAND_DPRESPONSE, 0, 1, &ied);
  643. st->trans->thread = 0;
  644. }
  645. AST_LIST_UNLOCK(&peers);
  646. ast_free(st);
  647. return NULL;
  648. }
  649. static void *dundi_precache_thread(void *data)
  650. {
  651. struct dundi_query_state *st = data;
  652. struct dundi_ie_data ied;
  653. struct dundi_hint_metadata hmd;
  654. char eid_str[20];
  655. ast_debug(1, "Whee, precaching '%s@%s' for '%s'\n", st->called_number, st->called_context,
  656. st->eids[0] ? ast_eid_to_str(eid_str, sizeof(eid_str), st->eids[0]) : "ourselves");
  657. memset(&ied, 0, sizeof(ied));
  658. /* Now produce precache */
  659. dundi_precache_internal(st->called_context, st->called_number, st->ttl, st->eids);
  660. AST_LIST_LOCK(&peers);
  661. /* Truncate if "don't ask" isn't present */
  662. if (!ast_test_flag_nonstd(&hmd, DUNDI_HINT_DONT_ASK))
  663. hmd.exten[0] = '\0';
  664. if (ast_test_flag(st->trans, FLAG_DEAD)) {
  665. ast_debug(1, "Our transaction went away!\n");
  666. st->trans->thread = 0;
  667. destroy_trans(st->trans, 0);
  668. } else {
  669. dundi_send(st->trans, DUNDI_COMMAND_PRECACHERP, 0, 1, &ied);
  670. st->trans->thread = 0;
  671. }
  672. AST_LIST_UNLOCK(&peers);
  673. ast_free(st);
  674. return NULL;
  675. }
  676. static int dundi_query_eid_internal(struct dundi_entity_info *dei, const char *dcontext, dundi_eid *eid, struct dundi_hint_metadata *hmd, int ttl, int blockempty, dundi_eid *avoid[]);
  677. static void *dundi_query_thread(void *data)
  678. {
  679. struct dundi_query_state *st = data;
  680. struct dundi_entity_info dei;
  681. struct dundi_ie_data ied;
  682. struct dundi_hint_metadata hmd;
  683. char eid_str[20];
  684. int res;
  685. ast_debug(1, "Whee, looking up '%s@%s' for '%s'\n", st->called_number, st->called_context,
  686. st->eids[0] ? ast_eid_to_str(eid_str, sizeof(eid_str), st->eids[0]) : "ourselves");
  687. memset(&ied, 0, sizeof(ied));
  688. memset(&dei, 0, sizeof(dei));
  689. memset(&hmd, 0, sizeof(hmd));
  690. if (!ast_eid_cmp(&st->trans->us_eid, &st->reqeid)) {
  691. /* Ooh, it's us! */
  692. ast_debug(1, "Neat, someone look for us!\n");
  693. ast_copy_string(dei.orgunit, dept, sizeof(dei.orgunit));
  694. ast_copy_string(dei.org, org, sizeof(dei.org));
  695. ast_copy_string(dei.locality, locality, sizeof(dei.locality));
  696. ast_copy_string(dei.stateprov, stateprov, sizeof(dei.stateprov));
  697. ast_copy_string(dei.country, country, sizeof(dei.country));
  698. ast_copy_string(dei.email, email, sizeof(dei.email));
  699. ast_copy_string(dei.phone, phone, sizeof(dei.phone));
  700. res = 1;
  701. } else {
  702. /* If we do not have a canonical result, keep looking */
  703. res = dundi_query_eid_internal(&dei, st->called_context, &st->reqeid, &hmd, st->ttl, 1, st->eids);
  704. }
  705. AST_LIST_LOCK(&peers);
  706. if (ast_test_flag(st->trans, FLAG_DEAD)) {
  707. ast_debug(1, "Our transaction went away!\n");
  708. st->trans->thread = 0;
  709. destroy_trans(st->trans, 0);
  710. } else {
  711. if (res) {
  712. dundi_ie_append_str(&ied, DUNDI_IE_DEPARTMENT, dei.orgunit);
  713. dundi_ie_append_str(&ied, DUNDI_IE_ORGANIZATION, dei.org);
  714. dundi_ie_append_str(&ied, DUNDI_IE_LOCALITY, dei.locality);
  715. dundi_ie_append_str(&ied, DUNDI_IE_STATE_PROV, dei.stateprov);
  716. dundi_ie_append_str(&ied, DUNDI_IE_COUNTRY, dei.country);
  717. dundi_ie_append_str(&ied, DUNDI_IE_EMAIL, dei.email);
  718. dundi_ie_append_str(&ied, DUNDI_IE_PHONE, dei.phone);
  719. if (!ast_strlen_zero(dei.ipaddr))
  720. dundi_ie_append_str(&ied, DUNDI_IE_IPADDR, dei.ipaddr);
  721. }
  722. dundi_ie_append_hint(&ied, DUNDI_IE_HINT, hmd.flags, hmd.exten);
  723. dundi_send(st->trans, DUNDI_COMMAND_EIDRESPONSE, 0, 1, &ied);
  724. st->trans->thread = 0;
  725. }
  726. AST_LIST_UNLOCK(&peers);
  727. ast_free(st);
  728. return NULL;
  729. }
  730. static int dundi_answer_entity(struct dundi_transaction *trans, struct dundi_ies *ies, char *ccontext)
  731. {
  732. struct dundi_query_state *st;
  733. int totallen;
  734. int x;
  735. int skipfirst=0;
  736. char eid_str[20];
  737. char *s;
  738. pthread_t lookupthread;
  739. if (ies->eidcount > 1) {
  740. /* Since it is a requirement that the first EID is the authenticating host
  741. and the last EID is the root, it is permissible that the first and last EID
  742. could be the same. In that case, we should go ahead copy only the "root" section
  743. since we will not need it for authentication. */
  744. if (!ast_eid_cmp(ies->eids[0], ies->eids[ies->eidcount - 1]))
  745. skipfirst = 1;
  746. }
  747. totallen = sizeof(struct dundi_query_state);
  748. totallen += (ies->eidcount - skipfirst) * sizeof(dundi_eid);
  749. st = ast_calloc(1, totallen);
  750. if (st) {
  751. ast_copy_string(st->called_context, ies->called_context, sizeof(st->called_context));
  752. memcpy(&st->reqeid, ies->reqeid, sizeof(st->reqeid));
  753. st->trans = trans;
  754. st->ttl = ies->ttl - 1;
  755. if (st->ttl < 0)
  756. st->ttl = 0;
  757. s = st->fluffy;
  758. for (x=skipfirst;ies->eids[x];x++) {
  759. st->eids[x-skipfirst] = (dundi_eid *)s;
  760. *st->eids[x-skipfirst] = *ies->eids[x];
  761. s += sizeof(dundi_eid);
  762. }
  763. ast_debug(1, "Answering EID query for '%s@%s'!\n", ast_eid_to_str(eid_str, sizeof(eid_str), ies->reqeid), ies->called_context);
  764. trans->thread = 1;
  765. if (ast_pthread_create_detached(&lookupthread, NULL, dundi_query_thread, st)) {
  766. struct dundi_ie_data ied = { 0, };
  767. trans->thread = 0;
  768. ast_log(LOG_WARNING, "Unable to create thread!\n");
  769. ast_free(st);
  770. dundi_ie_append_cause(&ied, DUNDI_IE_CAUSE, DUNDI_CAUSE_GENERAL, "Out of threads");
  771. dundi_send(trans, DUNDI_COMMAND_EIDRESPONSE, 0, 1, &ied);
  772. return -1;
  773. }
  774. } else {
  775. struct dundi_ie_data ied = { 0, };
  776. dundi_ie_append_cause(&ied, DUNDI_IE_CAUSE, DUNDI_CAUSE_GENERAL, "Out of memory");
  777. dundi_send(trans, DUNDI_COMMAND_EIDRESPONSE, 0, 1, &ied);
  778. return -1;
  779. }
  780. return 0;
  781. }
  782. static int cache_save_hint(dundi_eid *eidpeer, struct dundi_request *req, struct dundi_hint *hint, int expiration)
  783. {
  784. int unaffected;
  785. char key1[256];
  786. char key2[256];
  787. char eidpeer_str[20];
  788. char eidroot_str[20];
  789. char data[80];
  790. time_t timeout;
  791. if (expiration < 0)
  792. expiration = dundi_cache_time;
  793. /* Only cache hint if "don't ask" is there... */
  794. if (!ast_test_flag_nonstd(hint, htons(DUNDI_HINT_DONT_ASK)))
  795. return 0;
  796. unaffected = ast_test_flag_nonstd(hint, htons(DUNDI_HINT_UNAFFECTED));
  797. dundi_eid_to_str_short(eidpeer_str, sizeof(eidpeer_str), eidpeer);
  798. dundi_eid_to_str_short(eidroot_str, sizeof(eidroot_str), &req->root_eid);
  799. snprintf(key1, sizeof(key1), "hint/%s/%s/%s/e%08x", eidpeer_str, hint->data, req->dcontext, unaffected ? 0 : req->crc32);
  800. snprintf(key2, sizeof(key2), "hint/%s/%s/%s/r%s", eidpeer_str, hint->data, req->dcontext, eidroot_str);
  801. time(&timeout);
  802. timeout += expiration;
  803. snprintf(data, sizeof(data), "%ld|", (long)(timeout));
  804. ast_db_put("dundi/cache", key1, data);
  805. ast_debug(1, "Caching hint at '%s'\n", key1);
  806. ast_db_put("dundi/cache", key2, data);
  807. ast_debug(1, "Caching hint at '%s'\n", key2);
  808. return 0;
  809. }
  810. static int cache_save(dundi_eid *eidpeer, struct dundi_request *req, int start, int unaffected, int expiration, int push)
  811. {
  812. int x;
  813. char key1[256];
  814. char key2[256];
  815. char data[1024];
  816. char eidpeer_str[20];
  817. char eidroot_str[20];
  818. time_t timeout;
  819. if (expiration < 1)
  820. expiration = dundi_cache_time;
  821. /* Keep pushes a little longer, cut pulls a little short */
  822. if (push)
  823. expiration += 10;
  824. else
  825. expiration -= 10;
  826. if (expiration < 1)
  827. expiration = 1;
  828. dundi_eid_to_str_short(eidpeer_str, sizeof(eidpeer_str), eidpeer);
  829. dundi_eid_to_str_short(eidroot_str, sizeof(eidroot_str), &req->root_eid);
  830. snprintf(key1, sizeof(key1), "%s/%s/%s/e%08x", eidpeer_str, req->number, req->dcontext, unaffected ? 0 : req->crc32);
  831. snprintf(key2, sizeof(key2), "%s/%s/%s/r%s", eidpeer_str, req->number, req->dcontext, eidroot_str);
  832. /* Build request string */
  833. time(&timeout);
  834. timeout += expiration;
  835. snprintf(data, sizeof(data), "%ld|", (long)(timeout));
  836. for (x=start;x<req->respcount;x++) {
  837. /* Skip anything with an illegal pipe in it */
  838. if (strchr(req->dr[x].dest, '|'))
  839. continue;
  840. snprintf(data + strlen(data), sizeof(data) - strlen(data), "%u/%d/%d/%s/%s|",
  841. req->dr[x].flags, req->dr[x].weight, req->dr[x].techint, req->dr[x].dest,
  842. dundi_eid_to_str_short(eidpeer_str, sizeof(eidpeer_str), &req->dr[x].eid));
  843. }
  844. ast_db_put("dundi/cache", key1, data);
  845. ast_db_put("dundi/cache", key2, data);
  846. return 0;
  847. }
  848. static int dundi_prop_precache(struct dundi_transaction *trans, struct dundi_ies *ies, char *ccontext)
  849. {
  850. struct dundi_query_state *st;
  851. int totallen;
  852. int x,z;
  853. struct dundi_ie_data ied;
  854. char *s;
  855. struct dundi_result dr2[MAX_RESULTS];
  856. struct dundi_request dr;
  857. struct dundi_hint_metadata hmd;
  858. struct dundi_mapping *cur;
  859. int mapcount;
  860. int skipfirst = 0;
  861. pthread_t lookupthread;
  862. memset(&dr2, 0, sizeof(dr2));
  863. memset(&dr, 0, sizeof(dr));
  864. memset(&hmd, 0, sizeof(hmd));
  865. /* Forge request structure to hold answers for cache */
  866. hmd.flags = DUNDI_HINT_DONT_ASK | DUNDI_HINT_UNAFFECTED;
  867. dr.dr = dr2;
  868. dr.maxcount = MAX_RESULTS;
  869. dr.expiration = dundi_cache_time;
  870. dr.hmd = &hmd;
  871. dr.pfds[0] = dr.pfds[1] = -1;
  872. trans->parent = &dr;
  873. ast_copy_string(dr.dcontext, ies->called_context ? ies->called_context : "e164", sizeof(dr.dcontext));
  874. ast_copy_string(dr.number, ies->called_number, sizeof(dr.number));
  875. for (x=0;x<ies->anscount;x++) {
  876. if (trans->parent->respcount < trans->parent->maxcount) {
  877. /* Make sure it's not already there */
  878. for (z=0;z<trans->parent->respcount;z++) {
  879. if ((trans->parent->dr[z].techint == ies->answers[x]->protocol) &&
  880. !strcmp(trans->parent->dr[z].dest, (char *)ies->answers[x]->data))
  881. break;
  882. }
  883. if (z == trans->parent->respcount) {
  884. /* Copy into parent responses */
  885. trans->parent->dr[trans->parent->respcount].flags = ntohs(ies->answers[x]->flags);
  886. trans->parent->dr[trans->parent->respcount].techint = ies->answers[x]->protocol;
  887. trans->parent->dr[trans->parent->respcount].weight = ntohs(ies->answers[x]->weight);
  888. trans->parent->dr[trans->parent->respcount].eid = ies->answers[x]->eid;
  889. if (ies->expiration > 0)
  890. trans->parent->dr[trans->parent->respcount].expiration = ies->expiration;
  891. else
  892. trans->parent->dr[trans->parent->respcount].expiration = dundi_cache_time;
  893. ast_eid_to_str(trans->parent->dr[trans->parent->respcount].eid_str,
  894. sizeof(trans->parent->dr[trans->parent->respcount].eid_str),
  895. &ies->answers[x]->eid);
  896. ast_copy_string(trans->parent->dr[trans->parent->respcount].dest, (char *)ies->answers[x]->data,
  897. sizeof(trans->parent->dr[trans->parent->respcount].dest));
  898. ast_copy_string(trans->parent->dr[trans->parent->respcount].tech, tech2str(ies->answers[x]->protocol),
  899. sizeof(trans->parent->dr[trans->parent->respcount].tech));
  900. trans->parent->respcount++;
  901. ast_clear_flag_nonstd(trans->parent->hmd, DUNDI_HINT_DONT_ASK);
  902. } else if (trans->parent->dr[z].weight > ntohs(ies->answers[x]->weight)) {
  903. /* Update weight if appropriate */
  904. trans->parent->dr[z].weight = ntohs(ies->answers[x]->weight);
  905. }
  906. } else
  907. ast_log(LOG_NOTICE, "Dropping excessive answers in precache for %s@%s\n",
  908. trans->parent->number, trans->parent->dcontext);
  909. }
  910. /* Save all the results (if any) we had. Even if no results, still cache lookup. */
  911. cache_save(&trans->them_eid, trans->parent, 0, 0, ies->expiration, 1);
  912. if (ies->hint)
  913. cache_save_hint(&trans->them_eid, trans->parent, ies->hint, ies->expiration);
  914. totallen = sizeof(struct dundi_query_state);
  915. /* Count matching map entries */
  916. mapcount = 0;
  917. AST_LIST_TRAVERSE(&mappings, cur, list) {
  918. if (!strcasecmp(cur->dcontext, ccontext))
  919. mapcount++;
  920. }
  921. /* If no maps, return -1 immediately */
  922. if (!mapcount)
  923. return -1;
  924. if (ies->eidcount > 1) {
  925. /* Since it is a requirement that the first EID is the authenticating host
  926. and the last EID is the root, it is permissible that the first and last EID
  927. could be the same. In that case, we should go ahead copy only the "root" section
  928. since we will not need it for authentication. */
  929. if (!ast_eid_cmp(ies->eids[0], ies->eids[ies->eidcount - 1]))
  930. skipfirst = 1;
  931. }
  932. /* Prepare to run a query and then propagate that as necessary */
  933. totallen += mapcount * sizeof(struct dundi_mapping);
  934. totallen += (ies->eidcount - skipfirst) * sizeof(dundi_eid);
  935. st = ast_calloc(1, totallen);
  936. if (st) {
  937. ast_copy_string(st->called_context, dr.dcontext, sizeof(st->called_context));
  938. ast_copy_string(st->called_number, ies->called_number, sizeof(st->called_number));
  939. st->trans = trans;
  940. st->ttl = ies->ttl - 1;
  941. st->nocache = ies->cbypass;
  942. if (st->ttl < 0)
  943. st->ttl = 0;
  944. s = st->fluffy;
  945. for (x=skipfirst;ies->eids[x];x++) {
  946. st->eids[x-skipfirst] = (dundi_eid *)s;
  947. *st->eids[x-skipfirst] = *ies->eids[x];
  948. st->directs[x-skipfirst] = ies->eid_direct[x];
  949. s += sizeof(dundi_eid);
  950. }
  951. /* Append mappings */
  952. x = 0;
  953. st->maps = (struct dundi_mapping *)s;
  954. AST_LIST_TRAVERSE(&mappings, cur, list) {
  955. if (!strcasecmp(cur->dcontext, ccontext)) {
  956. if (x < mapcount) {
  957. st->maps[x] = *cur;
  958. st->maps[x].list.next = NULL;
  959. x++;
  960. }
  961. }
  962. }
  963. st->nummaps = mapcount;
  964. ast_debug(1, "Forwarding precache for '%s@%s'!\n", ies->called_number, ies->called_context);
  965. trans->thread = 1;
  966. if (ast_pthread_create_detached(&lookupthread, NULL, dundi_precache_thread, st)) {
  967. trans->thread = 0;
  968. ast_log(LOG_WARNING, "Unable to create thread!\n");
  969. ast_free(st);
  970. memset(&ied, 0, sizeof(ied));
  971. dundi_ie_append_cause(&ied, DUNDI_IE_CAUSE, DUNDI_CAUSE_GENERAL, "Out of threads");
  972. dundi_send(trans, DUNDI_COMMAND_PRECACHERP, 0, 1, &ied);
  973. return -1;
  974. }
  975. } else {
  976. ast_log(LOG_WARNING, "Out of memory!\n");
  977. memset(&ied, 0, sizeof(ied));
  978. dundi_ie_append_cause(&ied, DUNDI_IE_CAUSE, DUNDI_CAUSE_GENERAL, "Out of memory");
  979. dundi_send(trans, DUNDI_COMMAND_PRECACHERP, 0, 1, &ied);
  980. return -1;
  981. }
  982. return 0;
  983. }
  984. static int dundi_answer_query(struct dundi_transaction *trans, struct dundi_ies *ies, char *ccontext)
  985. {
  986. struct dundi_query_state *st;
  987. int totallen;
  988. int x;
  989. struct dundi_ie_data ied;
  990. char *s;
  991. struct dundi_mapping *cur;
  992. int mapcount = 0;
  993. int skipfirst = 0;
  994. pthread_t lookupthread;
  995. totallen = sizeof(struct dundi_query_state);
  996. /* Count matching map entries */
  997. AST_LIST_TRAVERSE(&mappings, cur, list) {
  998. if (!strcasecmp(cur->dcontext, ccontext))
  999. mapcount++;
  1000. }
  1001. /* If no maps, return -1 immediately */
  1002. if (!mapcount)
  1003. return -1;
  1004. if (ies->eidcount > 1) {
  1005. /* Since it is a requirement that the first EID is the authenticating host
  1006. and the last EID is the root, it is permissible that the first and last EID
  1007. could be the same. In that case, we should go ahead copy only the "root" section
  1008. since we will not need it for authentication. */
  1009. if (!ast_eid_cmp(ies->eids[0], ies->eids[ies->eidcount - 1]))
  1010. skipfirst = 1;
  1011. }
  1012. totallen += mapcount * sizeof(struct dundi_mapping);
  1013. totallen += (ies->eidcount - skipfirst) * sizeof(dundi_eid);
  1014. st = ast_calloc(1, totallen);
  1015. if (st) {
  1016. ast_copy_string(st->called_context, ies->called_context, sizeof(st->called_context));
  1017. ast_copy_string(st->called_number, ies->called_number, sizeof(st->called_number));
  1018. st->trans = trans;
  1019. st->ttl = ies->ttl - 1;
  1020. st->nocache = ies->cbypass;
  1021. if (st->ttl < 0)
  1022. st->ttl = 0;
  1023. s = st->fluffy;
  1024. for (x=skipfirst;ies->eids[x];x++) {
  1025. st->eids[x-skipfirst] = (dundi_eid *)s;
  1026. *st->eids[x-skipfirst] = *ies->eids[x];
  1027. st->directs[x-skipfirst] = ies->eid_direct[x];
  1028. s += sizeof(dundi_eid);
  1029. }
  1030. /* Append mappings */
  1031. x = 0;
  1032. st->maps = (struct dundi_mapping *)s;
  1033. AST_LIST_TRAVERSE(&mappings, cur, list) {
  1034. if (!strcasecmp(cur->dcontext, ccontext)) {
  1035. if (x < mapcount) {
  1036. st->maps[x] = *cur;
  1037. st->maps[x].list.next = NULL;
  1038. x++;
  1039. }
  1040. }
  1041. }
  1042. st->nummaps = mapcount;
  1043. ast_debug(1, "Answering query for '%s@%s'!\n", ies->called_number, ies->called_context);
  1044. trans->thread = 1;
  1045. if (ast_pthread_create_detached(&lookupthread, NULL, dundi_lookup_thread, st)) {
  1046. trans->thread = 0;
  1047. ast_log(LOG_WARNING, "Unable to create thread!\n");
  1048. ast_free(st);
  1049. memset(&ied, 0, sizeof(ied));
  1050. dundi_ie_append_cause(&ied, DUNDI_IE_CAUSE, DUNDI_CAUSE_GENERAL, "Out of threads");
  1051. dundi_send(trans, DUNDI_COMMAND_DPRESPONSE, 0, 1, &ied);
  1052. return -1;
  1053. }
  1054. } else {
  1055. ast_log(LOG_WARNING, "Out of memory!\n");
  1056. memset(&ied, 0, sizeof(ied));
  1057. dundi_ie_append_cause(&ied, DUNDI_IE_CAUSE, DUNDI_CAUSE_GENERAL, "Out of memory");
  1058. dundi_send(trans, DUNDI_COMMAND_DPRESPONSE, 0, 1, &ied);
  1059. return -1;
  1060. }
  1061. return 0;
  1062. }
  1063. static int cache_lookup_internal(time_t now, struct dundi_request *req, char *key, char *eid_str_full, int *lowexpiration)
  1064. {
  1065. char data[1024];
  1066. char *ptr, *term, *src;
  1067. int tech;
  1068. struct ast_flags flags;
  1069. int weight;
  1070. int length;
  1071. int z;
  1072. char fs[256];
  1073. /* Build request string */
  1074. if (!ast_db_get("dundi/cache", key, data, sizeof(data))) {
  1075. time_t timeout;
  1076. ptr = data;
  1077. if (!ast_get_time_t(ptr, &timeout, 0, &length)) {
  1078. int expiration = timeout - now;
  1079. if (expiration > 0) {
  1080. ast_debug(1, "Found cache expiring in %d seconds!\n", expiration);
  1081. ptr += length + 1;
  1082. while((sscanf(ptr, "%30d/%30d/%30d/%n", (int *)&(flags.flags), &weight, &tech, &length) == 3)) {
  1083. ptr += length;
  1084. term = strchr(ptr, '|');
  1085. if (term) {
  1086. *term = '\0';
  1087. src = strrchr(ptr, '/');
  1088. if (src) {
  1089. *src = '\0';
  1090. src++;
  1091. } else
  1092. src = "";
  1093. ast_debug(1, "Found cached answer '%s/%s' originally from '%s' with flags '%s' on behalf of '%s'\n",
  1094. tech2str(tech), ptr, src, dundi_flags2str(fs, sizeof(fs), flags.flags), eid_str_full);
  1095. /* Make sure it's not already there */
  1096. for (z=0;z<req->respcount;z++) {
  1097. if ((req->dr[z].techint == tech) &&
  1098. !strcmp(req->dr[z].dest, ptr))
  1099. break;
  1100. }
  1101. if (z == req->respcount) {
  1102. /* Copy into parent responses */
  1103. ast_copy_flags(&(req->dr[req->respcount]), &flags, AST_FLAGS_ALL);
  1104. req->dr[req->respcount].weight = weight;
  1105. req->dr[req->respcount].techint = tech;
  1106. req->dr[req->respcount].expiration = expiration;
  1107. dundi_str_short_to_eid(&req->dr[req->respcount].eid, src);
  1108. ast_eid_to_str(req->dr[req->respcount].eid_str,
  1109. sizeof(req->dr[req->respcount].eid_str), &req->dr[req->respcount].eid);
  1110. ast_copy_string(req->dr[req->respcount].dest, ptr,
  1111. sizeof(req->dr[req->respcount].dest));
  1112. ast_copy_string(req->dr[req->respcount].tech, tech2str(tech),
  1113. sizeof(req->dr[req->respcount].tech));
  1114. req->respcount++;
  1115. ast_clear_flag_nonstd(req->hmd, DUNDI_HINT_DONT_ASK);
  1116. } else if (req->dr[z].weight > weight)
  1117. req->dr[z].weight = weight;
  1118. ptr = term + 1;
  1119. }
  1120. }
  1121. /* We found *something* cached */
  1122. if (expiration < *lowexpiration)
  1123. *lowexpiration = expiration;
  1124. return 1;
  1125. } else
  1126. ast_db_del("dundi/cache", key);
  1127. } else
  1128. ast_db_del("dundi/cache", key);
  1129. }
  1130. return 0;
  1131. }
  1132. static int cache_lookup(struct dundi_request *req, dundi_eid *peer_eid, uint32_t crc, int *lowexpiration)
  1133. {
  1134. char eid_str[20];
  1135. char eidroot_str[20];
  1136. time_t now;
  1137. int res=0;
  1138. int res2=0;
  1139. char eid_str_full[20];
  1140. char tmp[256]="";
  1141. /* Enough space for largest value that can be stored in key. */
  1142. char key[sizeof(eid_str) + sizeof(tmp) + sizeof(req->dcontext) + sizeof(eidroot_str) + sizeof("hint////r")];
  1143. int x;
  1144. time(&now);
  1145. dundi_eid_to_str_short(eid_str, sizeof(eid_str), peer_eid);
  1146. dundi_eid_to_str_short(eidroot_str, sizeof(eidroot_str), &req->root_eid);
  1147. ast_eid_to_str(eid_str_full, sizeof(eid_str_full), peer_eid);
  1148. snprintf(key, sizeof(key), "%s/%s/%s/e%08x", eid_str, req->number, req->dcontext, crc);
  1149. res |= cache_lookup_internal(now, req, key, eid_str_full, lowexpiration);
  1150. snprintf(key, sizeof(key), "%s/%s/%s/e%08x", eid_str, req->number, req->dcontext, (unsigned)0);
  1151. res |= cache_lookup_internal(now, req, key, eid_str_full, lowexpiration);
  1152. snprintf(key, sizeof(key), "%s/%s/%s/r%s", eid_str, req->number, req->dcontext, eidroot_str);
  1153. res |= cache_lookup_internal(now, req, key, eid_str_full, lowexpiration);
  1154. x = 0;
  1155. if (!req->respcount) {
  1156. while(!res2) {
  1157. /* Look and see if we have a hint that would preclude us from looking at this
  1158. peer for this number. */
  1159. if (!(tmp[x] = req->number[x]))
  1160. break;
  1161. x++;
  1162. /* Check for hints */
  1163. snprintf(key, sizeof(key), "hint/%s/%s/%s/e%08x", eid_str, tmp, req->dcontext, crc);
  1164. res2 |= cache_lookup_internal(now, req, key, eid_str_full, lowexpiration);
  1165. snprintf(key, sizeof(key), "hint/%s/%s/%s/e%08x", eid_str, tmp, req->dcontext, (unsigned)0);
  1166. res2 |= cache_lookup_internal(now, req, key, eid_str_full, lowexpiration);
  1167. snprintf(key, sizeof(key), "hint/%s/%s/%s/r%s", eid_str, tmp, req->dcontext, eidroot_str);
  1168. res2 |= cache_lookup_internal(now, req, key, eid_str_full, lowexpiration);
  1169. if (res2) {
  1170. if (strlen(tmp) > strlen(req->hmd->exten)) {
  1171. /* Update meta data if appropriate */
  1172. ast_copy_string(req->hmd->exten, tmp, sizeof(req->hmd->exten));
  1173. }
  1174. }
  1175. }
  1176. res |= res2;
  1177. }
  1178. return res;
  1179. }
  1180. static void qualify_peer(struct dundi_peer *peer, int schedonly);
  1181. static void apply_peer(struct dundi_transaction *trans, struct dundi_peer *p)
  1182. {
  1183. if (!trans->addr.sin_addr.s_addr)
  1184. memcpy(&trans->addr, &p->addr, sizeof(trans->addr));
  1185. trans->us_eid = p->us_eid;
  1186. trans->them_eid = p->eid;
  1187. /* Enable encryption if appropriate */
  1188. if (!ast_strlen_zero(p->inkey))
  1189. ast_set_flag(trans, FLAG_ENCRYPT);
  1190. if (p->maxms) {
  1191. trans->autokilltimeout = p->maxms;
  1192. trans->retranstimer = DUNDI_DEFAULT_RETRANS_TIMER;
  1193. if (p->lastms > 1) {
  1194. trans->retranstimer = p->lastms * 2;
  1195. /* Keep it from being silly */
  1196. if (trans->retranstimer < 150)
  1197. trans->retranstimer = 150;
  1198. }
  1199. if (trans->retranstimer > DUNDI_DEFAULT_RETRANS_TIMER)
  1200. trans->retranstimer = DUNDI_DEFAULT_RETRANS_TIMER;
  1201. } else
  1202. trans->autokilltimeout = global_autokilltimeout;
  1203. }
  1204. /*! \note Called with the peers list already locked */
  1205. static int do_register_expire(const void *data)
  1206. {
  1207. struct dundi_peer *peer = (struct dundi_peer *)data;
  1208. char eid_str[20];
  1209. ast_debug(1, "Register expired for '%s'\n", ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid));
  1210. ast_db_del("dundi/dpeers", dundi_eid_to_str_short(eid_str, sizeof(eid_str), &peer->eid));
  1211. peer->registerexpire = -1;
  1212. peer->lastms = 0;
  1213. memset(&peer->addr, 0, sizeof(peer->addr));
  1214. return 0;
  1215. }
  1216. static int update_key(struct dundi_peer *peer)
  1217. {
  1218. unsigned char key[16];
  1219. struct ast_key *ekey, *skey;
  1220. char eid_str[20];
  1221. int res;
  1222. if (!peer->keyexpire || (peer->keyexpire < time(NULL))) {
  1223. build_iv(key);
  1224. ast_aes_set_encrypt_key(key, &peer->us_ecx);
  1225. ast_aes_set_decrypt_key(key, &peer->us_dcx);
  1226. ekey = ast_key_get(peer->inkey, AST_KEY_PUBLIC);
  1227. if (!ekey) {
  1228. ast_log(LOG_NOTICE, "No such key '%s' for creating RSA encrypted shared key for '%s'!\n",
  1229. peer->inkey, ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid));
  1230. return -1;
  1231. }
  1232. skey = ast_key_get(peer->outkey, AST_KEY_PRIVATE);
  1233. if (!skey) {
  1234. ast_log(LOG_NOTICE, "No such key '%s' for signing RSA encrypted shared key for '%s'!\n",
  1235. peer->outkey, ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid));
  1236. return -1;
  1237. }
  1238. if ((res = ast_encrypt_bin(peer->txenckey, key, sizeof(key), ekey)) != 128) {
  1239. ast_log(LOG_NOTICE, "Whoa, got a weird encrypt size (%d != %d)!\n", res, 128);
  1240. return -1;
  1241. }
  1242. if ((res = ast_sign_bin(skey, (char *)peer->txenckey, 128, peer->txenckey + 128))) {
  1243. ast_log(LOG_NOTICE, "Failed to sign key (%d)!\n", res);
  1244. return -1;
  1245. }
  1246. peer->us_keycrc32 = crc32(0L, peer->txenckey, 128);
  1247. peer->sentfullkey = 0;
  1248. /* Looks good */
  1249. time(&peer->keyexpire);
  1250. peer->keyexpire += dundi_key_ttl;
  1251. }
  1252. return 0;
  1253. }
  1254. static int encrypt_memcpy(unsigned char *dst, unsigned char *src, int len, unsigned char *iv, ast_aes_encrypt_key *ecx)
  1255. {
  1256. unsigned char curblock[16];
  1257. int x;
  1258. memcpy(curblock, iv, sizeof(curblock));
  1259. while(len > 0) {
  1260. for (x=0;x<16;x++)
  1261. curblock[x] ^= src[x];
  1262. ast_aes_encrypt(curblock, dst, ecx);
  1263. memcpy(curblock, dst, sizeof(curblock));
  1264. dst += 16;
  1265. src += 16;
  1266. len -= 16;
  1267. }
  1268. return 0;
  1269. }
  1270. static int decrypt_memcpy(unsigned char *dst, unsigned char *src, int len, unsigned char *iv, ast_aes_decrypt_key *dcx)
  1271. {
  1272. unsigned char lastblock[16];
  1273. int x;
  1274. memcpy(lastblock, iv, sizeof(lastblock));
  1275. while(len > 0) {
  1276. ast_aes_decrypt(src, dst, dcx);
  1277. for (x=0;x<16;x++)
  1278. dst[x] ^= lastblock[x];
  1279. memcpy(lastblock, src, sizeof(lastblock));
  1280. dst += 16;
  1281. src += 16;
  1282. len -= 16;
  1283. }
  1284. return 0;
  1285. }
  1286. static struct dundi_hdr *dundi_decrypt(struct dundi_transaction *trans, unsigned char *dst, int *dstlen, struct dundi_hdr *ohdr, struct dundi_encblock *src, int srclen)
  1287. {
  1288. int space = *dstlen;
  1289. unsigned long bytes;
  1290. struct dundi_hdr *h;
  1291. unsigned char *decrypt_space;
  1292. decrypt_space = ast_alloca(srclen);
  1293. decrypt_memcpy(decrypt_space, src->encdata, srclen, src->iv, &trans->dcx);
  1294. /* Setup header */
  1295. h = (struct dundi_hdr *)dst;
  1296. *h = *ohdr;
  1297. bytes = space - 6;
  1298. if (uncompress(dst + 6, &bytes, decrypt_space, srclen) != Z_OK) {
  1299. ast_debug(1, "Ouch, uncompress failed :(\n");
  1300. return NULL;
  1301. }
  1302. /* Update length */
  1303. *dstlen = bytes + 6;
  1304. /* Return new header */
  1305. return h;
  1306. }
  1307. static int dundi_encrypt(struct dundi_transaction *trans, struct dundi_packet *pack)
  1308. {
  1309. unsigned char *compress_space;
  1310. int len;
  1311. int res;
  1312. unsigned long bytes;
  1313. struct dundi_ie_data ied;
  1314. struct dundi_peer *peer;
  1315. unsigned char iv[16];
  1316. len = pack->datalen + pack->datalen / 100 + 42;
  1317. compress_space = ast_alloca(len);
  1318. memset(compress_space, 0, len);
  1319. /* We care about everthing save the first 6 bytes of header */
  1320. bytes = len;
  1321. res = compress(compress_space, &bytes, pack->data + 6, pack->datalen - 6);
  1322. if (res != Z_OK) {
  1323. ast_debug(1, "Ouch, compression failed!\n");
  1324. return -1;
  1325. }
  1326. memset(&ied, 0, sizeof(ied));
  1327. /* Say who we are */
  1328. if (!pack->h->iseqno && !pack->h->oseqno) {
  1329. /* Need the key in the first copy */
  1330. if (!(peer = find_peer(&trans->them_eid)))
  1331. return -1;
  1332. if (update_key(peer))
  1333. return -1;
  1334. if (!peer->sentfullkey)
  1335. ast_set_flag(trans, FLAG_SENDFULLKEY);
  1336. /* Append key data */
  1337. dundi_ie_append_eid(&ied, DUNDI_IE_EID, &trans->us_eid);
  1338. if (ast_test_flag(trans, FLAG_SENDFULLKEY)) {
  1339. dundi_ie_append_raw(&ied, DUNDI_IE_SHAREDKEY, peer->txenckey, 128);
  1340. dundi_ie_append_raw(&ied, DUNDI_IE_SIGNATURE, peer->txenckey + 128, 128);
  1341. } else {
  1342. dundi_ie_append_int(&ied, DUNDI_IE_KEYCRC32, peer->us_keycrc32);
  1343. }
  1344. /* Setup contexts */
  1345. trans->ecx = peer->us_ecx;
  1346. trans->dcx = peer->us_dcx;
  1347. /* We've sent the full key */
  1348. peer->sentfullkey = 1;
  1349. }
  1350. /* Build initialization vector */
  1351. build_iv(iv);
  1352. /* Add the field, rounded up to 16 bytes */
  1353. dundi_ie_append_encdata(&ied, DUNDI_IE_ENCDATA, iv, NULL, ((bytes + 15) / 16) * 16);
  1354. /* Copy the data */
  1355. if ((ied.pos + bytes) >= sizeof(ied.buf)) {
  1356. ast_log(LOG_NOTICE, "Final packet too large!\n");
  1357. return -1;
  1358. }
  1359. encrypt_memcpy(ied.buf + ied.pos, compress_space, bytes, iv, &trans->ecx);
  1360. ied.pos += ((bytes + 15) / 16) * 16;
  1361. /* Reconstruct header */
  1362. pack->datalen = sizeof(struct dundi_hdr);
  1363. pack->h->cmdresp = DUNDI_COMMAND_ENCRYPT;
  1364. pack->h->cmdflags = 0;
  1365. memcpy(pack->h->ies, ied.buf, ied.pos);
  1366. pack->datalen += ied.pos;
  1367. return 0;
  1368. }
  1369. static int check_key(struct dundi_peer *peer, unsigned char *newkey, unsigned char *newsig, uint32_t keycrc32)
  1370. {
  1371. unsigned char dst[128];
  1372. int res;
  1373. struct ast_key *key, *skey;
  1374. char eid_str[20];
  1375. ast_debug(1, "Expected '%08x' got '%08x'\n", peer->them_keycrc32, keycrc32);
  1376. if (peer->them_keycrc32 && (peer->them_keycrc32 == keycrc32)) {
  1377. /* A match */
  1378. return 1;
  1379. } else if (!newkey || !newsig)
  1380. return 0;
  1381. if (!memcmp(peer->rxenckey, newkey, 128) &&
  1382. !memcmp(peer->rxenckey + 128, newsig, 128)) {
  1383. /* By definition, a match */
  1384. return 1;
  1385. }
  1386. /* Decrypt key */
  1387. key = ast_key_get(peer->outkey, AST_KEY_PRIVATE);
  1388. if (!key) {
  1389. ast_log(LOG_NOTICE, "Unable to find key '%s' to decode shared key from '%s'\n",
  1390. peer->outkey, ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid));
  1391. return -1;
  1392. }
  1393. skey = ast_key_get(peer->inkey, AST_KEY_PUBLIC);
  1394. if (!skey) {
  1395. ast_log(LOG_NOTICE, "Unable to find key '%s' to verify shared key from '%s'\n",
  1396. peer->inkey, ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid));
  1397. return -1;
  1398. }
  1399. /* First check signature */
  1400. res = ast_check_signature_bin(skey, (char *)newkey, 128, newsig);
  1401. if (res)
  1402. return 0;
  1403. res = ast_decrypt_bin(dst, newkey, sizeof(dst), key);
  1404. if (res != 16) {
  1405. if (res >= 0)
  1406. ast_log(LOG_NOTICE, "Weird, key decoded to the wrong size (%d)\n", res);
  1407. return 0;
  1408. }
  1409. /* Decrypted, passes signature */
  1410. ast_debug(1, "Wow, new key combo passed signature and decrypt!\n");
  1411. memcpy(peer->rxenckey, newkey, 128);
  1412. memcpy(peer->rxenckey + 128, newsig, 128);
  1413. peer->them_keycrc32 = crc32(0L, peer->rxenckey, 128);
  1414. ast_aes_set_decrypt_key(dst, &peer->them_dcx);
  1415. ast_aes_set_encrypt_key(dst, &peer->them_ecx);
  1416. return 1;
  1417. }
  1418. static void deep_copy_peer(struct dundi_peer *peer_dst, const struct dundi_peer *peer_src)
  1419. {
  1420. struct permission *cur, *perm;
  1421. *peer_dst = *peer_src;
  1422. AST_LIST_NEXT(peer_dst, list) = NULL;
  1423. /* Scheduled items cannot go with the copy */
  1424. peer_dst->registerid = -1;
  1425. peer_dst->qualifyid = -1;
  1426. peer_dst->registerexpire = -1;
  1427. /* Transactions and lookup history cannot go with the copy either */
  1428. peer_dst->regtrans = NULL;
  1429. peer_dst->qualtrans = NULL;
  1430. memset(&peer_dst->lookups, 0, sizeof(peer_dst->lookups));
  1431. memset(&peer_dst->permit, 0, sizeof(peer_dst->permit));
  1432. memset(&peer_dst->include, 0, sizeof(peer_dst->permit));
  1433. AST_LIST_TRAVERSE(&peer_src->permit, cur, list) {
  1434. if (!(perm = ast_calloc(1, sizeof(*perm) + strlen(cur->name) + 1)))
  1435. continue;
  1436. perm->allow = cur->allow;
  1437. strcpy(perm->name, cur->name);
  1438. AST_LIST_INSERT_HEAD(&peer_dst->permit, perm, list);
  1439. }
  1440. AST_LIST_TRAVERSE(&peer_src->include, cur, list) {
  1441. if (!(perm = ast_calloc(1, sizeof(*perm) + strlen(cur->name) + 1)))
  1442. continue;
  1443. perm->allow = cur->allow;
  1444. strcpy(perm->name, cur->name);
  1445. AST_LIST_INSERT_HEAD(&peer_dst->include, perm, list);
  1446. }
  1447. }
  1448. static int handle_command_response(struct dundi_transaction *trans, struct dundi_hdr *hdr, int datalen, int encrypted)
  1449. {
  1450. /* Handle canonical command / response */
  1451. int final = hdr->cmdresp & 0x80;
  1452. int cmd = hdr->cmdresp & 0x7f;
  1453. int x,y,z;
  1454. int resp;
  1455. int res;
  1456. int authpass=0;
  1457. unsigned char *bufcpy;
  1458. #ifdef LOW_MEMORY
  1459. struct dundi_ie_data *ied = ast_calloc(1, sizeof(*ied));
  1460. #else
  1461. struct dundi_ie_data _ied = {
  1462. .pos = 0,
  1463. };
  1464. struct dundi_ie_data *ied = &_ied;
  1465. #endif
  1466. struct dundi_ies ies = {
  1467. .eidcount = 0,
  1468. };
  1469. struct dundi_peer *peer = NULL;
  1470. char eid_str[20];
  1471. char eid_str2[20];
  1472. int retval = -1;
  1473. if (!ied) {
  1474. return -1;
  1475. }
  1476. if (datalen) {
  1477. bufcpy = ast_alloca(datalen);
  1478. /* Make a copy for parsing */
  1479. memcpy(bufcpy, hdr->ies, datalen);
  1480. ast_debug(1, "Got canonical message %d (%d), %d bytes data%s\n", cmd, hdr->oseqno, datalen, final ? " (Final)" : "");
  1481. if (dundi_parse_ies(&ies, bufcpy, datalen) < 0) {
  1482. ast_log(LOG_WARNING, "Failed to parse DUNDI information elements!\n");
  1483. goto return_cleanup;
  1484. }
  1485. }
  1486. switch(cmd) {
  1487. case DUNDI_COMMAND_DPDISCOVER:
  1488. case DUNDI_COMMAND_EIDQUERY:
  1489. case DUNDI_COMMAND_PRECACHERQ:
  1490. if (cmd == DUNDI_COMMAND_EIDQUERY)
  1491. resp = DUNDI_COMMAND_EIDRESPONSE;
  1492. else if (cmd == DUNDI_COMMAND_PRECACHERQ)
  1493. resp = DUNDI_COMMAND_PRECACHERP;
  1494. else
  1495. resp = DUNDI_COMMAND_DPRESPONSE;
  1496. /* A dialplan or entity discover -- qualify by highest level entity */
  1497. peer = find_peer(ies.eids[0]);
  1498. if (!peer) {
  1499. dundi_ie_append_cause(ied, DUNDI_IE_CAUSE, DUNDI_CAUSE_NOAUTH, NULL);
  1500. dundi_send(trans, resp, 0, 1, ied);
  1501. } else {
  1502. int hasauth = 0;
  1503. trans->us_eid = peer->us_eid;
  1504. if (strlen(peer->inkey)) {
  1505. hasauth = encrypted;
  1506. } else
  1507. hasauth = 1;
  1508. if (hasauth) {
  1509. /* Okay we're authentiated and all, now we check if they're authorized */
  1510. if (!ies.called_context)
  1511. ies.called_context = "e164";
  1512. if (cmd == DUNDI_COMMAND_EIDQUERY) {
  1513. res = dundi_answer_entity(trans, &ies, ies.called_context);
  1514. } else {
  1515. if (ast_strlen_zero(ies.called_number)) {
  1516. /* They're not permitted to access that context */
  1517. dundi_ie_append_cause(ied, DUNDI_IE_CAUSE, DUNDI_CAUSE_GENERAL, "Invalid or missing number/entity");
  1518. dundi_send(trans, resp, 0, 1, ied);
  1519. } else if ((cmd == DUNDI_COMMAND_DPDISCOVER) &&
  1520. (peer->model & DUNDI_MODEL_INBOUND) &&
  1521. has_permission(&peer->permit, ies.called_context)) {
  1522. res = dundi_answer_query(trans, &ies, ies.called_context);
  1523. if (res < 0) {
  1524. /* There is no such dundi context */
  1525. dundi_ie_append_cause(ied, DUNDI_IE_CAUSE, DUNDI_CAUSE_NOAUTH, "Unsupported DUNDI Context");
  1526. dundi_send(trans, resp, 0, 1, ied);
  1527. }
  1528. } else if ((cmd = DUNDI_COMMAND_PRECACHERQ) &&
  1529. (peer->pcmodel & DUNDI_MODEL_INBOUND) &&
  1530. has_permission(&peer->include, ies.called_context)) {
  1531. res = dundi_prop_precache(trans, &ies, ies.called_context);
  1532. if (res < 0) {
  1533. /* There is no such dundi context */
  1534. dundi_ie_append_cause(ied, DUNDI_IE_CAUSE, DUNDI_CAUSE_NOAUTH, "Unsupported DUNDI Context");
  1535. dundi_send(trans, resp, 0, 1, ied);
  1536. }
  1537. } else {
  1538. /* They're not permitted to access that context */
  1539. dundi_ie_append_cause(ied, DUNDI_IE_CAUSE, DUNDI_CAUSE_NOAUTH, "Permission to context denied");
  1540. dundi_send(trans, resp, 0, 1, ied);
  1541. }
  1542. }
  1543. } else {
  1544. /* They're not permitted to access that context */
  1545. dundi_ie_append_cause(ied, DUNDI_IE_CAUSE, DUNDI_CAUSE_NOAUTH, "Unencrypted responses not permitted");
  1546. dundi_send(trans, resp, 0, 1, ied);
  1547. }
  1548. }
  1549. break;
  1550. case DUNDI_COMMAND_REGREQ:
  1551. /* A register request -- should only have one entity */
  1552. peer = find_peer(ies.eids[0]);
  1553. /* if the peer is not found and we have a valid 'any_peer' setting */
  1554. if (any_peer && peer == any_peer) {
  1555. /* copy any_peer into a new peer object */
  1556. peer = ast_calloc(1, sizeof(*peer));
  1557. if (peer) {
  1558. deep_copy_peer(peer, any_peer);
  1559. /* set EID to remote EID */
  1560. peer->eid = *ies.eids[0];
  1561. AST_LIST_LOCK(&peers);
  1562. AST_LIST_INSERT_HEAD(&peers, peer, list);
  1563. AST_LIST_UNLOCK(&peers);
  1564. }
  1565. }
  1566. if (!peer || !peer->dynamic) {
  1567. dundi_ie_append_cause(ied, DUNDI_IE_CAUSE, DUNDI_CAUSE_NOAUTH, NULL);
  1568. dundi_send(trans, DUNDI_COMMAND_REGRESPONSE, 0, 1, ied);
  1569. } else {
  1570. int hasauth = 0;
  1571. trans->us_eid = peer->us_eid;
  1572. if (!ast_strlen_zero(peer->inkey)) {
  1573. hasauth = encrypted;
  1574. } else
  1575. hasauth = 1;
  1576. if (hasauth) {
  1577. int expire = default_expiration;
  1578. char data[256];
  1579. int needqual = 0;
  1580. AST_SCHED_DEL(sched, peer->registerexpire);
  1581. peer->registerexpire = ast_sched_add(sched, (expire + 10) * 1000, do_register_expire, peer);
  1582. snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(trans->addr.sin_addr),
  1583. ntohs(trans->addr.sin_port), expire);
  1584. ast_db_put("dundi/dpeers", dundi_eid_to_str_short(eid_str, sizeof(eid_str), &peer->eid), data);
  1585. if (inaddrcmp(&peer->addr, &trans->addr)) {
  1586. ast_verb(3, "Registered DUNDi peer '%s' at '%s:%d'\n",
  1587. ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid),
  1588. ast_inet_ntoa(trans->addr.sin_addr), ntohs(trans->addr.sin_port));
  1589. needqual = 1;
  1590. }
  1591. memcpy(&peer->addr, &trans->addr, sizeof(peer->addr));
  1592. dundi_ie_append_short(ied, DUNDI_IE_EXPIRATION, default_expiration);
  1593. dundi_send(trans, DUNDI_COMMAND_REGRESPONSE, 0, 1, ied);
  1594. if (needqual)
  1595. qualify_peer(peer, 1);
  1596. }
  1597. }
  1598. break;
  1599. case DUNDI_COMMAND_DPRESPONSE:
  1600. /* A dialplan response, lets see what we got... */
  1601. if (ies.cause < 1) {
  1602. /* Success of some sort */
  1603. ast_debug(1, "Looks like success of some sort (%d), %d answers\n", ies.cause, ies.anscount);
  1604. if (ast_test_flag(trans, FLAG_ENCRYPT)) {
  1605. authpass = encrypted;
  1606. } else
  1607. authpass = 1;
  1608. if (authpass) {
  1609. /* Pass back up answers */
  1610. if (trans->parent && trans->parent->dr) {
  1611. y = trans->parent->respcount;
  1612. for (x=0;x<ies.anscount;x++) {
  1613. if (trans->parent->respcount < trans->parent->maxcount) {
  1614. /* Make sure it's not already there */
  1615. for (z=0;z<trans->parent->respcount;z++) {
  1616. if ((trans->parent->dr[z].techint == ies.answers[x]->protocol) &&
  1617. !strcmp(trans->parent->dr[z].dest, (char *)ies.answers[x]->data))
  1618. break;
  1619. }
  1620. if (z == trans->parent->respcount) {
  1621. /* Copy into parent responses */
  1622. trans->parent->dr[trans->parent->respcount].flags = ntohs(ies.answers[x]->flags);
  1623. trans->parent->dr[trans->parent->respcount].techint = ies.answers[x]->protocol;
  1624. trans->parent->dr[trans->parent->respcount].weight = ntohs(ies.answers[x]->weight);
  1625. trans->parent->dr[trans->parent->respcount].eid = ies.answers[x]->eid;
  1626. if (ies.expiration > 0)
  1627. trans->parent->dr[trans->parent->respcount].expiration = ies.expiration;
  1628. else
  1629. trans->parent->dr[trans->parent->respcount].expiration = dundi_cache_time;
  1630. ast_eid_to_str(trans->parent->dr[trans->parent->respcount].eid_str,
  1631. sizeof(trans->parent->dr[trans->parent->respcount].eid_str),
  1632. &ies.answers[x]->eid);
  1633. ast_copy_string(trans->parent->dr[trans->parent->respcount].dest, (char *)ies.answers[x]->data,
  1634. sizeof(trans->parent->dr[trans->parent->respcount].dest));
  1635. ast_copy_string(trans->parent->dr[trans->parent->respcount].tech, tech2str(ies.answers[x]->protocol),
  1636. sizeof(trans->parent->dr[trans->parent->respcount].tech));
  1637. trans->parent->respcount++;
  1638. ast_clear_flag_nonstd(trans->parent->hmd, DUNDI_HINT_DONT_ASK);
  1639. } else if (trans->parent->dr[z].weight > ntohs(ies.answers[x]->weight)) {
  1640. /* Update weight if appropriate */
  1641. trans->parent->dr[z].weight = ntohs(ies.answers[x]->weight);
  1642. }
  1643. } else
  1644. ast_log(LOG_NOTICE, "Dropping excessive answers to request for %s@%s\n",
  1645. trans->parent->number, trans->parent->dcontext);
  1646. }
  1647. /* Save all the results (if any) we had. Even if no results, still cache lookup. Let
  1648. the cache know if this request was unaffected by our entity list. */
  1649. cache_save(&trans->them_eid, trans->parent, y,
  1650. ies.hint ? ast_test_flag_nonstd(ies.hint, htons(DUNDI_HINT_UNAFFECTED)) : 0, ies.expiration, 0);
  1651. if (ies.hint) {
  1652. cache_save_hint(&trans->them_eid, trans->parent, ies.hint, ies.expiration);
  1653. if (ast_test_flag_nonstd(ies.hint, htons(DUNDI_HINT_TTL_EXPIRED)))
  1654. ast_set_flag_nonstd(trans->parent->hmd, DUNDI_HINT_TTL_EXPIRED);
  1655. if (ast_test_flag_nonstd(ies.hint, htons(DUNDI_HINT_DONT_ASK))) {
  1656. if (strlen((char *)ies.hint->data) > strlen(trans->parent->hmd->exten)) {
  1657. ast_copy_string(trans->parent->hmd->exten, (char *)ies.hint->data,
  1658. sizeof(trans->parent->hmd->exten));
  1659. }
  1660. } else {
  1661. ast_clear_flag_nonstd(trans->parent->hmd, DUNDI_HINT_DONT_ASK);
  1662. }
  1663. }
  1664. if (ies.expiration > 0) {
  1665. if (trans->parent->expiration > ies.expiration) {
  1666. trans->parent->expiration = ies.expiration;
  1667. }
  1668. }
  1669. }
  1670. /* Close connection if not final */
  1671. if (!final)
  1672. dundi_send(trans, DUNDI_COMMAND_CANCEL, 0, 1, NULL);
  1673. }
  1674. } else {
  1675. /* Auth failure, check for data */
  1676. if (!final) {
  1677. /* Cancel if they didn't already */
  1678. dundi_send(trans, DUNDI_COMMAND_CANCEL, 0, 1, NULL);
  1679. }
  1680. }
  1681. break;
  1682. case DUNDI_COMMAND_EIDRESPONSE:
  1683. /* A dialplan response, lets see what we got... */
  1684. if (ies.cause < 1) {
  1685. /* Success of some sort */
  1686. ast_debug(1, "Looks like success of some sort (%d)\n", ies.cause);
  1687. if (ast_test_flag(trans, FLAG_ENCRYPT)) {
  1688. authpass = encrypted;
  1689. } else
  1690. authpass = 1;
  1691. if (authpass) {
  1692. /* Pass back up answers */
  1693. if (trans->parent && trans->parent->dei && ies.q_org) {
  1694. if (!trans->parent->respcount) {
  1695. trans->parent->respcount++;
  1696. if (ies.q_dept)
  1697. ast_copy_string(trans->parent->dei->orgunit, ies.q_dept, sizeof(trans->parent->dei->orgunit));
  1698. if (ies.q_org)
  1699. ast_copy_string(trans->parent->dei->org, ies.q_org, sizeof(trans->parent->dei->org));
  1700. if (ies.q_locality)
  1701. ast_copy_string(trans->parent->dei->locality, ies.q_locality, sizeof(trans->parent->dei->locality));
  1702. if (ies.q_stateprov)
  1703. ast_copy_string(trans->parent->dei->stateprov, ies.q_stateprov, sizeof(trans->parent->dei->stateprov));
  1704. if (ies.q_country)
  1705. ast_copy_string(trans->parent->dei->country, ies.q_country, sizeof(trans->parent->dei->country));
  1706. if (ies.q_email)
  1707. ast_copy_string(trans->parent->dei->email, ies.q_email, sizeof(trans->parent->dei->email));
  1708. if (ies.q_phone)
  1709. ast_copy_string(trans->parent->dei->phone, ies.q_phone, sizeof(trans->parent->dei->phone));
  1710. if (ies.q_ipaddr)
  1711. ast_copy_string(trans->parent->dei->ipaddr, ies.q_ipaddr, sizeof(trans->parent->dei->ipaddr));
  1712. if (!ast_eid_cmp(&trans->them_eid, &trans->parent->query_eid)) {
  1713. /* If it's them, update our address */
  1714. ast_copy_string(trans->parent->dei->ipaddr, ast_inet_ntoa(trans->addr.sin_addr), sizeof(trans->parent->dei->ipaddr));
  1715. }
  1716. }
  1717. if (ies.hint) {
  1718. if (ast_test_flag_nonstd(ies.hint, htons(DUNDI_HINT_TTL_EXPIRED)))
  1719. ast_set_flag_nonstd(trans->parent->hmd, DUNDI_HINT_TTL_EXPIRED);
  1720. }
  1721. }
  1722. /* Close connection if not final */
  1723. if (!final)
  1724. dundi_send(trans, DUNDI_COMMAND_CANCEL, 0, 1, NULL);
  1725. }
  1726. } else {
  1727. /* Auth failure, check for data */
  1728. if (!final) {
  1729. /* Cancel if they didn't already */
  1730. dundi_send(trans, DUNDI_COMMAND_CANCEL, 0, 1, NULL);
  1731. }
  1732. }
  1733. break;
  1734. case DUNDI_COMMAND_REGRESPONSE:
  1735. /* A dialplan response, lets see what we got... */
  1736. if (ies.cause < 1) {
  1737. int hasauth;
  1738. /* Success of some sort */
  1739. if (ast_test_flag(trans, FLAG_ENCRYPT)) {
  1740. hasauth = encrypted;
  1741. } else
  1742. hasauth = 1;
  1743. if (!hasauth) {
  1744. ast_log(LOG_NOTICE, "Reponse to register not authorized!\n");
  1745. if (!final) {
  1746. dundi_ie_append_cause(ied, DUNDI_IE_CAUSE, DUNDI_CAUSE_NOAUTH, "Improper signature in answer");
  1747. dundi_send(trans, DUNDI_COMMAND_CANCEL, 0, 1, ied);
  1748. }
  1749. } else {
  1750. ast_debug(1, "Yay, we've registered as '%s' to '%s'\n", ast_eid_to_str(eid_str, sizeof(eid_str), &trans->us_eid),
  1751. ast_eid_to_str(eid_str2, sizeof(eid_str2), &trans->them_eid));
  1752. /* Close connection if not final */
  1753. if (!final)
  1754. dundi_send(trans, DUNDI_COMMAND_CANCEL, 0, 1, NULL);
  1755. }
  1756. } else {
  1757. /* Auth failure, cancel if they didn't for some reason */
  1758. if (!final) {
  1759. dundi_send(trans, DUNDI_COMMAND_CANCEL, 0, 1, NULL);
  1760. }
  1761. }
  1762. break;
  1763. case DUNDI_COMMAND_INVALID:
  1764. case DUNDI_COMMAND_NULL:
  1765. case DUNDI_COMMAND_PRECACHERP:
  1766. /* Do nothing special */
  1767. if (!final)
  1768. dundi_send(trans, DUNDI_COMMAND_CANCEL, 0, 1, NULL);
  1769. break;
  1770. case DUNDI_COMMAND_ENCREJ:
  1771. if ((ast_test_flag(trans, FLAG_SENDFULLKEY)) || AST_LIST_EMPTY(&trans->lasttrans) || !(peer = find_peer(&trans->them_eid))) {
  1772. /* No really, it's over at this point */
  1773. if (!final)
  1774. dundi_send(trans, DUNDI_COMMAND_CANCEL, 0, 1, NULL);
  1775. } else {
  1776. /* Send with full key */
  1777. ast_set_flag(trans, FLAG_SENDFULLKEY);
  1778. if (final) {
  1779. /* Ooops, we got a final message, start by sending ACK... */
  1780. dundi_ack(trans, hdr->cmdresp & 0x80);
  1781. trans->aseqno = trans->iseqno;
  1782. /* Now, we gotta create a new transaction */
  1783. if (!reset_transaction(trans)) {
  1784. /* Make sure handle_frame doesn't destroy us */
  1785. hdr->cmdresp &= 0x7f;
  1786. /* Parse the message we transmitted */
  1787. memset(&ies, 0, sizeof(ies));
  1788. dundi_parse_ies(&ies, (AST_LIST_FIRST(&trans->lasttrans))->h->ies, (AST_LIST_FIRST(&trans->lasttrans))->datalen - sizeof(struct dundi_hdr));
  1789. /* Reconstruct outgoing encrypted packet */
  1790. memset(ied, 0, sizeof(*ied));
  1791. dundi_ie_append_eid(ied, DUNDI_IE_EID, &trans->us_eid);
  1792. dundi_ie_append_raw(ied, DUNDI_IE_SHAREDKEY, peer->txenckey, 128);
  1793. dundi_ie_append_raw(ied, DUNDI_IE_SIGNATURE, peer->txenckey + 128, 128);
  1794. if (ies.encblock)
  1795. dundi_ie_append_encdata(ied, DUNDI_IE_ENCDATA, ies.encblock->iv, ies.encblock->encdata, ies.enclen);
  1796. dundi_send(trans, DUNDI_COMMAND_ENCRYPT, 0, (AST_LIST_FIRST(&trans->lasttrans))->h->cmdresp & 0x80, ied);
  1797. peer->sentfullkey = 1;
  1798. }
  1799. }
  1800. }
  1801. break;
  1802. case DUNDI_COMMAND_ENCRYPT:
  1803. if (!encrypted) {
  1804. /* No nested encryption! */
  1805. if ((trans->iseqno == 1) && !trans->oseqno) {
  1806. if (!ies.eids[0] || !(peer = find_peer(ies.eids[0])) ||
  1807. ((!ies.encsharedkey || !ies.encsig) && !ies.keycrc32) ||
  1808. (check_key(peer, ies.encsharedkey, ies.encsig, ies.keycrc32) < 1)) {
  1809. if (!final) {
  1810. dundi_send(trans, DUNDI_COMMAND_ENCREJ, 0, 1, NULL);
  1811. }
  1812. break;
  1813. }
  1814. apply_peer(trans, peer);
  1815. /* Key passed, use new contexts for this session */
  1816. trans->ecx = peer->them_ecx;
  1817. trans->dcx = peer->them_dcx;
  1818. }
  1819. if (ast_test_flag(trans, FLAG_ENCRYPT) && ies.encblock && ies.enclen) {
  1820. struct dundi_hdr *dhdr;
  1821. unsigned char decoded[MAX_PACKET_SIZE];
  1822. int ddatalen;
  1823. ddatalen = sizeof(decoded);
  1824. dhdr = dundi_decrypt(trans, decoded, &ddatalen, hdr, ies.encblock, ies.enclen);
  1825. if (dhdr) {
  1826. /* Handle decrypted response */
  1827. if (dundidebug)
  1828. dundi_showframe(dhdr, 3, &trans->addr, ddatalen - sizeof(struct dundi_hdr));
  1829. handle_command_response(trans, dhdr, ddatalen - sizeof(struct dundi_hdr), 1);
  1830. /* Carry back final flag */
  1831. hdr->cmdresp |= dhdr->cmdresp & 0x80;
  1832. break;
  1833. } else {
  1834. ast_debug(1, "Ouch, decrypt failed :(\n");
  1835. }
  1836. }
  1837. }
  1838. if (!final) {
  1839. /* Turn off encryption */
  1840. ast_clear_flag(trans, FLAG_ENCRYPT);
  1841. dundi_send(trans, DUNDI_COMMAND_ENCREJ, 0, 1, NULL);
  1842. }
  1843. break;
  1844. default:
  1845. /* Send unknown command if we don't know it, with final flag IFF it's the
  1846. first command in the dialog and only if we haven't received final notification */
  1847. if (!final) {
  1848. dundi_ie_append_byte(ied, DUNDI_IE_UNKNOWN, cmd);
  1849. dundi_send(trans, DUNDI_COMMAND_UNKNOWN, 0, !hdr->oseqno, ied);
  1850. }
  1851. }
  1852. retval = 0;
  1853. return_cleanup:
  1854. #ifdef LOW_MEMORY
  1855. ast_free(ied);
  1856. #endif
  1857. return retval;
  1858. }
  1859. static void destroy_packet(struct dundi_packet *pack, int needfree);
  1860. static void destroy_packets(struct packetlist *p)
  1861. {
  1862. struct dundi_packet *pack;
  1863. while ((pack = AST_LIST_REMOVE_HEAD(p, list))) {
  1864. AST_SCHED_DEL(sched, pack->retransid);
  1865. ast_free(pack);
  1866. }
  1867. }
  1868. static int ack_trans(struct dundi_transaction *trans, int iseqno)
  1869. {
  1870. struct dundi_packet *pack;
  1871. /* Ack transmitted packet corresponding to iseqno */
  1872. AST_LIST_TRAVERSE(&trans->packets, pack, list) {
  1873. if ((pack->h->oseqno + 1) % 255 == iseqno) {
  1874. destroy_packet(pack, 0);
  1875. if (!AST_LIST_EMPTY(&trans->lasttrans)) {
  1876. ast_log(LOG_WARNING, "Whoa, there was still a last trans?\n");
  1877. destroy_packets(&trans->lasttrans);
  1878. }
  1879. AST_LIST_INSERT_HEAD(&trans->lasttrans, pack, list);
  1880. AST_SCHED_DEL(sched, trans->autokillid);
  1881. return 1;
  1882. }
  1883. }
  1884. return 0;
  1885. }
  1886. static int handle_frame(struct dundi_hdr *h, struct sockaddr_in *sin, int datalen)
  1887. {
  1888. struct dundi_transaction *trans;
  1889. trans = find_transaction(h, sin);
  1890. if (!trans) {
  1891. dundi_reject(h, sin);
  1892. return 0;
  1893. }
  1894. /* Got a transaction, see where this header fits in */
  1895. if (h->oseqno == trans->iseqno) {
  1896. /* Just what we were looking for... Anything but ack increments iseqno */
  1897. if (ack_trans(trans, h->iseqno) && ast_test_flag(trans, FLAG_FINAL)) {
  1898. /* If final, we're done */
  1899. destroy_trans(trans, 0);
  1900. return 0;
  1901. }
  1902. if (h->cmdresp != DUNDI_COMMAND_ACK) {
  1903. trans->oiseqno = trans->iseqno;
  1904. trans->iseqno++;
  1905. handle_command_response(trans, h, datalen, 0);
  1906. }
  1907. if (trans->aseqno != trans->iseqno) {
  1908. dundi_ack(trans, h->cmdresp & 0x80);
  1909. trans->aseqno = trans->iseqno;
  1910. }
  1911. /* Delete any saved last transmissions */
  1912. destroy_packets(&trans->lasttrans);
  1913. if (h->cmdresp & 0x80) {
  1914. /* Final -- destroy now */
  1915. destroy_trans(trans, 0);
  1916. }
  1917. } else if (h->oseqno == trans->oiseqno) {
  1918. /* Last incoming sequence number -- send ACK without processing */
  1919. dundi_ack(trans, 0);
  1920. } else {
  1921. /* Out of window -- simply drop */
  1922. ast_debug(1, "Dropping packet out of window!\n");
  1923. }
  1924. return 0;
  1925. }
  1926. static int socket_read(int *id, int fd, short events, void *cbdata)
  1927. {
  1928. struct sockaddr_in sin;
  1929. int res;
  1930. struct dundi_hdr *h;
  1931. char buf[MAX_PACKET_SIZE];
  1932. socklen_t len = sizeof(sin);
  1933. res = recvfrom(netsocket, buf, sizeof(buf) - 1, 0,(struct sockaddr *) &sin, &len);
  1934. if (res < 0) {
  1935. if (errno != ECONNREFUSED)
  1936. ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
  1937. return 1;
  1938. }
  1939. if (res < sizeof(struct dundi_hdr)) {
  1940. ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int)sizeof(struct dundi_hdr));
  1941. return 1;
  1942. }
  1943. buf[res] = '\0';
  1944. h = (struct dundi_hdr *) buf;
  1945. if (dundidebug)
  1946. dundi_showframe(h, 1, &sin, res - sizeof(struct dundi_hdr));
  1947. AST_LIST_LOCK(&peers);
  1948. handle_frame(h, &sin, res - sizeof(struct dundi_hdr));
  1949. AST_LIST_UNLOCK(&peers);
  1950. return 1;
  1951. }
  1952. static void build_secret(char *secret, int seclen)
  1953. {
  1954. unsigned char tmp[16];
  1955. char *s;
  1956. build_iv(tmp);
  1957. secret[0] = '\0';
  1958. ast_base64encode(secret, tmp, sizeof(tmp), seclen);
  1959. /* Eliminate potential bad characters */
  1960. while((s = strchr(secret, ';'))) *s = '+';
  1961. while((s = strchr(secret, '/'))) *s = '+';
  1962. while((s = strchr(secret, ':'))) *s = '+';
  1963. while((s = strchr(secret, '@'))) *s = '+';
  1964. }
  1965. static void save_secret(const char *newkey, const char *oldkey)
  1966. {
  1967. char tmp[256];
  1968. if (oldkey)
  1969. snprintf(tmp, sizeof(tmp), "%s;%s", oldkey, newkey);
  1970. else
  1971. snprintf(tmp, sizeof(tmp), "%s", newkey);
  1972. rotatetime = time(NULL) + DUNDI_SECRET_TIME;
  1973. ast_db_put(secretpath, "secret", tmp);
  1974. snprintf(tmp, sizeof(tmp), "%d", (int)rotatetime);
  1975. ast_db_put(secretpath, "secretexpiry", tmp);
  1976. }
  1977. static void load_password(void)
  1978. {
  1979. char *current=NULL;
  1980. char *last=NULL;
  1981. char tmp[256];
  1982. time_t expired;
  1983. ast_db_get(secretpath, "secretexpiry", tmp, sizeof(tmp));
  1984. if (!ast_get_time_t(tmp, &expired, 0, NULL)) {
  1985. ast_db_get(secretpath, "secret", tmp, sizeof(tmp));
  1986. current = strchr(tmp, ';');
  1987. if (!current)
  1988. current = tmp;
  1989. else {
  1990. *current = '\0';
  1991. current++;
  1992. };
  1993. if ((time(NULL) - expired) < 0) {
  1994. if ((expired - time(NULL)) > DUNDI_SECRET_TIME)
  1995. expired = time(NULL) + DUNDI_SECRET_TIME;
  1996. } else if ((time(NULL) - (expired + DUNDI_SECRET_TIME)) < 0) {
  1997. last = current;
  1998. current = NULL;
  1999. } else {
  2000. last = NULL;
  2001. current = NULL;
  2002. }
  2003. }
  2004. if (current) {
  2005. /* Current key is still valid, just setup rotatation properly */
  2006. ast_copy_string(cursecret, current, sizeof(cursecret));
  2007. rotatetime = expired;
  2008. } else {
  2009. /* Current key is out of date, rotate or eliminate all together */
  2010. build_secret(cursecret, sizeof(cursecret));
  2011. save_secret(cursecret, last);
  2012. }
  2013. }
  2014. static void check_password(void)
  2015. {
  2016. char oldsecret[80];
  2017. time_t now;
  2018. time(&now);
  2019. #if 0
  2020. printf("%ld/%ld\n", now, rotatetime);
  2021. #endif
  2022. if ((now - rotatetime) >= 0) {
  2023. /* Time to rotate keys */
  2024. ast_copy_string(oldsecret, cursecret, sizeof(oldsecret));
  2025. build_secret(cursecret, sizeof(cursecret));
  2026. save_secret(cursecret, oldsecret);
  2027. }
  2028. }
  2029. static void *network_thread(void *ignore)
  2030. {
  2031. /* Our job is simple: Send queued messages, retrying if necessary. Read frames
  2032. from the network, and queue them for delivery to the channels */
  2033. int res;
  2034. /* Establish I/O callback for socket read */
  2035. int *socket_read_id = ast_io_add(io, netsocket, socket_read, AST_IO_IN, NULL);
  2036. while (!dundi_shutdown) {
  2037. res = ast_sched_wait(sched);
  2038. if ((res > 1000) || (res < 0))
  2039. res = 1000;
  2040. res = ast_io_wait(io, res);
  2041. if (res >= 0) {
  2042. AST_LIST_LOCK(&peers);
  2043. ast_sched_runq(sched);
  2044. AST_LIST_UNLOCK(&peers);
  2045. }
  2046. check_password();
  2047. }
  2048. ast_io_remove(io, socket_read_id);
  2049. return NULL;
  2050. }
  2051. static void *process_clearcache(void *ignore)
  2052. {
  2053. struct ast_db_entry *db_entry, *db_tree;
  2054. int striplen = sizeof("/dundi/cache");
  2055. time_t now;
  2056. while (!dundi_shutdown) {
  2057. pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
  2058. time(&now);
  2059. db_entry = db_tree = ast_db_gettree("dundi/cache", NULL);
  2060. for (; db_entry; db_entry = db_entry->next) {
  2061. time_t expiry;
  2062. if (!ast_get_time_t(db_entry->data, &expiry, 0, NULL)) {
  2063. if (expiry < now) {
  2064. ast_debug(1, "clearing expired DUNDI cache entry: %s\n", db_entry->key);
  2065. ast_db_del("dundi/cache", db_entry->key + striplen);
  2066. }
  2067. }
  2068. }
  2069. ast_db_freetree(db_tree);
  2070. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2071. pthread_testcancel();
  2072. sleep(60);
  2073. pthread_testcancel();
  2074. }
  2075. return NULL;
  2076. }
  2077. static void *process_precache(void *ign)
  2078. {
  2079. struct dundi_precache_queue *qe;
  2080. time_t now;
  2081. char context[256];
  2082. char number[256];
  2083. int run;
  2084. while (!dundi_shutdown) {
  2085. time(&now);
  2086. run = 0;
  2087. AST_LIST_LOCK(&pcq);
  2088. if ((qe = AST_LIST_FIRST(&pcq))) {
  2089. if (!qe->expiration) {
  2090. /* Gone... Remove... */
  2091. AST_LIST_REMOVE_HEAD(&pcq, list);
  2092. ast_free(qe);
  2093. } else if (qe->expiration < now) {
  2094. /* Process this entry */
  2095. qe->expiration = 0;
  2096. ast_copy_string(context, qe->context, sizeof(context));
  2097. ast_copy_string(number, qe->number, sizeof(number));
  2098. run = 1;
  2099. }
  2100. }
  2101. AST_LIST_UNLOCK(&pcq);
  2102. if (run) {
  2103. dundi_precache(context, number);
  2104. } else
  2105. sleep(1);
  2106. }
  2107. return NULL;
  2108. }
  2109. static int start_network_thread(void)
  2110. {
  2111. ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL);
  2112. ast_pthread_create_background(&precachethreadid, NULL, process_precache, NULL);
  2113. ast_pthread_create_background(&clearcachethreadid, NULL, process_clearcache, NULL);
  2114. return 0;
  2115. }
  2116. static char *dundi_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2117. {
  2118. switch (cmd) {
  2119. case CLI_INIT:
  2120. e->command = "dundi set debug {on|off}";
  2121. e->usage =
  2122. "Usage: dundi set debug {on|off}\n"
  2123. " Enables/Disables dumping of DUNDi packets for debugging purposes\n";
  2124. return NULL;
  2125. case CLI_GENERATE:
  2126. return NULL;
  2127. }
  2128. if (a->argc != e->args) {
  2129. return CLI_SHOWUSAGE;
  2130. }
  2131. if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
  2132. dundidebug = 1;
  2133. ast_cli(a->fd, "DUNDi Debugging Enabled\n");
  2134. } else {
  2135. dundidebug = 0;
  2136. ast_cli(a->fd, "DUNDi Debugging Disabled\n");
  2137. }
  2138. return CLI_SUCCESS;
  2139. }
  2140. static char *dundi_store_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2141. {
  2142. switch (cmd) {
  2143. case CLI_INIT:
  2144. e->command = "dundi store history {on|off}";
  2145. e->usage =
  2146. "Usage: dundi store history {on|off}\n"
  2147. " Enables/Disables storing of DUNDi requests and times for debugging\n"
  2148. "purposes\n";
  2149. return NULL;
  2150. case CLI_GENERATE:
  2151. return NULL;
  2152. }
  2153. if (a->argc != e->args) {
  2154. return CLI_SHOWUSAGE;
  2155. }
  2156. if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
  2157. global_storehistory = 1;
  2158. ast_cli(a->fd, "DUNDi History Storage Enabled\n");
  2159. } else {
  2160. global_storehistory = 0;
  2161. ast_cli(a->fd, "DUNDi History Storage Disabled\n");
  2162. }
  2163. return CLI_SUCCESS;
  2164. }
  2165. static char *dundi_flush(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2166. {
  2167. int stats = 0;
  2168. switch (cmd) {
  2169. case CLI_INIT:
  2170. e->command = "dundi flush [stats]";
  2171. e->usage =
  2172. "Usage: dundi flush [stats]\n"
  2173. " Flushes DUNDi answer cache, used primarily for debug. If\n"
  2174. "'stats' is present, clears timer statistics instead of normal\n"
  2175. "operation.\n";
  2176. return NULL;
  2177. case CLI_GENERATE:
  2178. return NULL;
  2179. }
  2180. if ((a->argc < 2) || (a->argc > 3)) {
  2181. return CLI_SHOWUSAGE;
  2182. }
  2183. if (a->argc > 2) {
  2184. if (!strcasecmp(a->argv[2], "stats")) {
  2185. stats = 1;
  2186. } else {
  2187. return CLI_SHOWUSAGE;
  2188. }
  2189. }
  2190. if (stats) {
  2191. /* Flush statistics */
  2192. struct dundi_peer *p;
  2193. int x;
  2194. AST_LIST_LOCK(&peers);
  2195. AST_LIST_TRAVERSE(&peers, p, list) {
  2196. for (x = 0;x < DUNDI_TIMING_HISTORY; x++) {
  2197. ast_free(p->lookups[x]);
  2198. p->lookups[x] = NULL;
  2199. p->lookuptimes[x] = 0;
  2200. }
  2201. p->avgms = 0;
  2202. }
  2203. AST_LIST_UNLOCK(&peers);
  2204. } else {
  2205. ast_db_deltree("dundi/cache", NULL);
  2206. ast_cli(a->fd, "DUNDi Cache Flushed\n");
  2207. }
  2208. return CLI_SUCCESS;
  2209. }
  2210. static char *model2str(int model)
  2211. {
  2212. switch(model) {
  2213. case DUNDI_MODEL_INBOUND:
  2214. return "Inbound";
  2215. case DUNDI_MODEL_OUTBOUND:
  2216. return "Outbound";
  2217. case DUNDI_MODEL_SYMMETRIC:
  2218. return "Symmetric";
  2219. default:
  2220. return "Unknown";
  2221. }
  2222. }
  2223. static char *complete_peer_helper(const char *line, const char *word, int pos, int state, int rpos)
  2224. {
  2225. int which=0, len;
  2226. char *ret = NULL;
  2227. struct dundi_peer *p;
  2228. char eid_str[20];
  2229. if (pos != rpos)
  2230. return NULL;
  2231. AST_LIST_LOCK(&peers);
  2232. len = strlen(word);
  2233. AST_LIST_TRAVERSE(&peers, p, list) {
  2234. const char *s = ast_eid_to_str(eid_str, sizeof(eid_str), &p->eid);
  2235. if (!strncasecmp(word, s, len) && ++which > state) {
  2236. ret = ast_strdup(s);
  2237. break;
  2238. }
  2239. }
  2240. AST_LIST_UNLOCK(&peers);
  2241. return ret;
  2242. }
  2243. static int rescomp(const void *a, const void *b)
  2244. {
  2245. const struct dundi_result *resa, *resb;
  2246. resa = a;
  2247. resb = b;
  2248. if (resa->weight < resb->weight)
  2249. return -1;
  2250. if (resa->weight > resb->weight)
  2251. return 1;
  2252. return 0;
  2253. }
  2254. static void sort_results(struct dundi_result *results, int count)
  2255. {
  2256. qsort(results, count, sizeof(results[0]), rescomp);
  2257. }
  2258. static char *dundi_do_lookup(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2259. {
  2260. int res;
  2261. char tmp[256];
  2262. char fs[80] = "";
  2263. char *context;
  2264. int x;
  2265. int bypass = 0;
  2266. struct dundi_result dr[MAX_RESULTS];
  2267. struct timeval start;
  2268. switch (cmd) {
  2269. case CLI_INIT:
  2270. e->command = "dundi lookup";
  2271. e->usage =
  2272. "Usage: dundi lookup <number>[@context] [bypass]\n"
  2273. " Lookup the given number within the given DUNDi context\n"
  2274. "(or e164 if none is specified). Bypasses cache if 'bypass'\n"
  2275. "keyword is specified.\n";
  2276. return NULL;
  2277. case CLI_GENERATE:
  2278. return NULL;
  2279. }
  2280. if ((a->argc < 3) || (a->argc > 4)) {
  2281. return CLI_SHOWUSAGE;
  2282. }
  2283. if (a->argc > 3) {
  2284. if (!strcasecmp(a->argv[3], "bypass")) {
  2285. bypass=1;
  2286. } else {
  2287. return CLI_SHOWUSAGE;
  2288. }
  2289. }
  2290. ast_copy_string(tmp, a->argv[2], sizeof(tmp));
  2291. context = strchr(tmp, '@');
  2292. if (context) {
  2293. *context = '\0';
  2294. context++;
  2295. }
  2296. start = ast_tvnow();
  2297. res = dundi_lookup(dr, MAX_RESULTS, NULL, context, tmp, bypass);
  2298. if (res < 0)
  2299. ast_cli(a->fd, "DUNDi lookup returned error.\n");
  2300. else if (!res)
  2301. ast_cli(a->fd, "DUNDi lookup returned no results.\n");
  2302. else
  2303. sort_results(dr, res);
  2304. for (x=0;x<res;x++) {
  2305. ast_cli(a->fd, "%3d. %5d %s/%s (%s)\n", x + 1, dr[x].weight, dr[x].tech, dr[x].dest, dundi_flags2str(fs, sizeof(fs), dr[x].flags));
  2306. ast_cli(a->fd, " from %s, expires in %d s\n", dr[x].eid_str, dr[x].expiration);
  2307. }
  2308. ast_cli(a->fd, "DUNDi lookup completed in %" PRIi64 " ms\n", ast_tvdiff_ms(ast_tvnow(), start));
  2309. return CLI_SUCCESS;
  2310. }
  2311. static char *dundi_do_precache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2312. {
  2313. int res;
  2314. char tmp[256];
  2315. char *context;
  2316. struct timeval start;
  2317. switch (cmd) {
  2318. case CLI_INIT:
  2319. e->command = "dundi precache";
  2320. e->usage =
  2321. "Usage: dundi precache <number>[@context]\n"
  2322. " Lookup the given number within the given DUNDi context\n"
  2323. "(or e164 if none is specified) and precaches the results to any\n"
  2324. "upstream DUNDi push servers.\n";
  2325. return NULL;
  2326. case CLI_GENERATE:
  2327. return NULL;
  2328. }
  2329. if ((a->argc < 3) || (a->argc > 3)) {
  2330. return CLI_SHOWUSAGE;
  2331. }
  2332. ast_copy_string(tmp, a->argv[2], sizeof(tmp));
  2333. context = strchr(tmp, '@');
  2334. if (context) {
  2335. *context = '\0';
  2336. context++;
  2337. }
  2338. start = ast_tvnow();
  2339. res = dundi_precache(context, tmp);
  2340. if (res < 0)
  2341. ast_cli(a->fd, "DUNDi precache returned error.\n");
  2342. else if (!res)
  2343. ast_cli(a->fd, "DUNDi precache returned no error.\n");
  2344. ast_cli(a->fd, "DUNDi lookup completed in %" PRIi64 " ms\n", ast_tvdiff_ms(ast_tvnow(), start));
  2345. return CLI_SUCCESS;
  2346. }
  2347. static char *dundi_do_query(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2348. {
  2349. int res;
  2350. char tmp[256];
  2351. char *context;
  2352. dundi_eid eid;
  2353. struct dundi_entity_info dei;
  2354. switch (cmd) {
  2355. case CLI_INIT:
  2356. e->command = "dundi query";
  2357. e->usage =
  2358. "Usage: dundi query <entity>[@context]\n"
  2359. " Attempts to retrieve contact information for a specific\n"
  2360. "DUNDi entity identifier (EID) within a given DUNDi context (or\n"
  2361. "e164 if none is specified).\n";
  2362. return NULL;
  2363. case CLI_GENERATE:
  2364. return NULL;
  2365. }
  2366. if ((a->argc < 3) || (a->argc > 3)) {
  2367. return CLI_SHOWUSAGE;
  2368. }
  2369. if (ast_str_to_eid(&eid, a->argv[2])) {
  2370. ast_cli(a->fd, "'%s' is not a valid EID!\n", a->argv[2]);
  2371. return CLI_SHOWUSAGE;
  2372. }
  2373. ast_copy_string(tmp, a->argv[2], sizeof(tmp));
  2374. context = strchr(tmp, '@');
  2375. if (context) {
  2376. *context = '\0';
  2377. context++;
  2378. }
  2379. res = dundi_query_eid(&dei, context, eid);
  2380. if (res < 0)
  2381. ast_cli(a->fd, "DUNDi Query EID returned error.\n");
  2382. else if (!res)
  2383. ast_cli(a->fd, "DUNDi Query EID returned no results.\n");
  2384. else {
  2385. ast_cli(a->fd, "DUNDi Query EID succeeded:\n");
  2386. ast_cli(a->fd, "Department: %s\n", dei.orgunit);
  2387. ast_cli(a->fd, "Organization: %s\n", dei.org);
  2388. ast_cli(a->fd, "City/Locality: %s\n", dei.locality);
  2389. ast_cli(a->fd, "State/Province: %s\n", dei.stateprov);
  2390. ast_cli(a->fd, "Country: %s\n", dei.country);
  2391. ast_cli(a->fd, "E-mail: %s\n", dei.email);
  2392. ast_cli(a->fd, "Phone: %s\n", dei.phone);
  2393. ast_cli(a->fd, "IP Address: %s\n", dei.ipaddr);
  2394. }
  2395. return CLI_SUCCESS;
  2396. }
  2397. static char *dundi_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2398. {
  2399. struct dundi_peer *peer;
  2400. struct permission *p;
  2401. char *order;
  2402. char eid_str[20];
  2403. int x, cnt;
  2404. switch (cmd) {
  2405. case CLI_INIT:
  2406. e->command = "dundi show peer";
  2407. e->usage =
  2408. "Usage: dundi show peer [peer]\n"
  2409. " Provide a detailed description of a specifid DUNDi peer.\n";
  2410. return NULL;
  2411. case CLI_GENERATE:
  2412. return complete_peer_helper(a->line, a->word, a->pos, a->n, 3);
  2413. }
  2414. if (a->argc != 4) {
  2415. return CLI_SHOWUSAGE;
  2416. }
  2417. AST_LIST_LOCK(&peers);
  2418. AST_LIST_TRAVERSE(&peers, peer, list) {
  2419. if (!strcasecmp(ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid), a->argv[3]))
  2420. break;
  2421. }
  2422. if (peer) {
  2423. switch(peer->order) {
  2424. case 0:
  2425. order = "Primary";
  2426. break;
  2427. case 1:
  2428. order = "Secondary";
  2429. break;
  2430. case 2:
  2431. order = "Tertiary";
  2432. break;
  2433. case 3:
  2434. order = "Quartiary";
  2435. break;
  2436. default:
  2437. order = "Unknown";
  2438. }
  2439. ast_cli(a->fd, "Peer: %s\n", ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid));
  2440. ast_cli(a->fd, "Model: %s\n", model2str(peer->model));
  2441. ast_cli(a->fd, "Order: %s\n", order);
  2442. ast_cli(a->fd, "Host: %s\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "<Unspecified>");
  2443. ast_cli(a->fd, "Port: %d\n", ntohs(peer->addr.sin_port));
  2444. ast_cli(a->fd, "Dynamic: %s\n", peer->dynamic ? "yes" : "no");
  2445. ast_cli(a->fd, "Reg: %s\n", peer->registerid < 0 ? "No" : "Yes");
  2446. ast_cli(a->fd, "In Key: %s\n", ast_strlen_zero(peer->inkey) ? "<None>" : peer->inkey);
  2447. ast_cli(a->fd, "Out Key: %s\n", ast_strlen_zero(peer->outkey) ? "<None>" : peer->outkey);
  2448. if (!AST_LIST_EMPTY(&peer->include))
  2449. ast_cli(a->fd, "Include logic%s:\n", peer->model & DUNDI_MODEL_OUTBOUND ? "" : " (IGNORED)");
  2450. AST_LIST_TRAVERSE(&peer->include, p, list)
  2451. ast_cli(a->fd, "-- %s %s\n", p->allow ? "include" : "do not include", p->name);
  2452. if (!AST_LIST_EMPTY(&peer->permit))
  2453. ast_cli(a->fd, "Query logic%s:\n", peer->model & DUNDI_MODEL_INBOUND ? "" : " (IGNORED)");
  2454. AST_LIST_TRAVERSE(&peer->permit, p, list)
  2455. ast_cli(a->fd, "-- %s %s\n", p->allow ? "permit" : "deny", p->name);
  2456. cnt = 0;
  2457. for (x = 0;x < DUNDI_TIMING_HISTORY; x++) {
  2458. if (peer->lookups[x]) {
  2459. if (!cnt)
  2460. ast_cli(a->fd, "Last few query times:\n");
  2461. ast_cli(a->fd, "-- %d. %s (%d ms)\n", x + 1, peer->lookups[x], peer->lookuptimes[x]);
  2462. cnt++;
  2463. }
  2464. }
  2465. if (cnt)
  2466. ast_cli(a->fd, "Average query time: %d ms\n", peer->avgms);
  2467. } else
  2468. ast_cli(a->fd, "No such peer '%s'\n", a->argv[3]);
  2469. AST_LIST_UNLOCK(&peers);
  2470. return CLI_SUCCESS;
  2471. }
  2472. static char *dundi_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2473. {
  2474. #define FORMAT2 "%-20.20s %-15.15s %-6.6s %-10.10s %-8.8s %-15.15s\n"
  2475. #define FORMAT "%-20.20s %-15.15s %s %-6d %-10.10s %-8.8s %-15.15s\n"
  2476. struct dundi_peer *peer;
  2477. int registeredonly=0;
  2478. char avgms[20];
  2479. char eid_str[20];
  2480. int online_peers = 0;
  2481. int offline_peers = 0;
  2482. int unmonitored_peers = 0;
  2483. int total_peers = 0;
  2484. switch (cmd) {
  2485. case CLI_INIT:
  2486. e->command = "dundi show peers [registered|include|exclude|begin]";
  2487. e->usage =
  2488. "Usage: dundi show peers [registered|include|exclude|begin]\n"
  2489. " Lists all known DUNDi peers.\n"
  2490. " If 'registered' is present, only registered peers are shown.\n";
  2491. return NULL;
  2492. case CLI_GENERATE:
  2493. return NULL;
  2494. }
  2495. if ((a->argc != 3) && (a->argc != 4) && (a->argc != 5)) {
  2496. return CLI_SHOWUSAGE;
  2497. }
  2498. if ((a->argc == 4)) {
  2499. if (!strcasecmp(a->argv[3], "registered")) {
  2500. registeredonly = 1;
  2501. } else {
  2502. return CLI_SHOWUSAGE;
  2503. }
  2504. }
  2505. AST_LIST_LOCK(&peers);
  2506. ast_cli(a->fd, FORMAT2, "EID", "Host", "Port", "Model", "AvgTime", "Status");
  2507. AST_LIST_TRAVERSE(&peers, peer, list) {
  2508. char status[20];
  2509. int print_line = -1;
  2510. char srch[2000];
  2511. total_peers++;
  2512. if (registeredonly && !peer->addr.sin_addr.s_addr)
  2513. continue;
  2514. if (peer->maxms) {
  2515. if (peer->lastms < 0) {
  2516. strcpy(status, "UNREACHABLE");
  2517. offline_peers++;
  2518. }
  2519. else if (peer->lastms > peer->maxms) {
  2520. snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
  2521. offline_peers++;
  2522. }
  2523. else if (peer->lastms) {
  2524. snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
  2525. online_peers++;
  2526. }
  2527. else {
  2528. strcpy(status, "UNKNOWN");
  2529. offline_peers++;
  2530. }
  2531. } else {
  2532. strcpy(status, "Unmonitored");
  2533. unmonitored_peers++;
  2534. }
  2535. if (peer->avgms)
  2536. snprintf(avgms, sizeof(avgms), "%d ms", peer->avgms);
  2537. else
  2538. strcpy(avgms, "Unavail");
  2539. snprintf(srch, sizeof(srch), FORMAT, ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid),
  2540. peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
  2541. peer->dynamic ? "(D)" : "(S)", ntohs(peer->addr.sin_port), model2str(peer->model), avgms, status);
  2542. if (a->argc == 5) {
  2543. if (!strcasecmp(a->argv[3],"include") && strstr(srch,a->argv[4])) {
  2544. print_line = -1;
  2545. } else if (!strcasecmp(a->argv[3],"exclude") && !strstr(srch,a->argv[4])) {
  2546. print_line = 1;
  2547. } else if (!strcasecmp(a->argv[3],"begin") && !strncasecmp(srch,a->argv[4],strlen(a->argv[4]))) {
  2548. print_line = -1;
  2549. } else {
  2550. print_line = 0;
  2551. }
  2552. }
  2553. if (print_line) {
  2554. ast_cli(a->fd, FORMAT, ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid),
  2555. peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
  2556. peer->dynamic ? "(D)" : "(S)", ntohs(peer->addr.sin_port), model2str(peer->model), avgms, status);
  2557. }
  2558. }
  2559. ast_cli(a->fd, "%d dundi peers [%d online, %d offline, %d unmonitored]\n", total_peers, online_peers, offline_peers, unmonitored_peers);
  2560. AST_LIST_UNLOCK(&peers);
  2561. return CLI_SUCCESS;
  2562. #undef FORMAT
  2563. #undef FORMAT2
  2564. }
  2565. static char *dundi_show_trans(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2566. {
  2567. #define FORMAT2 "%-22.22s %-5.5s %-5.5s %-3.3s %-3.3s %-3.3s\n"
  2568. #define FORMAT "%-16.16s:%5d %-5.5d %-5.5d %-3.3d %-3.3d %-3.3d\n"
  2569. struct dundi_transaction *trans;
  2570. switch (cmd) {
  2571. case CLI_INIT:
  2572. e->command = "dundi show trans";
  2573. e->usage =
  2574. "Usage: dundi show trans\n"
  2575. " Lists all known DUNDi transactions.\n";
  2576. return NULL;
  2577. case CLI_GENERATE:
  2578. return NULL;
  2579. }
  2580. if (a->argc != 3) {
  2581. return CLI_SHOWUSAGE;
  2582. }
  2583. AST_LIST_LOCK(&peers);
  2584. ast_cli(a->fd, FORMAT2, "Remote", "Src", "Dst", "Tx", "Rx", "Ack");
  2585. AST_LIST_TRAVERSE(&alltrans, trans, all) {
  2586. ast_cli(a->fd, FORMAT, ast_inet_ntoa(trans->addr.sin_addr),
  2587. ntohs(trans->addr.sin_port), trans->strans, trans->dtrans, trans->oseqno, trans->iseqno, trans->aseqno);
  2588. }
  2589. AST_LIST_UNLOCK(&peers);
  2590. return CLI_SUCCESS;
  2591. #undef FORMAT
  2592. #undef FORMAT2
  2593. }
  2594. static char *dundi_show_entityid(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2595. {
  2596. char eid_str[20];
  2597. switch (cmd) {
  2598. case CLI_INIT:
  2599. e->command = "dundi show entityid";
  2600. e->usage =
  2601. "Usage: dundi show entityid\n"
  2602. " Displays the global entityid for this host.\n";
  2603. return NULL;
  2604. case CLI_GENERATE:
  2605. return NULL;
  2606. }
  2607. if (a->argc != 3) {
  2608. return CLI_SHOWUSAGE;
  2609. }
  2610. AST_LIST_LOCK(&peers);
  2611. ast_eid_to_str(eid_str, sizeof(eid_str), &global_eid);
  2612. AST_LIST_UNLOCK(&peers);
  2613. ast_cli(a->fd, "Global EID for this system is '%s'\n", eid_str);
  2614. return CLI_SUCCESS;
  2615. }
  2616. static char *dundi_show_requests(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2617. {
  2618. #define FORMAT2 "%-15s %-15s %-15s %-3.3s %-3.3s\n"
  2619. #define FORMAT "%-15s %-15s %-15s %-3.3d %-3.3d\n"
  2620. struct dundi_request *req;
  2621. char eidstr[20];
  2622. switch (cmd) {
  2623. case CLI_INIT:
  2624. e->command = "dundi show requests";
  2625. e->usage =
  2626. "Usage: dundi show requests\n"
  2627. " Lists all known pending DUNDi requests.\n";
  2628. return NULL;
  2629. case CLI_GENERATE:
  2630. return NULL;
  2631. }
  2632. if (a->argc != 3) {
  2633. return CLI_SHOWUSAGE;
  2634. }
  2635. AST_LIST_LOCK(&peers);
  2636. ast_cli(a->fd, FORMAT2, "Number", "Context", "Root", "Max", "Rsp");
  2637. AST_LIST_TRAVERSE(&requests, req, list) {
  2638. ast_cli(a->fd, FORMAT, req->number, req->dcontext,
  2639. dundi_eid_zero(&req->root_eid) ? "<unspecified>" : ast_eid_to_str(eidstr, sizeof(eidstr), &req->root_eid), req->maxcount, req->respcount);
  2640. }
  2641. AST_LIST_UNLOCK(&peers);
  2642. return CLI_SUCCESS;
  2643. #undef FORMAT
  2644. #undef FORMAT2
  2645. }
  2646. /* Grok-a-dial DUNDi */
  2647. static char *dundi_show_mappings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2648. {
  2649. #define FORMAT2 "%-12.12s %-7.7s %-12.12s %-10.10s %-5.5s %-25.25s\n"
  2650. #define FORMAT "%-12.12s %-7s %-12.12s %-10.10s %-5.5s %-25.25s\n"
  2651. struct dundi_mapping *map;
  2652. char fs[256];
  2653. char weight[8];
  2654. switch (cmd) {
  2655. case CLI_INIT:
  2656. e->command = "dundi show mappings";
  2657. e->usage =
  2658. "Usage: dundi show mappings\n"
  2659. " Lists all known DUNDi mappings.\n";
  2660. return NULL;
  2661. case CLI_GENERATE:
  2662. return NULL;
  2663. }
  2664. if (a->argc != 3) {
  2665. return CLI_SHOWUSAGE;
  2666. }
  2667. AST_LIST_LOCK(&peers);
  2668. ast_cli(a->fd, FORMAT2, "DUNDi Cntxt", "Weight", "Local Cntxt", "Options", "Tech", "Destination");
  2669. AST_LIST_TRAVERSE(&mappings, map, list) {
  2670. snprintf(weight, sizeof(weight), "%d", get_mapping_weight(map, NULL));
  2671. ast_cli(a->fd, FORMAT, map->dcontext, weight,
  2672. ast_strlen_zero(map->lcontext) ? "<none>" : map->lcontext,
  2673. dundi_flags2str(fs, sizeof(fs), map->options), tech2str(map->tech), map->dest);
  2674. }
  2675. AST_LIST_UNLOCK(&peers);
  2676. return CLI_SUCCESS;
  2677. #undef FORMAT
  2678. #undef FORMAT2
  2679. }
  2680. static char *dundi_show_precache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2681. {
  2682. #define FORMAT2 "%-12.12s %-12.12s %-10.10s\n"
  2683. #define FORMAT "%-12.12s %-12.12s %02d:%02d:%02d\n"
  2684. struct dundi_precache_queue *qe;
  2685. int h,m,s;
  2686. time_t now;
  2687. switch (cmd) {
  2688. case CLI_INIT:
  2689. e->command = "dundi show precache";
  2690. e->usage =
  2691. "Usage: dundi show precache\n"
  2692. " Lists all known DUNDi scheduled precache updates.\n";
  2693. return NULL;
  2694. case CLI_GENERATE:
  2695. return NULL;
  2696. }
  2697. if (a->argc != 3) {
  2698. return CLI_SHOWUSAGE;
  2699. }
  2700. time(&now);
  2701. ast_cli(a->fd, FORMAT2, "Number", "Context", "Expiration");
  2702. AST_LIST_LOCK(&pcq);
  2703. AST_LIST_TRAVERSE(&pcq, qe, list) {
  2704. s = qe->expiration - now;
  2705. h = s / 3600;
  2706. s = s % 3600;
  2707. m = s / 60;
  2708. s = s % 60;
  2709. ast_cli(a->fd, FORMAT, qe->number, qe->context, h,m,s);
  2710. }
  2711. AST_LIST_UNLOCK(&pcq);
  2712. return CLI_SUCCESS;
  2713. #undef FORMAT
  2714. #undef FORMAT2
  2715. }
  2716. static char *dundi_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2717. {
  2718. #define FORMAT2 "%-12.12s %-16.16s %-10.10s %-18s %-7s %s\n"
  2719. #define FORMAT "%-12.12s %-16.16s %6d sec %-18s %-7d %s/%s (%s)\n"
  2720. struct ast_db_entry *db_tree, *db_entry;
  2721. int cnt = 0;
  2722. time_t ts, now;
  2723. dundi_eid src_eid;
  2724. char src_eid_str[20];
  2725. int expiry, tech, weight;
  2726. struct ast_flags flags;
  2727. char fs[256];
  2728. int length;
  2729. char *ptr, *term, *src, *number, *context, *dst;
  2730. switch (cmd) {
  2731. case CLI_INIT:
  2732. e->command = "dundi show cache";
  2733. e->usage =
  2734. "Usage: dundi show cache\n"
  2735. " Lists all DUNDi cache entries.\n";
  2736. return NULL;
  2737. case CLI_GENERATE:
  2738. return NULL;
  2739. }
  2740. if (a->argc != 3) {
  2741. return CLI_SHOWUSAGE;
  2742. }
  2743. time(&now);
  2744. db_tree = ast_db_gettree("dundi/cache", NULL);
  2745. ast_cli(a->fd, FORMAT2, "Number", "Context", "Expiration", "From", "Weight", "Destination (Flags)");
  2746. for (db_entry = db_tree; db_entry; db_entry = db_entry->next) {
  2747. if ((strncmp(db_entry->key, "/dundi/cache/hint/", 18) == 0) || ast_get_time_t(db_entry->data, &ts, 0, &length)) {
  2748. continue;
  2749. }
  2750. expiry = ts - now;
  2751. if (expiry <= 0) {
  2752. continue;
  2753. }
  2754. ptr = db_entry->key + sizeof("/dundi/cache");
  2755. strtok(ptr, "/");
  2756. number = strtok(NULL, "/");
  2757. context = strtok(NULL, "/");
  2758. ptr = strtok(NULL, "/");
  2759. if (*ptr != 'e') {
  2760. continue;
  2761. }
  2762. ptr = db_entry->data + length + 1;
  2763. if ((sscanf(ptr, "%30u/%30d/%30d/%n", &(flags.flags), &weight, &tech, &length) != 3)) {
  2764. continue;
  2765. }
  2766. ptr += length;
  2767. dst = ptr;
  2768. term = strchr(ptr, '|');
  2769. if (!term) {
  2770. continue;
  2771. }
  2772. /* Ok, at this point we know we aren't going to skp the entry, so we go ahead and increment the count. */
  2773. cnt++;
  2774. *term = '\0';
  2775. src = strrchr(ptr, '/');
  2776. dundi_eid_zero(&src_eid);
  2777. if (src) {
  2778. *src = '\0';
  2779. src++;
  2780. dundi_str_short_to_eid(&src_eid, src);
  2781. ast_eid_to_str(src_eid_str, sizeof(src_eid_str), &src_eid);
  2782. }
  2783. ast_cli(a->fd, FORMAT, number, context, expiry, src_eid_str, weight, tech2str(tech), dst, dundi_flags2str(fs, sizeof(fs), flags.flags));
  2784. }
  2785. ast_cli(a->fd, "Number of entries: %d\n", cnt);
  2786. ast_db_freetree(db_tree);
  2787. return CLI_SUCCESS;
  2788. #undef FORMAT
  2789. #undef FORMAT2
  2790. }
  2791. static char *dundi_show_hints(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2792. {
  2793. #define FORMAT2 "%-12.12s %-16.16s %-10.10s %-18s\n"
  2794. #define FORMAT "%-12.12s %-16.16s %6d sec %-18s\n"
  2795. struct ast_db_entry *db_tree, *db_entry;
  2796. int cnt = 0;
  2797. time_t ts, now;
  2798. dundi_eid src_eid;
  2799. char src_eid_str[20];
  2800. int expiry;
  2801. int length;
  2802. char *ptr, *src, *number, *context;
  2803. switch (cmd) {
  2804. case CLI_INIT:
  2805. e->command = "dundi show hints";
  2806. e->usage =
  2807. "Usage: dundi show hints\n"
  2808. " Lists all DUNDi 'DONTASK' hints in the cache.\n";
  2809. return NULL;
  2810. case CLI_GENERATE:
  2811. return NULL;
  2812. }
  2813. if (a->argc != 3) {
  2814. return CLI_SHOWUSAGE;
  2815. }
  2816. time(&now);
  2817. db_tree = ast_db_gettree("dundi/cache/hint", NULL);
  2818. ast_cli(a->fd, FORMAT2, "Prefix", "Context", "Expiration", "From");
  2819. for (db_entry = db_tree; db_entry; db_entry = db_entry->next) {
  2820. if (ast_get_time_t(db_entry->data, &ts, 0, &length)) {
  2821. continue;
  2822. }
  2823. expiry = ts - now;
  2824. if (expiry <= 0) {
  2825. continue;
  2826. }
  2827. ptr = db_entry->key + sizeof("/dundi/cache/hint");
  2828. src = strtok(ptr, "/");
  2829. number = strtok(NULL, "/");
  2830. context = strtok(NULL, "/");
  2831. ptr = strtok(NULL, "/");
  2832. if (*ptr != 'e') {
  2833. continue;
  2834. }
  2835. cnt++;
  2836. dundi_str_short_to_eid(&src_eid, src);
  2837. ast_eid_to_str(src_eid_str, sizeof(src_eid_str), &src_eid);
  2838. ast_cli(a->fd, FORMAT, number, context, expiry, src_eid_str);
  2839. }
  2840. ast_cli(a->fd, "Number of entries: %d\n", cnt);
  2841. ast_db_freetree(db_tree);
  2842. return CLI_SUCCESS;
  2843. #undef FORMAT
  2844. #undef FORMAT2
  2845. }
  2846. static struct ast_cli_entry cli_dundi[] = {
  2847. AST_CLI_DEFINE(dundi_set_debug, "Enable/Disable DUNDi debugging"),
  2848. AST_CLI_DEFINE(dundi_store_history, "Enable/Disable DUNDi historic records"),
  2849. AST_CLI_DEFINE(dundi_flush, "Flush DUNDi cache"),
  2850. AST_CLI_DEFINE(dundi_show_peers, "Show defined DUNDi peers"),
  2851. AST_CLI_DEFINE(dundi_show_trans, "Show active DUNDi transactions"),
  2852. AST_CLI_DEFINE(dundi_show_entityid, "Display Global Entity ID"),
  2853. AST_CLI_DEFINE(dundi_show_mappings, "Show DUNDi mappings"),
  2854. AST_CLI_DEFINE(dundi_show_precache, "Show DUNDi precache"),
  2855. AST_CLI_DEFINE(dundi_show_requests, "Show DUNDi requests"),
  2856. AST_CLI_DEFINE(dundi_show_peer, "Show info on a specific DUNDi peer"),
  2857. AST_CLI_DEFINE(dundi_show_cache, "Show DUNDi cache"),
  2858. AST_CLI_DEFINE(dundi_show_hints, "Show DUNDi hints in the cache"),
  2859. AST_CLI_DEFINE(dundi_do_precache, "Precache a number in DUNDi"),
  2860. AST_CLI_DEFINE(dundi_do_lookup, "Lookup a number in DUNDi"),
  2861. AST_CLI_DEFINE(dundi_do_query, "Query a DUNDi EID"),
  2862. };
  2863. static struct dundi_transaction *create_transaction(struct dundi_peer *p)
  2864. {
  2865. struct dundi_transaction *trans;
  2866. int tid;
  2867. /* Don't allow creation of transactions to non-registered peers */
  2868. if (p && !p->addr.sin_addr.s_addr)
  2869. return NULL;
  2870. tid = get_trans_id();
  2871. if (tid < 1)
  2872. return NULL;
  2873. if (!(trans = ast_calloc(1, sizeof(*trans))))
  2874. return NULL;
  2875. if (global_storehistory) {
  2876. trans->start = ast_tvnow();
  2877. ast_set_flag(trans, FLAG_STOREHIST);
  2878. }
  2879. trans->retranstimer = DUNDI_DEFAULT_RETRANS_TIMER;
  2880. trans->autokillid = -1;
  2881. if (p) {
  2882. apply_peer(trans, p);
  2883. if (!p->sentfullkey)
  2884. ast_set_flag(trans, FLAG_SENDFULLKEY);
  2885. }
  2886. trans->strans = tid;
  2887. AST_LIST_INSERT_HEAD(&alltrans, trans, all);
  2888. return trans;
  2889. }
  2890. static int dundi_xmit(struct dundi_packet *pack)
  2891. {
  2892. int res;
  2893. if (dundidebug)
  2894. dundi_showframe(pack->h, 0, &pack->parent->addr, pack->datalen - sizeof(struct dundi_hdr));
  2895. res = sendto(netsocket, pack->data, pack->datalen, 0, (struct sockaddr *)&pack->parent->addr, sizeof(pack->parent->addr));
  2896. if (res < 0) {
  2897. ast_log(LOG_WARNING, "Failed to transmit to '%s:%d': %s\n",
  2898. ast_inet_ntoa(pack->parent->addr.sin_addr),
  2899. ntohs(pack->parent->addr.sin_port), strerror(errno));
  2900. }
  2901. if (res > 0)
  2902. res = 0;
  2903. return res;
  2904. }
  2905. static void destroy_packet(struct dundi_packet *pack, int needfree)
  2906. {
  2907. if (pack->parent)
  2908. AST_LIST_REMOVE(&pack->parent->packets, pack, list);
  2909. AST_SCHED_DEL(sched, pack->retransid);
  2910. if (needfree)
  2911. ast_free(pack);
  2912. }
  2913. static void destroy_trans(struct dundi_transaction *trans, int fromtimeout)
  2914. {
  2915. struct dundi_peer *peer;
  2916. int ms;
  2917. int x;
  2918. int cnt;
  2919. char eid_str[20];
  2920. if (ast_test_flag(trans, FLAG_ISREG | FLAG_ISQUAL | FLAG_STOREHIST)) {
  2921. AST_LIST_TRAVERSE(&peers, peer, list) {
  2922. if (peer->regtrans == trans)
  2923. peer->regtrans = NULL;
  2924. if (peer->qualtrans == trans) {
  2925. if (fromtimeout) {
  2926. if (peer->lastms > -1)
  2927. ast_log(LOG_NOTICE, "Peer '%s' has become UNREACHABLE!\n", ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid));
  2928. peer->lastms = -1;
  2929. } else {
  2930. ms = ast_tvdiff_ms(ast_tvnow(), peer->qualtx);
  2931. if (ms < 1)
  2932. ms = 1;
  2933. if (ms < peer->maxms) {
  2934. if ((peer->lastms >= peer->maxms) || (peer->lastms < 0))
  2935. ast_log(LOG_NOTICE, "Peer '%s' has become REACHABLE!\n", ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid));
  2936. } else if (peer->lastms < peer->maxms) {
  2937. ast_log(LOG_NOTICE, "Peer '%s' has become TOO LAGGED (%d ms)\n", ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid), ms);
  2938. }
  2939. peer->lastms = ms;
  2940. }
  2941. peer->qualtrans = NULL;
  2942. }
  2943. if (ast_test_flag(trans, FLAG_STOREHIST)) {
  2944. if (trans->parent && !ast_strlen_zero(trans->parent->number)) {
  2945. if (!ast_eid_cmp(&trans->them_eid, &peer->eid)) {
  2946. peer->avgms = 0;
  2947. cnt = 0;
  2948. ast_free(peer->lookups[DUNDI_TIMING_HISTORY - 1]);
  2949. for (x=DUNDI_TIMING_HISTORY-1;x>0;x--) {
  2950. peer->lookuptimes[x] = peer->lookuptimes[x-1];
  2951. peer->lookups[x] = peer->lookups[x-1];
  2952. if (peer->lookups[x]) {
  2953. peer->avgms += peer->lookuptimes[x];
  2954. cnt++;
  2955. }
  2956. }
  2957. peer->lookuptimes[0] = ast_tvdiff_ms(ast_tvnow(), trans->start);
  2958. peer->lookups[0] = ast_malloc(strlen(trans->parent->number) + strlen(trans->parent->dcontext) + 2);
  2959. if (peer->lookups[0]) {
  2960. sprintf(peer->lookups[0], "%s@%s", trans->parent->number, trans->parent->dcontext);
  2961. peer->avgms += peer->lookuptimes[0];
  2962. cnt++;
  2963. }
  2964. if (cnt)
  2965. peer->avgms /= cnt;
  2966. }
  2967. }
  2968. }
  2969. }
  2970. }
  2971. if (trans->parent) {
  2972. /* Unlink from parent if appropriate */
  2973. AST_LIST_REMOVE(&trans->parent->trans, trans, parentlist);
  2974. if (AST_LIST_EMPTY(&trans->parent->trans)) {
  2975. /* Wake up sleeper */
  2976. if (trans->parent->pfds[1] > -1) {
  2977. if (write(trans->parent->pfds[1], "killa!", 6) < 0) {
  2978. ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
  2979. }
  2980. }
  2981. }
  2982. }
  2983. /* Unlink from all trans */
  2984. AST_LIST_REMOVE(&alltrans, trans, all);
  2985. destroy_packets(&trans->packets);
  2986. destroy_packets(&trans->lasttrans);
  2987. AST_SCHED_DEL(sched, trans->autokillid);
  2988. if (trans->thread) {
  2989. /* If used by a thread, mark as dead and be done */
  2990. ast_set_flag(trans, FLAG_DEAD);
  2991. } else
  2992. ast_free(trans);
  2993. }
  2994. static int dundi_rexmit(const void *data)
  2995. {
  2996. struct dundi_packet *pack = (struct dundi_packet *)data;
  2997. int res;
  2998. AST_LIST_LOCK(&peers);
  2999. if (pack->retrans < 1) {
  3000. pack->retransid = -1;
  3001. if (!ast_test_flag(pack->parent, FLAG_ISQUAL))
  3002. ast_log(LOG_NOTICE, "Max retries exceeded to host '%s:%d' msg %d on call %d\n",
  3003. ast_inet_ntoa(pack->parent->addr.sin_addr),
  3004. ntohs(pack->parent->addr.sin_port), pack->h->oseqno, ntohs(pack->h->strans));
  3005. destroy_trans(pack->parent, 1);
  3006. res = 0;
  3007. } else {
  3008. /* Decrement retransmission, try again */
  3009. pack->retrans--;
  3010. dundi_xmit(pack);
  3011. res = 1;
  3012. }
  3013. AST_LIST_UNLOCK(&peers);
  3014. return res;
  3015. }
  3016. static int dundi_send(struct dundi_transaction *trans, int cmdresp, int flags, int final, struct dundi_ie_data *ied)
  3017. {
  3018. struct dundi_packet *pack;
  3019. int res;
  3020. int len;
  3021. char eid_str[20];
  3022. len = sizeof(struct dundi_packet) + sizeof(struct dundi_hdr) + (ied ? ied->pos : 0);
  3023. /* Reserve enough space for encryption */
  3024. if (ast_test_flag(trans, FLAG_ENCRYPT))
  3025. len += 384;
  3026. pack = ast_calloc(1, len);
  3027. if (pack) {
  3028. pack->h = (struct dundi_hdr *)(pack->data);
  3029. pack->retransid = -1;
  3030. if (cmdresp != DUNDI_COMMAND_ACK) {
  3031. pack->retransid = ast_sched_add(sched, trans->retranstimer, dundi_rexmit, pack);
  3032. pack->retrans = DUNDI_DEFAULT_RETRANS - 1;
  3033. AST_LIST_INSERT_HEAD(&trans->packets, pack, list);
  3034. }
  3035. pack->parent = trans;
  3036. pack->h->strans = htons(trans->strans);
  3037. pack->h->dtrans = htons(trans->dtrans);
  3038. pack->h->iseqno = trans->iseqno;
  3039. pack->h->oseqno = trans->oseqno;
  3040. pack->h->cmdresp = cmdresp;
  3041. pack->datalen = sizeof(struct dundi_hdr);
  3042. if (ied) {
  3043. memcpy(pack->h->ies, ied->buf, ied->pos);
  3044. pack->datalen += ied->pos;
  3045. }
  3046. if (final) {
  3047. pack->h->cmdresp |= DUNDI_COMMAND_FINAL;
  3048. ast_set_flag(trans, FLAG_FINAL);
  3049. }
  3050. pack->h->cmdflags = flags;
  3051. if (cmdresp != DUNDI_COMMAND_ACK) {
  3052. trans->oseqno++;
  3053. trans->oseqno = trans->oseqno % 256;
  3054. }
  3055. trans->aseqno = trans->iseqno;
  3056. /* If we have their public key, encrypt */
  3057. if (ast_test_flag(trans, FLAG_ENCRYPT)) {
  3058. switch(cmdresp) {
  3059. case DUNDI_COMMAND_REGREQ:
  3060. case DUNDI_COMMAND_REGRESPONSE:
  3061. case DUNDI_COMMAND_DPDISCOVER:
  3062. case DUNDI_COMMAND_DPRESPONSE:
  3063. case DUNDI_COMMAND_EIDQUERY:
  3064. case DUNDI_COMMAND_EIDRESPONSE:
  3065. case DUNDI_COMMAND_PRECACHERQ:
  3066. case DUNDI_COMMAND_PRECACHERP:
  3067. if (dundidebug)
  3068. dundi_showframe(pack->h, 2, &trans->addr, pack->datalen - sizeof(struct dundi_hdr));
  3069. res = dundi_encrypt(trans, pack);
  3070. break;
  3071. default:
  3072. res = 0;
  3073. }
  3074. } else
  3075. res = 0;
  3076. if (!res)
  3077. res = dundi_xmit(pack);
  3078. if (res)
  3079. ast_log(LOG_NOTICE, "Failed to send packet to '%s'\n", ast_eid_to_str(eid_str, sizeof(eid_str), &trans->them_eid));
  3080. if (cmdresp == DUNDI_COMMAND_ACK)
  3081. ast_free(pack);
  3082. return res;
  3083. }
  3084. return -1;
  3085. }
  3086. static int do_autokill(const void *data)
  3087. {
  3088. struct dundi_transaction *trans = (struct dundi_transaction *)data;
  3089. char eid_str[20];
  3090. ast_log(LOG_NOTICE, "Transaction to '%s' took too long to ACK, destroying\n",
  3091. ast_eid_to_str(eid_str, sizeof(eid_str), &trans->them_eid));
  3092. trans->autokillid = -1;
  3093. destroy_trans(trans, 0); /* We could actually set it to 1 instead of 0, but we won't ;-) */
  3094. return 0;
  3095. }
  3096. static void dundi_ie_append_eid_appropriately(struct dundi_ie_data *ied, char *context, dundi_eid *eid, dundi_eid *us)
  3097. {
  3098. struct dundi_peer *p;
  3099. if (!ast_eid_cmp(eid, us)) {
  3100. dundi_ie_append_eid(ied, DUNDI_IE_EID_DIRECT, eid);
  3101. return;
  3102. }
  3103. AST_LIST_LOCK(&peers);
  3104. AST_LIST_TRAVERSE(&peers, p, list) {
  3105. if (!ast_eid_cmp(&p->eid, eid)) {
  3106. if (has_permission(&p->include, context))
  3107. dundi_ie_append_eid(ied, DUNDI_IE_EID_DIRECT, eid);
  3108. else
  3109. dundi_ie_append_eid(ied, DUNDI_IE_EID, eid);
  3110. break;
  3111. }
  3112. }
  3113. if (!p)
  3114. dundi_ie_append_eid(ied, DUNDI_IE_EID, eid);
  3115. AST_LIST_UNLOCK(&peers);
  3116. }
  3117. static int dundi_discover(struct dundi_transaction *trans)
  3118. {
  3119. struct dundi_ie_data ied;
  3120. int x;
  3121. if (!trans->parent) {
  3122. ast_log(LOG_WARNING, "Tried to discover a transaction with no parent?!?\n");
  3123. return -1;
  3124. }
  3125. memset(&ied, 0, sizeof(ied));
  3126. dundi_ie_append_short(&ied, DUNDI_IE_VERSION, DUNDI_DEFAULT_VERSION);
  3127. if (!dundi_eid_zero(&trans->us_eid))
  3128. dundi_ie_append_eid(&ied, DUNDI_IE_EID_DIRECT, &trans->us_eid);
  3129. for (x=0;x<trans->eidcount;x++)
  3130. dundi_ie_append_eid_appropriately(&ied, trans->parent->dcontext, &trans->eids[x], &trans->us_eid);
  3131. dundi_ie_append_str(&ied, DUNDI_IE_CALLED_NUMBER, trans->parent->number);
  3132. dundi_ie_append_str(&ied, DUNDI_IE_CALLED_CONTEXT, trans->parent->dcontext);
  3133. dundi_ie_append_short(&ied, DUNDI_IE_TTL, trans->ttl);
  3134. if (trans->parent->cbypass)
  3135. dundi_ie_append(&ied, DUNDI_IE_CACHEBYPASS);
  3136. if (trans->autokilltimeout)
  3137. trans->autokillid = ast_sched_add(sched, trans->autokilltimeout, do_autokill, trans);
  3138. return dundi_send(trans, DUNDI_COMMAND_DPDISCOVER, 0, 0, &ied);
  3139. }
  3140. static int precache_trans(struct dundi_transaction *trans, struct dundi_mapping *maps, int mapcount, int *minexp, int *foundanswers)
  3141. {
  3142. struct dundi_ie_data ied;
  3143. int x, res;
  3144. int max = 999999;
  3145. int expiration = dundi_cache_time;
  3146. int ouranswers=0;
  3147. dundi_eid *avoid[1] = { NULL, };
  3148. int direct[1] = { 0, };
  3149. struct dundi_result dr[MAX_RESULTS];
  3150. struct dundi_hint_metadata hmd;
  3151. if (!trans->parent) {
  3152. ast_log(LOG_WARNING, "Tried to discover a transaction with no parent?!?\n");
  3153. return -1;
  3154. }
  3155. memset(&hmd, 0, sizeof(hmd));
  3156. memset(&dr, 0, sizeof(dr));
  3157. /* Look up the answers we're going to include */
  3158. for (x=0;x<mapcount;x++)
  3159. ouranswers = dundi_lookup_local(dr, maps + x, trans->parent->number, &trans->us_eid, ouranswers, &hmd);
  3160. if (ouranswers < 0)
  3161. ouranswers = 0;
  3162. for (x=0;x<ouranswers;x++) {
  3163. if (dr[x].weight < max)
  3164. max = dr[x].weight;
  3165. }
  3166. if (max) {
  3167. /* If we do not have a canonical result, keep looking */
  3168. res = dundi_lookup_internal(dr + ouranswers, MAX_RESULTS - ouranswers, NULL, trans->parent->dcontext, trans->parent->number, trans->ttl, 1, &hmd, &expiration, 0, 1, &trans->them_eid, avoid, direct);
  3169. if (res > 0) {
  3170. /* Append answer in result */
  3171. ouranswers += res;
  3172. }
  3173. }
  3174. if (ouranswers > 0) {
  3175. *foundanswers += ouranswers;
  3176. memset(&ied, 0, sizeof(ied));
  3177. dundi_ie_append_short(&ied, DUNDI_IE_VERSION, DUNDI_DEFAULT_VERSION);
  3178. if (!dundi_eid_zero(&trans->us_eid))
  3179. dundi_ie_append_eid(&ied, DUNDI_IE_EID, &trans->us_eid);
  3180. for (x=0;x<trans->eidcount;x++)
  3181. dundi_ie_append_eid(&ied, DUNDI_IE_EID, &trans->eids[x]);
  3182. dundi_ie_append_str(&ied, DUNDI_IE_CALLED_NUMBER, trans->parent->number);
  3183. dundi_ie_append_str(&ied, DUNDI_IE_CALLED_CONTEXT, trans->parent->dcontext);
  3184. dundi_ie_append_short(&ied, DUNDI_IE_TTL, trans->ttl);
  3185. for (x=0;x<ouranswers;x++) {
  3186. /* Add answers */
  3187. if (dr[x].expiration && (expiration > dr[x].expiration))
  3188. expiration = dr[x].expiration;
  3189. dundi_ie_append_answer(&ied, DUNDI_IE_ANSWER, &dr[x].eid, dr[x].techint, dr[x].flags, dr[x].weight, dr[x].dest);
  3190. }
  3191. dundi_ie_append_hint(&ied, DUNDI_IE_HINT, hmd.flags, hmd.exten);
  3192. dundi_ie_append_short(&ied, DUNDI_IE_EXPIRATION, expiration);
  3193. if (trans->autokilltimeout)
  3194. trans->autokillid = ast_sched_add(sched, trans->autokilltimeout, do_autokill, trans);
  3195. if (expiration < *minexp)
  3196. *minexp = expiration;
  3197. return dundi_send(trans, DUNDI_COMMAND_PRECACHERQ, 0, 0, &ied);
  3198. } else {
  3199. /* Oops, nothing to send... */
  3200. destroy_trans(trans, 0);
  3201. return 0;
  3202. }
  3203. }
  3204. static int dundi_query(struct dundi_transaction *trans)
  3205. {
  3206. struct dundi_ie_data ied;
  3207. int x;
  3208. if (!trans->parent) {
  3209. ast_log(LOG_WARNING, "Tried to query a transaction with no parent?!?\n");
  3210. return -1;
  3211. }
  3212. memset(&ied, 0, sizeof(ied));
  3213. dundi_ie_append_short(&ied, DUNDI_IE_VERSION, DUNDI_DEFAULT_VERSION);
  3214. if (!dundi_eid_zero(&trans->us_eid))
  3215. dundi_ie_append_eid(&ied, DUNDI_IE_EID, &trans->us_eid);
  3216. for (x=0;x<trans->eidcount;x++)
  3217. dundi_ie_append_eid(&ied, DUNDI_IE_EID, &trans->eids[x]);
  3218. dundi_ie_append_eid(&ied, DUNDI_IE_REQEID, &trans->parent->query_eid);
  3219. dundi_ie_append_str(&ied, DUNDI_IE_CALLED_CONTEXT, trans->parent->dcontext);
  3220. dundi_ie_append_short(&ied, DUNDI_IE_TTL, trans->ttl);
  3221. if (trans->autokilltimeout)
  3222. trans->autokillid = ast_sched_add(sched, trans->autokilltimeout, do_autokill, trans);
  3223. return dundi_send(trans, DUNDI_COMMAND_EIDQUERY, 0, 0, &ied);
  3224. }
  3225. static int discover_transactions(struct dundi_request *dr)
  3226. {
  3227. struct dundi_transaction *trans;
  3228. AST_LIST_LOCK(&peers);
  3229. AST_LIST_TRAVERSE(&dr->trans, trans, parentlist) {
  3230. dundi_discover(trans);
  3231. }
  3232. AST_LIST_UNLOCK(&peers);
  3233. return 0;
  3234. }
  3235. static int precache_transactions(struct dundi_request *dr, struct dundi_mapping *maps, int mapcount, int *expiration, int *foundanswers)
  3236. {
  3237. struct dundi_transaction *trans;
  3238. /* Mark all as "in thread" so they don't disappear */
  3239. AST_LIST_LOCK(&peers);
  3240. AST_LIST_TRAVERSE(&dr->trans, trans, parentlist) {
  3241. if (trans->thread)
  3242. ast_log(LOG_WARNING, "This shouldn't happen, really...\n");
  3243. trans->thread = 1;
  3244. }
  3245. AST_LIST_UNLOCK(&peers);
  3246. AST_LIST_TRAVERSE(&dr->trans, trans, parentlist) {
  3247. if (!ast_test_flag(trans, FLAG_DEAD))
  3248. precache_trans(trans, maps, mapcount, expiration, foundanswers);
  3249. }
  3250. /* Cleanup any that got destroyed in the mean time */
  3251. AST_LIST_LOCK(&peers);
  3252. AST_LIST_TRAVERSE_SAFE_BEGIN(&dr->trans, trans, parentlist) {
  3253. trans->thread = 0;
  3254. if (ast_test_flag(trans, FLAG_DEAD)) {
  3255. ast_debug(1, "Our transaction went away!\n");
  3256. /* This is going to remove the transaction from the dundi_request's list, as well
  3257. * as the global transactions list */
  3258. destroy_trans(trans, 0);
  3259. }
  3260. }
  3261. AST_LIST_TRAVERSE_SAFE_END
  3262. AST_LIST_UNLOCK(&peers);
  3263. return 0;
  3264. }
  3265. static int query_transactions(struct dundi_request *dr)
  3266. {
  3267. struct dundi_transaction *trans;
  3268. AST_LIST_LOCK(&peers);
  3269. AST_LIST_TRAVERSE(&dr->trans, trans, parentlist) {
  3270. dundi_query(trans);
  3271. }
  3272. AST_LIST_UNLOCK(&peers);
  3273. return 0;
  3274. }
  3275. static int optimize_transactions(struct dundi_request *dr, int order)
  3276. {
  3277. /* Minimize the message propagation through DUNDi by
  3278. alerting the network to hops which should be not be considered */
  3279. struct dundi_transaction *trans;
  3280. struct dundi_peer *peer;
  3281. dundi_eid tmp;
  3282. int x;
  3283. int needpush;
  3284. AST_LIST_LOCK(&peers);
  3285. AST_LIST_TRAVERSE(&dr->trans, trans, parentlist) {
  3286. /* Pop off the true root */
  3287. if (trans->eidcount) {
  3288. tmp = trans->eids[--trans->eidcount];
  3289. needpush = 1;
  3290. } else {
  3291. tmp = trans->us_eid;
  3292. needpush = 0;
  3293. }
  3294. AST_LIST_TRAVERSE(&peers, peer, list) {
  3295. if (ast_eid_cmp(&peer->eid, &empty_eid) && /* peer's eid is not empty (in case of dynamic peers) */
  3296. (peer->lastms > -1) && /* peer is reachable */
  3297. has_permission(&peer->include, dr->dcontext) && /* peer has destination context */
  3298. ast_eid_cmp(&peer->eid, &trans->them_eid) && /* peer is not transaction endpoint */
  3299. (peer->order <= order)) {
  3300. /* For each other transaction, make sure we don't
  3301. ask this EID about the others if they're not
  3302. already in the list */
  3303. if (!ast_eid_cmp(&tmp, &peer->eid))
  3304. x = -1;
  3305. else {
  3306. for (x=0;x<trans->eidcount;x++) {
  3307. if (!ast_eid_cmp(&trans->eids[x], &peer->eid))
  3308. break;
  3309. }
  3310. }
  3311. if (x == trans->eidcount) {
  3312. /* Nope not in the list, if needed, add us at the end since we're the source */
  3313. if (trans->eidcount < DUNDI_MAX_STACK - needpush) {
  3314. trans->eids[trans->eidcount++] = peer->eid;
  3315. /* Need to insert the real root (or us) at the bottom now as
  3316. a requirement now. */
  3317. needpush = 1;
  3318. }
  3319. }
  3320. }
  3321. }
  3322. /* If necessary, push the true root back on the end */
  3323. if (needpush)
  3324. trans->eids[trans->eidcount++] = tmp;
  3325. }
  3326. AST_LIST_UNLOCK(&peers);
  3327. return 0;
  3328. }
  3329. static int append_transaction(struct dundi_request *dr, struct dundi_peer *p, int ttl, dundi_eid *avoid[])
  3330. {
  3331. struct dundi_transaction *trans;
  3332. int x;
  3333. char eid_str[20];
  3334. char eid_str2[20];
  3335. /* Ignore if not registered */
  3336. if (!p->addr.sin_addr.s_addr)
  3337. return 0;
  3338. if (p->maxms && ((p->lastms < 0) || (p->lastms >= p->maxms)))
  3339. return 0;
  3340. if (ast_strlen_zero(dr->number))
  3341. ast_debug(1, "Will query peer '%s' for '%s' (context '%s')\n", ast_eid_to_str(eid_str, sizeof(eid_str), &p->eid), ast_eid_to_str(eid_str2, sizeof(eid_str2), &dr->query_eid), dr->dcontext);
  3342. else
  3343. ast_debug(1, "Will query peer '%s' for '%s@%s'\n", ast_eid_to_str(eid_str, sizeof(eid_str), &p->eid), dr->number, dr->dcontext);
  3344. trans = create_transaction(p);
  3345. if (!trans)
  3346. return -1;
  3347. trans->parent = dr;
  3348. trans->ttl = ttl;
  3349. for (x = 0; avoid[x] && (x < DUNDI_MAX_STACK); x++)
  3350. trans->eids[x] = *avoid[x];
  3351. trans->eidcount = x;
  3352. AST_LIST_INSERT_HEAD(&dr->trans, trans, parentlist);
  3353. return 0;
  3354. }
  3355. static void cancel_request(struct dundi_request *dr)
  3356. {
  3357. struct dundi_transaction *trans;
  3358. AST_LIST_LOCK(&peers);
  3359. while ((trans = AST_LIST_REMOVE_HEAD(&dr->trans, parentlist))) {
  3360. /* Orphan transaction from request */
  3361. trans->parent = NULL;
  3362. /* Send final cancel */
  3363. dundi_send(trans, DUNDI_COMMAND_CANCEL, 0, 1, NULL);
  3364. }
  3365. AST_LIST_UNLOCK(&peers);
  3366. }
  3367. static void abort_request(struct dundi_request *dr)
  3368. {
  3369. struct dundi_transaction *trans;
  3370. AST_LIST_LOCK(&peers);
  3371. while ((trans = AST_LIST_FIRST(&dr->trans))) {
  3372. /* This will remove the transaction from the list */
  3373. destroy_trans(trans, 0);
  3374. }
  3375. AST_LIST_UNLOCK(&peers);
  3376. }
  3377. static void build_transactions(struct dundi_request *dr, int ttl, int order, int *foundcache, int *skipped, int blockempty, int nocache, int modeselect, dundi_eid *skip, dundi_eid *avoid[], int directs[])
  3378. {
  3379. struct dundi_peer *p;
  3380. int x;
  3381. int res;
  3382. int pass;
  3383. int allowconnect;
  3384. char eid_str[20];
  3385. AST_LIST_LOCK(&peers);
  3386. AST_LIST_TRAVERSE(&peers, p, list) {
  3387. if (modeselect == 1) {
  3388. /* Send the precache to push upstreams only! */
  3389. pass = has_permission(&p->permit, dr->dcontext) && (p->pcmodel & DUNDI_MODEL_OUTBOUND);
  3390. allowconnect = 1;
  3391. } else {
  3392. /* Normal lookup / EID query */
  3393. pass = has_permission(&p->include, dr->dcontext);
  3394. allowconnect = p->model & DUNDI_MODEL_OUTBOUND;
  3395. }
  3396. if (skip) {
  3397. if (!ast_eid_cmp(skip, &p->eid))
  3398. pass = 0;
  3399. }
  3400. if (pass) {
  3401. if (p->order <= order) {
  3402. /* Check order first, then check cache, regardless of
  3403. omissions, this gets us more likely to not have an
  3404. affected answer. */
  3405. if((nocache || !(res = cache_lookup(dr, &p->eid, dr->crc32, &dr->expiration)))) {
  3406. res = 0;
  3407. /* Make sure we haven't already seen it and that it won't
  3408. affect our answer */
  3409. for (x=0;avoid[x];x++) {
  3410. if (!ast_eid_cmp(avoid[x], &p->eid) || !ast_eid_cmp(avoid[x], &p->us_eid)) {
  3411. /* If not a direct connection, it affects our answer */
  3412. if (directs && !directs[x])
  3413. ast_clear_flag_nonstd(dr->hmd, DUNDI_HINT_UNAFFECTED);
  3414. break;
  3415. }
  3416. }
  3417. /* Make sure we can ask */
  3418. if (allowconnect) {
  3419. if (!avoid[x] && (!blockempty || !dundi_eid_zero(&p->us_eid))) {
  3420. /* Check for a matching or 0 cache entry */
  3421. append_transaction(dr, p, ttl, avoid);
  3422. } else {
  3423. ast_debug(1, "Avoiding '%s' in transaction\n", ast_eid_to_str(eid_str, sizeof(eid_str), avoid[x]));
  3424. }
  3425. }
  3426. }
  3427. *foundcache |= res;
  3428. } else if (!*skipped || (p->order < *skipped))
  3429. *skipped = p->order;
  3430. }
  3431. }
  3432. AST_LIST_UNLOCK(&peers);
  3433. }
  3434. static int register_request(struct dundi_request *dr, struct dundi_request **pending)
  3435. {
  3436. struct dundi_request *cur;
  3437. int res=0;
  3438. char eid_str[20];
  3439. AST_LIST_LOCK(&peers);
  3440. AST_LIST_TRAVERSE(&requests, cur, list) {
  3441. ast_debug(1, "Checking '%s@%s' vs '%s@%s'\n", cur->dcontext, cur->number,
  3442. dr->dcontext, dr->number);
  3443. if (!strcasecmp(cur->dcontext, dr->dcontext) &&
  3444. !strcasecmp(cur->number, dr->number) &&
  3445. (!ast_eid_cmp(&cur->root_eid, &dr->root_eid) || (cur->crc32 == dr->crc32))) {
  3446. ast_debug(1, "Found existing query for '%s@%s' for '%s' crc '%08x'\n",
  3447. cur->dcontext, cur->number, ast_eid_to_str(eid_str, sizeof(eid_str), &cur->root_eid), cur->crc32);
  3448. *pending = cur;
  3449. res = 1;
  3450. break;
  3451. }
  3452. }
  3453. if (!res) {
  3454. ast_debug(1, "Registering request for '%s@%s' on behalf of '%s' crc '%08x'\n",
  3455. dr->number, dr->dcontext, ast_eid_to_str(eid_str, sizeof(eid_str), &dr->root_eid), dr->crc32);
  3456. /* Go ahead and link us in since nobody else is searching for this */
  3457. AST_LIST_INSERT_HEAD(&requests, dr, list);
  3458. *pending = NULL;
  3459. }
  3460. AST_LIST_UNLOCK(&peers);
  3461. return res;
  3462. }
  3463. static void unregister_request(struct dundi_request *dr)
  3464. {
  3465. AST_LIST_LOCK(&peers);
  3466. AST_LIST_REMOVE(&requests, dr, list);
  3467. AST_LIST_UNLOCK(&peers);
  3468. }
  3469. static int check_request(struct dundi_request *dr)
  3470. {
  3471. struct dundi_request *cur;
  3472. AST_LIST_LOCK(&peers);
  3473. AST_LIST_TRAVERSE(&requests, cur, list) {
  3474. if (cur == dr)
  3475. break;
  3476. }
  3477. AST_LIST_UNLOCK(&peers);
  3478. return cur ? 1 : 0;
  3479. }
  3480. static unsigned long avoid_crc32(dundi_eid *avoid[])
  3481. {
  3482. /* Idea is that we're calculating a checksum which is independent of
  3483. the order that the EID's are listed in */
  3484. uint32_t acrc32 = 0;
  3485. int x;
  3486. for (x=0;avoid[x];x++) {
  3487. /* Order doesn't matter */
  3488. if (avoid[x+1]) {
  3489. acrc32 ^= crc32(0L, (unsigned char *)avoid[x], sizeof(dundi_eid));
  3490. }
  3491. }
  3492. return acrc32;
  3493. }
  3494. static int dundi_lookup_internal(struct dundi_result *result, int maxret, struct ast_channel *chan, const char *dcontext, const char *number, int ttl, int blockempty, struct dundi_hint_metadata *hmd, int *expiration, int cbypass, int modeselect, dundi_eid *skip, dundi_eid *avoid[], int direct[])
  3495. {
  3496. int res;
  3497. struct dundi_request dr, *pending;
  3498. dundi_eid *rooteid=NULL;
  3499. int x;
  3500. int ttlms;
  3501. int ms;
  3502. int foundcache;
  3503. int skipped=0;
  3504. int order=0;
  3505. char eid_str[20];
  3506. struct timeval start;
  3507. /* Don't do anthing for a hungup channel */
  3508. if (chan && ast_check_hangup(chan))
  3509. return 0;
  3510. ttlms = DUNDI_FLUFF_TIME + ttl * DUNDI_TTL_TIME;
  3511. for (x=0;avoid[x];x++)
  3512. rooteid = avoid[x];
  3513. /* Now perform real check */
  3514. memset(&dr, 0, sizeof(dr));
  3515. if (pipe(dr.pfds)) {
  3516. ast_log(LOG_WARNING, "pipe failed: %s\n" , strerror(errno));
  3517. return -1;
  3518. }
  3519. dr.dr = result;
  3520. dr.hmd = hmd;
  3521. dr.maxcount = maxret;
  3522. dr.expiration = *expiration;
  3523. dr.cbypass = cbypass;
  3524. dr.crc32 = avoid_crc32(avoid);
  3525. ast_copy_string(dr.dcontext, dcontext ? dcontext : "e164", sizeof(dr.dcontext));
  3526. ast_copy_string(dr.number, number, sizeof(dr.number));
  3527. if (rooteid)
  3528. dr.root_eid = *rooteid;
  3529. res = register_request(&dr, &pending);
  3530. if (res) {
  3531. /* Already a request */
  3532. if (rooteid && !ast_eid_cmp(&dr.root_eid, &pending->root_eid)) {
  3533. /* This is on behalf of someone else. Go ahead and close this out since
  3534. they'll get their answer anyway. */
  3535. ast_debug(1, "Oooh, duplicate request for '%s@%s' for '%s'\n",
  3536. dr.number,dr.dcontext,ast_eid_to_str(eid_str, sizeof(eid_str), &dr.root_eid));
  3537. close(dr.pfds[0]);
  3538. close(dr.pfds[1]);
  3539. return -2;
  3540. } else {
  3541. /* Wait for the cache to populate */
  3542. ast_debug(1, "Waiting for similar request for '%s@%s' for '%s'\n",
  3543. dr.number,dr.dcontext,ast_eid_to_str(eid_str, sizeof(eid_str), &pending->root_eid));
  3544. start = ast_tvnow();
  3545. while(check_request(pending) && (ast_tvdiff_ms(ast_tvnow(), start) < ttlms) && (!chan || !ast_check_hangup(chan))) {
  3546. /* XXX Would be nice to have a way to poll/select here XXX */
  3547. /* XXX this is a busy wait loop!!! */
  3548. usleep(1);
  3549. }
  3550. /* Continue on as normal, our cache should kick in */
  3551. }
  3552. }
  3553. /* Create transactions */
  3554. do {
  3555. order = skipped;
  3556. skipped = 0;
  3557. foundcache = 0;
  3558. build_transactions(&dr, ttl, order, &foundcache, &skipped, blockempty, cbypass, modeselect, skip, avoid, direct);
  3559. } while (skipped && !foundcache && AST_LIST_EMPTY(&dr.trans));
  3560. /* If no TTL, abort and return 0 now after setting TTL expired hint. Couldn't
  3561. do this earlier because we didn't know if we were going to have transactions
  3562. or not. */
  3563. if (!ttl) {
  3564. ast_set_flag_nonstd(hmd, DUNDI_HINT_TTL_EXPIRED);
  3565. abort_request(&dr);
  3566. unregister_request(&dr);
  3567. close(dr.pfds[0]);
  3568. close(dr.pfds[1]);
  3569. return 0;
  3570. }
  3571. /* Optimize transactions */
  3572. optimize_transactions(&dr, order);
  3573. /* Actually perform transactions */
  3574. discover_transactions(&dr);
  3575. /* Wait for transaction to come back */
  3576. start = ast_tvnow();
  3577. while (!AST_LIST_EMPTY(&dr.trans) && (ast_tvdiff_ms(ast_tvnow(), start) < ttlms) && (!chan || !ast_check_hangup(chan))) {
  3578. ms = 100;
  3579. ast_waitfor_n_fd(dr.pfds, 1, &ms, NULL);
  3580. }
  3581. if (chan && ast_check_hangup(chan))
  3582. ast_debug(1, "Hrm, '%s' hungup before their query for %s@%s finished\n", ast_channel_name(chan), dr.number, dr.dcontext);
  3583. cancel_request(&dr);
  3584. unregister_request(&dr);
  3585. res = dr.respcount;
  3586. *expiration = dr.expiration;
  3587. close(dr.pfds[0]);
  3588. close(dr.pfds[1]);
  3589. return res;
  3590. }
  3591. int dundi_lookup(struct dundi_result *result, int maxret, struct ast_channel *chan, const char *dcontext, const char *number, int cbypass)
  3592. {
  3593. struct dundi_hint_metadata hmd;
  3594. dundi_eid *avoid[1] = { NULL, };
  3595. int direct[1] = { 0, };
  3596. int expiration = dundi_cache_time;
  3597. memset(&hmd, 0, sizeof(hmd));
  3598. hmd.flags = DUNDI_HINT_DONT_ASK | DUNDI_HINT_UNAFFECTED;
  3599. return dundi_lookup_internal(result, maxret, chan, dcontext, number, dundi_ttl, 0, &hmd, &expiration, cbypass, 0, NULL, avoid, direct);
  3600. }
  3601. static void reschedule_precache(const char *number, const char *context, int expiration)
  3602. {
  3603. int len;
  3604. struct dundi_precache_queue *qe, *prev;
  3605. AST_LIST_LOCK(&pcq);
  3606. AST_LIST_TRAVERSE_SAFE_BEGIN(&pcq, qe, list) {
  3607. if (!strcmp(number, qe->number) && !strcasecmp(context, qe->context)) {
  3608. AST_LIST_REMOVE_CURRENT(list);
  3609. break;
  3610. }
  3611. }
  3612. AST_LIST_TRAVERSE_SAFE_END;
  3613. if (!qe) {
  3614. len = sizeof(*qe);
  3615. len += strlen(number) + 1;
  3616. len += strlen(context) + 1;
  3617. if (!(qe = ast_calloc(1, len))) {
  3618. AST_LIST_UNLOCK(&pcq);
  3619. return;
  3620. }
  3621. strcpy(qe->number, number);
  3622. qe->context = qe->number + strlen(number) + 1;
  3623. strcpy(qe->context, context);
  3624. }
  3625. time(&qe->expiration);
  3626. qe->expiration += expiration;
  3627. if ((prev = AST_LIST_FIRST(&pcq))) {
  3628. while (AST_LIST_NEXT(prev, list) && ((AST_LIST_NEXT(prev, list))->expiration <= qe->expiration))
  3629. prev = AST_LIST_NEXT(prev, list);
  3630. AST_LIST_INSERT_AFTER(&pcq, prev, qe, list);
  3631. } else
  3632. AST_LIST_INSERT_HEAD(&pcq, qe, list);
  3633. AST_LIST_UNLOCK(&pcq);
  3634. }
  3635. static void dundi_precache_full(void)
  3636. {
  3637. struct dundi_mapping *cur;
  3638. struct ast_context *con;
  3639. struct ast_exten *e;
  3640. AST_LIST_TRAVERSE(&mappings, cur, list) {
  3641. ast_log(LOG_NOTICE, "Should precache context '%s'\n", cur->dcontext);
  3642. ast_rdlock_contexts();
  3643. con = NULL;
  3644. while ((con = ast_walk_contexts(con))) {
  3645. if (strcasecmp(cur->lcontext, ast_get_context_name(con)))
  3646. continue;
  3647. /* Found the match, now queue them all up */
  3648. ast_rdlock_context(con);
  3649. e = NULL;
  3650. while ((e = ast_walk_context_extensions(con, e)))
  3651. reschedule_precache(ast_get_extension_name(e), cur->dcontext, 0);
  3652. ast_unlock_context(con);
  3653. }
  3654. ast_unlock_contexts();
  3655. }
  3656. }
  3657. static int dundi_precache_internal(const char *context, const char *number, int ttl, dundi_eid *avoids[])
  3658. {
  3659. struct dundi_request dr;
  3660. struct dundi_hint_metadata hmd;
  3661. struct dundi_result dr2[MAX_RESULTS];
  3662. struct timeval start;
  3663. struct dundi_mapping *maps = NULL, *cur;
  3664. int nummaps = 0;
  3665. int foundanswers;
  3666. int foundcache, skipped, ttlms, ms;
  3667. if (!context)
  3668. context = "e164";
  3669. ast_debug(1, "Precache internal (%s@%s)!\n", number, context);
  3670. AST_LIST_LOCK(&peers);
  3671. AST_LIST_TRAVERSE(&mappings, cur, list) {
  3672. if (!strcasecmp(cur->dcontext, context))
  3673. nummaps++;
  3674. }
  3675. if (nummaps) {
  3676. maps = ast_alloca(nummaps * sizeof(*maps));
  3677. nummaps = 0;
  3678. AST_LIST_TRAVERSE(&mappings, cur, list) {
  3679. if (!strcasecmp(cur->dcontext, context))
  3680. maps[nummaps++] = *cur;
  3681. }
  3682. }
  3683. AST_LIST_UNLOCK(&peers);
  3684. if (!nummaps) {
  3685. return -1;
  3686. }
  3687. ttlms = DUNDI_FLUFF_TIME + ttl * DUNDI_TTL_TIME;
  3688. memset(&dr2, 0, sizeof(dr2));
  3689. memset(&dr, 0, sizeof(dr));
  3690. memset(&hmd, 0, sizeof(hmd));
  3691. dr.dr = dr2;
  3692. ast_copy_string(dr.number, number, sizeof(dr.number));
  3693. ast_copy_string(dr.dcontext, context ? context : "e164", sizeof(dr.dcontext));
  3694. dr.maxcount = MAX_RESULTS;
  3695. dr.expiration = dundi_cache_time;
  3696. dr.hmd = &hmd;
  3697. dr.pfds[0] = dr.pfds[1] = -1;
  3698. if (pipe(dr.pfds) < 0) {
  3699. ast_log(LOG_WARNING, "pipe() failed: %s\n", strerror(errno));
  3700. return -1;
  3701. }
  3702. build_transactions(&dr, ttl, 0, &foundcache, &skipped, 0, 1, 1, NULL, avoids, NULL);
  3703. optimize_transactions(&dr, 0);
  3704. foundanswers = 0;
  3705. precache_transactions(&dr, maps, nummaps, &dr.expiration, &foundanswers);
  3706. if (foundanswers) {
  3707. if (dr.expiration > 0)
  3708. reschedule_precache(dr.number, dr.dcontext, dr.expiration);
  3709. else
  3710. ast_log(LOG_NOTICE, "Weird, expiration = %d, but need to precache for %s@%s?!\n", dr.expiration, dr.number, dr.dcontext);
  3711. }
  3712. start = ast_tvnow();
  3713. while (!AST_LIST_EMPTY(&dr.trans) && (ast_tvdiff_ms(ast_tvnow(), start) < ttlms)) {
  3714. if (dr.pfds[0] > -1) {
  3715. ms = 100;
  3716. ast_waitfor_n_fd(dr.pfds, 1, &ms, NULL);
  3717. } else
  3718. usleep(1);
  3719. }
  3720. cancel_request(&dr);
  3721. if (dr.pfds[0] > -1) {
  3722. close(dr.pfds[0]);
  3723. close(dr.pfds[1]);
  3724. }
  3725. return 0;
  3726. }
  3727. int dundi_precache(const char *context, const char *number)
  3728. {
  3729. dundi_eid *avoid[1] = { NULL, };
  3730. return dundi_precache_internal(context, number, dundi_ttl, avoid);
  3731. }
  3732. static int dundi_query_eid_internal(struct dundi_entity_info *dei, const char *dcontext, dundi_eid *eid, struct dundi_hint_metadata *hmd, int ttl, int blockempty, dundi_eid *avoid[])
  3733. {
  3734. int res;
  3735. struct dundi_request dr;
  3736. dundi_eid *rooteid=NULL;
  3737. int x;
  3738. int ttlms;
  3739. int skipped=0;
  3740. int foundcache=0;
  3741. struct timeval start;
  3742. ttlms = DUNDI_FLUFF_TIME + ttl * DUNDI_TTL_TIME;
  3743. for (x=0;avoid[x];x++)
  3744. rooteid = avoid[x];
  3745. /* Now perform real check */
  3746. memset(&dr, 0, sizeof(dr));
  3747. dr.hmd = hmd;
  3748. dr.dei = dei;
  3749. dr.pfds[0] = dr.pfds[1] = -1;
  3750. ast_copy_string(dr.dcontext, dcontext ? dcontext : "e164", sizeof(dr.dcontext));
  3751. memcpy(&dr.query_eid, eid, sizeof(dr.query_eid));
  3752. if (rooteid)
  3753. dr.root_eid = *rooteid;
  3754. /* Create transactions */
  3755. build_transactions(&dr, ttl, 9999, &foundcache, &skipped, blockempty, 0, 0, NULL, avoid, NULL);
  3756. /* If no TTL, abort and return 0 now after setting TTL expired hint. Couldn't
  3757. do this earlier because we didn't know if we were going to have transactions
  3758. or not. */
  3759. if (!ttl) {
  3760. ast_set_flag_nonstd(hmd, DUNDI_HINT_TTL_EXPIRED);
  3761. return 0;
  3762. }
  3763. /* Optimize transactions */
  3764. optimize_transactions(&dr, 9999);
  3765. /* Actually perform transactions */
  3766. query_transactions(&dr);
  3767. /* Wait for transaction to come back */
  3768. start = ast_tvnow();
  3769. while (!AST_LIST_EMPTY(&dr.trans) && (ast_tvdiff_ms(ast_tvnow(), start) < ttlms))
  3770. usleep(1);
  3771. res = dr.respcount;
  3772. return res;
  3773. }
  3774. int dundi_query_eid(struct dundi_entity_info *dei, const char *dcontext, dundi_eid eid)
  3775. {
  3776. dundi_eid *avoid[1] = { NULL, };
  3777. struct dundi_hint_metadata hmd;
  3778. memset(&hmd, 0, sizeof(hmd));
  3779. return dundi_query_eid_internal(dei, dcontext, &eid, &hmd, dundi_ttl, 0, avoid);
  3780. }
  3781. enum {
  3782. OPT_BYPASS_CACHE = (1 << 0),
  3783. };
  3784. AST_APP_OPTIONS(dundi_query_opts, BEGIN_OPTIONS
  3785. AST_APP_OPTION('b', OPT_BYPASS_CACHE),
  3786. END_OPTIONS );
  3787. static int dundifunc_read(struct ast_channel *chan, const char *cmd, char *num, char *buf, size_t len)
  3788. {
  3789. int results;
  3790. int x;
  3791. struct dundi_result dr[MAX_RESULTS];
  3792. AST_DECLARE_APP_ARGS(args,
  3793. AST_APP_ARG(number);
  3794. AST_APP_ARG(context);
  3795. AST_APP_ARG(options);
  3796. );
  3797. char *parse;
  3798. struct ast_flags opts = { 0, };
  3799. buf[0] = '\0';
  3800. if (ast_strlen_zero(num)) {
  3801. ast_log(LOG_WARNING, "DUNDILOOKUP requires an argument (number)\n");
  3802. return -1;
  3803. }
  3804. parse = ast_strdupa(num);
  3805. AST_STANDARD_APP_ARGS(args, parse);
  3806. if (!ast_strlen_zero(args.options)) {
  3807. ast_app_parse_options(dundi_query_opts, &opts, NULL, args.options);
  3808. }
  3809. if (ast_strlen_zero(args.context)) {
  3810. args.context = "e164";
  3811. }
  3812. results = dundi_lookup(dr, MAX_RESULTS, NULL, args.context, args.number, ast_test_flag(&opts, OPT_BYPASS_CACHE));
  3813. if (results > 0) {
  3814. sort_results(dr, results);
  3815. for (x = 0; x < results; x++) {
  3816. if (ast_test_flag(dr + x, DUNDI_FLAG_EXISTS)) {
  3817. snprintf(buf, len, "%s/%s", dr[x].tech, dr[x].dest);
  3818. break;
  3819. }
  3820. }
  3821. }
  3822. return 0;
  3823. }
  3824. /*! DUNDILOOKUP
  3825. * \ingroup functions
  3826. */
  3827. static struct ast_custom_function dundi_function = {
  3828. .name = "DUNDILOOKUP",
  3829. .read = dundifunc_read,
  3830. };
  3831. static unsigned int dundi_result_id;
  3832. struct dundi_result_datastore {
  3833. struct dundi_result results[MAX_RESULTS];
  3834. unsigned int num_results;
  3835. unsigned int id;
  3836. };
  3837. static void drds_destroy(struct dundi_result_datastore *drds)
  3838. {
  3839. ast_free(drds);
  3840. }
  3841. static void drds_destroy_cb(void *data)
  3842. {
  3843. struct dundi_result_datastore *drds = data;
  3844. drds_destroy(drds);
  3845. }
  3846. static const struct ast_datastore_info dundi_result_datastore_info = {
  3847. .type = "DUNDIQUERY",
  3848. .destroy = drds_destroy_cb,
  3849. };
  3850. static int dundi_query_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  3851. {
  3852. AST_DECLARE_APP_ARGS(args,
  3853. AST_APP_ARG(number);
  3854. AST_APP_ARG(context);
  3855. AST_APP_ARG(options);
  3856. );
  3857. struct ast_flags opts = { 0, };
  3858. char *parse;
  3859. struct dundi_result_datastore *drds;
  3860. struct ast_datastore *datastore;
  3861. if (ast_strlen_zero(data)) {
  3862. ast_log(LOG_WARNING, "DUNDIQUERY requires an argument (number)\n");
  3863. return -1;
  3864. }
  3865. if (!chan) {
  3866. ast_log(LOG_ERROR, "DUNDIQUERY can not be used without a channel!\n");
  3867. return -1;
  3868. }
  3869. parse = ast_strdupa(data);
  3870. AST_STANDARD_APP_ARGS(args, parse);
  3871. if (!ast_strlen_zero(args.options))
  3872. ast_app_parse_options(dundi_query_opts, &opts, NULL, args.options);
  3873. if (ast_strlen_zero(args.context))
  3874. args.context = "e164";
  3875. if (!(drds = ast_calloc(1, sizeof(*drds)))) {
  3876. return -1;
  3877. }
  3878. drds->id = ast_atomic_fetchadd_int((int *) &dundi_result_id, 1);
  3879. snprintf(buf, len, "%u", drds->id);
  3880. if (!(datastore = ast_datastore_alloc(&dundi_result_datastore_info, buf))) {
  3881. drds_destroy(drds);
  3882. return -1;
  3883. }
  3884. datastore->data = drds;
  3885. drds->num_results = dundi_lookup(drds->results, ARRAY_LEN(drds->results), NULL, args.context,
  3886. args.number, ast_test_flag(&opts, OPT_BYPASS_CACHE));
  3887. if (drds->num_results > 0)
  3888. sort_results(drds->results, drds->num_results);
  3889. ast_channel_lock(chan);
  3890. ast_channel_datastore_add(chan, datastore);
  3891. ast_channel_unlock(chan);
  3892. return 0;
  3893. }
  3894. static struct ast_custom_function dundi_query_function = {
  3895. .name = "DUNDIQUERY",
  3896. .read = dundi_query_read,
  3897. };
  3898. static int dundi_result_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  3899. {
  3900. AST_DECLARE_APP_ARGS(args,
  3901. AST_APP_ARG(id);
  3902. AST_APP_ARG(resultnum);
  3903. );
  3904. char *parse;
  3905. unsigned int num;
  3906. struct dundi_result_datastore *drds;
  3907. struct ast_datastore *datastore;
  3908. int res = -1;
  3909. if (ast_strlen_zero(data)) {
  3910. ast_log(LOG_WARNING, "DUNDIRESULT requires an argument (id and resultnum)\n");
  3911. goto finish;
  3912. }
  3913. if (!chan) {
  3914. ast_log(LOG_ERROR, "DUNDRESULT can not be used without a channel!\n");
  3915. goto finish;
  3916. }
  3917. parse = ast_strdupa(data);
  3918. AST_STANDARD_APP_ARGS(args, parse);
  3919. if (ast_strlen_zero(args.id)) {
  3920. ast_log(LOG_ERROR, "A result ID must be provided to DUNDIRESULT\n");
  3921. goto finish;
  3922. }
  3923. if (ast_strlen_zero(args.resultnum)) {
  3924. ast_log(LOG_ERROR, "A result number must be given to DUNDIRESULT!\n");
  3925. goto finish;
  3926. }
  3927. ast_channel_lock(chan);
  3928. datastore = ast_channel_datastore_find(chan, &dundi_result_datastore_info, args.id);
  3929. ast_channel_unlock(chan);
  3930. if (!datastore) {
  3931. ast_log(LOG_WARNING, "No DUNDi results found for query ID '%s'\n", args.id);
  3932. goto finish;
  3933. }
  3934. drds = datastore->data;
  3935. if (!strcasecmp(args.resultnum, "getnum")) {
  3936. snprintf(buf, len, "%u", drds->num_results);
  3937. res = 0;
  3938. goto finish;
  3939. }
  3940. if (sscanf(args.resultnum, "%30u", &num) != 1) {
  3941. ast_log(LOG_ERROR, "Invalid value '%s' for resultnum to DUNDIRESULT!\n",
  3942. args.resultnum);
  3943. goto finish;
  3944. }
  3945. if (num && num <= drds->num_results) {
  3946. snprintf(buf, len, "%s/%s", drds->results[num - 1].tech, drds->results[num - 1].dest);
  3947. res = 0;
  3948. } else
  3949. ast_log(LOG_WARNING, "Result number %u is not valid for DUNDi query results for ID %s!\n", num, args.id);
  3950. finish:
  3951. return res;
  3952. }
  3953. static struct ast_custom_function dundi_result_function = {
  3954. .name = "DUNDIRESULT",
  3955. .read = dundi_result_read,
  3956. };
  3957. static void mark_peers(void)
  3958. {
  3959. struct dundi_peer *peer;
  3960. AST_LIST_LOCK(&peers);
  3961. AST_LIST_TRAVERSE(&peers, peer, list) {
  3962. peer->dead = 1;
  3963. }
  3964. AST_LIST_UNLOCK(&peers);
  3965. }
  3966. static void mark_mappings(void)
  3967. {
  3968. struct dundi_mapping *map;
  3969. AST_LIST_LOCK(&peers);
  3970. AST_LIST_TRAVERSE(&mappings, map, list) {
  3971. map->dead = 1;
  3972. }
  3973. AST_LIST_UNLOCK(&peers);
  3974. }
  3975. static void destroy_permissions(struct permissionlist *permlist)
  3976. {
  3977. struct permission *perm;
  3978. while ((perm = AST_LIST_REMOVE_HEAD(permlist, list)))
  3979. ast_free(perm);
  3980. }
  3981. static void destroy_peer(struct dundi_peer *peer)
  3982. {
  3983. int idx;
  3984. AST_SCHED_DEL(sched, peer->registerexpire);
  3985. AST_SCHED_DEL(sched, peer->registerid);
  3986. if (peer->regtrans) {
  3987. destroy_trans(peer->regtrans, 0);
  3988. }
  3989. AST_SCHED_DEL(sched, peer->qualifyid);
  3990. if (peer->qualtrans) {
  3991. destroy_trans(peer->qualtrans, 0);
  3992. }
  3993. destroy_permissions(&peer->permit);
  3994. destroy_permissions(&peer->include);
  3995. /* Release lookup history */
  3996. for (idx = 0; idx < ARRAY_LEN(peer->lookups); ++idx) {
  3997. ast_free(peer->lookups[idx]);
  3998. }
  3999. ast_free(peer);
  4000. }
  4001. static void destroy_map(struct dundi_mapping *map)
  4002. {
  4003. ast_free(map->weightstr);
  4004. ast_free(map);
  4005. }
  4006. static void prune_peers(void)
  4007. {
  4008. struct dundi_peer *peer;
  4009. AST_LIST_LOCK(&peers);
  4010. AST_LIST_TRAVERSE_SAFE_BEGIN(&peers, peer, list) {
  4011. if (peer->dead) {
  4012. AST_LIST_REMOVE_CURRENT(list);
  4013. destroy_peer(peer);
  4014. }
  4015. }
  4016. AST_LIST_TRAVERSE_SAFE_END;
  4017. AST_LIST_UNLOCK(&peers);
  4018. }
  4019. static void prune_mappings(void)
  4020. {
  4021. struct dundi_mapping *map;
  4022. AST_LIST_LOCK(&peers);
  4023. AST_LIST_TRAVERSE_SAFE_BEGIN(&mappings, map, list) {
  4024. if (map->dead) {
  4025. AST_LIST_REMOVE_CURRENT(list);
  4026. destroy_map(map);
  4027. }
  4028. }
  4029. AST_LIST_TRAVERSE_SAFE_END;
  4030. AST_LIST_UNLOCK(&peers);
  4031. }
  4032. static void append_permission(struct permissionlist *permlist, const char *s, int allow)
  4033. {
  4034. struct permission *perm;
  4035. if (!(perm = ast_calloc(1, sizeof(*perm) + strlen(s) + 1)))
  4036. return;
  4037. strcpy(perm->name, s);
  4038. perm->allow = allow;
  4039. AST_LIST_INSERT_TAIL(permlist, perm, list);
  4040. }
  4041. #define MAX_OPTS 128
  4042. static void build_mapping(const char *name, const char *value)
  4043. {
  4044. char *t, *fields[MAX_OPTS];
  4045. struct dundi_mapping *map;
  4046. int x;
  4047. int y;
  4048. t = ast_strdupa(value);
  4049. AST_LIST_TRAVERSE(&mappings, map, list) {
  4050. /* Find a double match */
  4051. if (!strcasecmp(map->dcontext, name) &&
  4052. (!strncasecmp(map->lcontext, value, strlen(map->lcontext)) &&
  4053. (!value[strlen(map->lcontext)] ||
  4054. (value[strlen(map->lcontext)] == ','))))
  4055. break;
  4056. }
  4057. if (!map) {
  4058. if (!(map = ast_calloc(1, sizeof(*map))))
  4059. return;
  4060. AST_LIST_INSERT_HEAD(&mappings, map, list);
  4061. map->dead = 1;
  4062. }
  4063. map->options = 0;
  4064. memset(fields, 0, sizeof(fields));
  4065. x = 0;
  4066. while (t && x < MAX_OPTS) {
  4067. fields[x++] = t;
  4068. t = strchr(t, ',');
  4069. if (t) {
  4070. *t = '\0';
  4071. t++;
  4072. }
  4073. } /* Russell was here, arrrr! */
  4074. if ((x == 1) && ast_strlen_zero(fields[0])) {
  4075. /* Placeholder mapping */
  4076. ast_copy_string(map->dcontext, name, sizeof(map->dcontext));
  4077. map->dead = 0;
  4078. } else if (x >= 4) {
  4079. ast_copy_string(map->dcontext, name, sizeof(map->dcontext));
  4080. ast_copy_string(map->lcontext, fields[0], sizeof(map->lcontext));
  4081. if ((sscanf(fields[1], "%30d", &map->_weight) == 1) && (map->_weight >= 0) && (map->_weight <= MAX_WEIGHT)) {
  4082. ast_copy_string(map->dest, fields[3], sizeof(map->dest));
  4083. if ((map->tech = str2tech(fields[2])))
  4084. map->dead = 0;
  4085. } else if (!strncmp(fields[1], "${", 2) && fields[1][strlen(fields[1]) - 1] == '}') {
  4086. map->weightstr = ast_strdup(fields[1]);
  4087. ast_copy_string(map->dest, fields[3], sizeof(map->dest));
  4088. if ((map->tech = str2tech(fields[2])))
  4089. map->dead = 0;
  4090. } else {
  4091. ast_log(LOG_WARNING, "Invalid weight '%s' specified, deleting entry '%s/%s'\n", fields[1], map->dcontext, map->lcontext);
  4092. }
  4093. for (y = 4;y < x; y++) {
  4094. if (!strcasecmp(fields[y], "nounsolicited"))
  4095. map->options |= DUNDI_FLAG_NOUNSOLICITED;
  4096. else if (!strcasecmp(fields[y], "nocomunsolicit"))
  4097. map->options |= DUNDI_FLAG_NOCOMUNSOLICIT;
  4098. else if (!strcasecmp(fields[y], "residential"))
  4099. map->options |= DUNDI_FLAG_RESIDENTIAL;
  4100. else if (!strcasecmp(fields[y], "commercial"))
  4101. map->options |= DUNDI_FLAG_COMMERCIAL;
  4102. else if (!strcasecmp(fields[y], "mobile"))
  4103. map->options |= DUNDI_FLAG_MOBILE;
  4104. else if (!strcasecmp(fields[y], "nopartial"))
  4105. map->options |= DUNDI_FLAG_INTERNAL_NOPARTIAL;
  4106. else
  4107. ast_log(LOG_WARNING, "Don't know anything about option '%s'\n", fields[y]);
  4108. }
  4109. } else
  4110. ast_log(LOG_WARNING, "Expected at least %d arguments in map, but got only %d\n", 4, x);
  4111. }
  4112. /* \note Called with the peers list already locked */
  4113. static int do_register(const void *data)
  4114. {
  4115. struct dundi_ie_data ied;
  4116. struct dundi_peer *peer = (struct dundi_peer *)data;
  4117. char eid_str[20];
  4118. char eid_str2[20];
  4119. ast_debug(1, "Register us as '%s' to '%s'\n", ast_eid_to_str(eid_str, sizeof(eid_str), &peer->us_eid), ast_eid_to_str(eid_str2, sizeof(eid_str2), &peer->eid));
  4120. peer->registerid = ast_sched_add(sched, default_expiration * 1000, do_register, data);
  4121. /* Destroy old transaction if there is one */
  4122. if (peer->regtrans)
  4123. destroy_trans(peer->regtrans, 0);
  4124. peer->regtrans = create_transaction(peer);
  4125. if (peer->regtrans) {
  4126. ast_set_flag(peer->regtrans, FLAG_ISREG);
  4127. memset(&ied, 0, sizeof(ied));
  4128. dundi_ie_append_short(&ied, DUNDI_IE_VERSION, DUNDI_DEFAULT_VERSION);
  4129. dundi_ie_append_eid(&ied, DUNDI_IE_EID, &peer->regtrans->us_eid);
  4130. dundi_ie_append_short(&ied, DUNDI_IE_EXPIRATION, default_expiration);
  4131. dundi_send(peer->regtrans, DUNDI_COMMAND_REGREQ, 0, 0, &ied);
  4132. } else
  4133. ast_log(LOG_NOTICE, "Unable to create new transaction for registering to '%s'!\n", ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid));
  4134. return 0;
  4135. }
  4136. static int do_qualify(const void *data)
  4137. {
  4138. struct dundi_peer *peer = (struct dundi_peer *)data;
  4139. peer->qualifyid = -1;
  4140. qualify_peer(peer, 0);
  4141. return 0;
  4142. }
  4143. static void qualify_peer(struct dundi_peer *peer, int schedonly)
  4144. {
  4145. int when;
  4146. AST_SCHED_DEL(sched, peer->qualifyid);
  4147. if (peer->qualtrans)
  4148. destroy_trans(peer->qualtrans, 0);
  4149. peer->qualtrans = NULL;
  4150. if (peer->maxms > 0) {
  4151. when = 60000;
  4152. if (peer->lastms < 0)
  4153. when = 10000;
  4154. if (schedonly)
  4155. when = 5000;
  4156. peer->qualifyid = ast_sched_add(sched, when, do_qualify, peer);
  4157. if (!schedonly)
  4158. peer->qualtrans = create_transaction(peer);
  4159. if (peer->qualtrans) {
  4160. peer->qualtx = ast_tvnow();
  4161. ast_set_flag(peer->qualtrans, FLAG_ISQUAL);
  4162. dundi_send(peer->qualtrans, DUNDI_COMMAND_NULL, 0, 1, NULL);
  4163. }
  4164. }
  4165. }
  4166. static void populate_addr(struct dundi_peer *peer, dundi_eid *eid)
  4167. {
  4168. char data[256];
  4169. char *c;
  4170. int port, expire;
  4171. char eid_str[20];
  4172. ast_eid_to_str(eid_str, sizeof(eid_str), eid);
  4173. if (!ast_db_get("dundi/dpeers", eid_str, data, sizeof(data))) {
  4174. c = strchr(data, ':');
  4175. if (c) {
  4176. *c = '\0';
  4177. c++;
  4178. if (sscanf(c, "%5d:%30d", &port, &expire) == 2) {
  4179. /* Got it! */
  4180. inet_aton(data, &peer->addr.sin_addr);
  4181. peer->addr.sin_family = AF_INET;
  4182. peer->addr.sin_port = htons(port);
  4183. peer->registerexpire = ast_sched_add(sched, (expire + 10) * 1000, do_register_expire, peer);
  4184. }
  4185. }
  4186. }
  4187. }
  4188. static void build_peer(dundi_eid *eid, struct ast_variable *v, int *globalpcmode)
  4189. {
  4190. struct dundi_peer *peer;
  4191. struct ast_hostent he;
  4192. struct hostent *hp;
  4193. dundi_eid testeid;
  4194. int needregister=0;
  4195. char eid_str[20];
  4196. AST_LIST_LOCK(&peers);
  4197. AST_LIST_TRAVERSE(&peers, peer, list) {
  4198. if (!ast_eid_cmp(&peer->eid, eid)) {
  4199. break;
  4200. }
  4201. }
  4202. if (!peer) {
  4203. /* Add us into the list */
  4204. if (!(peer = ast_calloc(1, sizeof(*peer)))) {
  4205. AST_LIST_UNLOCK(&peers);
  4206. return;
  4207. }
  4208. peer->registerid = -1;
  4209. peer->registerexpire = -1;
  4210. peer->qualifyid = -1;
  4211. peer->addr.sin_family = AF_INET;
  4212. peer->addr.sin_port = htons(DUNDI_PORT);
  4213. populate_addr(peer, eid);
  4214. AST_LIST_INSERT_HEAD(&peers, peer, list);
  4215. }
  4216. peer->dead = 0;
  4217. peer->eid = *eid;
  4218. peer->us_eid = global_eid;
  4219. destroy_permissions(&peer->permit);
  4220. destroy_permissions(&peer->include);
  4221. AST_SCHED_DEL(sched, peer->registerid);
  4222. for (; v; v = v->next) {
  4223. if (!strcasecmp(v->name, "inkey")) {
  4224. ast_copy_string(peer->inkey, v->value, sizeof(peer->inkey));
  4225. } else if (!strcasecmp(v->name, "outkey")) {
  4226. ast_copy_string(peer->outkey, v->value, sizeof(peer->outkey));
  4227. } else if (!strcasecmp(v->name, "port")) {
  4228. peer->addr.sin_port = htons(atoi(v->value));
  4229. } else if (!strcasecmp(v->name, "host")) {
  4230. if (!strcasecmp(v->value, "dynamic")) {
  4231. peer->dynamic = 1;
  4232. } else {
  4233. hp = ast_gethostbyname(v->value, &he);
  4234. if (hp) {
  4235. memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
  4236. peer->dynamic = 0;
  4237. } else {
  4238. ast_log(LOG_WARNING, "Unable to find host '%s' at line %d\n", v->value, v->lineno);
  4239. peer->dead = 1;
  4240. }
  4241. }
  4242. } else if (!strcasecmp(v->name, "ustothem")) {
  4243. if (!ast_str_to_eid(&testeid, v->value))
  4244. peer->us_eid = testeid;
  4245. else
  4246. ast_log(LOG_WARNING, "'%s' is not a valid DUNDi Entity Identifier at line %d\n", v->value, v->lineno);
  4247. } else if (!strcasecmp(v->name, "include")) {
  4248. append_permission(&peer->include, v->value, 1);
  4249. } else if (!strcasecmp(v->name, "permit")) {
  4250. append_permission(&peer->permit, v->value, 1);
  4251. } else if (!strcasecmp(v->name, "noinclude")) {
  4252. append_permission(&peer->include, v->value, 0);
  4253. } else if (!strcasecmp(v->name, "deny")) {
  4254. append_permission(&peer->permit, v->value, 0);
  4255. } else if (!strcasecmp(v->name, "register")) {
  4256. needregister = ast_true(v->value);
  4257. } else if (!strcasecmp(v->name, "order")) {
  4258. if (!strcasecmp(v->value, "primary"))
  4259. peer->order = 0;
  4260. else if (!strcasecmp(v->value, "secondary"))
  4261. peer->order = 1;
  4262. else if (!strcasecmp(v->value, "tertiary"))
  4263. peer->order = 2;
  4264. else if (!strcasecmp(v->value, "quartiary"))
  4265. peer->order = 3;
  4266. else {
  4267. ast_log(LOG_WARNING, "'%s' is not a valid order, should be primary, secondary, tertiary or quartiary at line %d\n", v->value, v->lineno);
  4268. }
  4269. } else if (!strcasecmp(v->name, "qualify")) {
  4270. if (!strcasecmp(v->value, "no")) {
  4271. peer->maxms = 0;
  4272. } else if (!strcasecmp(v->value, "yes")) {
  4273. peer->maxms = DEFAULT_MAXMS;
  4274. } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
  4275. ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of dundi.conf\n",
  4276. ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid), v->lineno);
  4277. peer->maxms = 0;
  4278. }
  4279. } else if (!strcasecmp(v->name, "model")) {
  4280. if (!strcasecmp(v->value, "inbound"))
  4281. peer->model = DUNDI_MODEL_INBOUND;
  4282. else if (!strcasecmp(v->value, "outbound"))
  4283. peer->model = DUNDI_MODEL_OUTBOUND;
  4284. else if (!strcasecmp(v->value, "symmetric"))
  4285. peer->model = DUNDI_MODEL_SYMMETRIC;
  4286. else if (!strcasecmp(v->value, "none"))
  4287. peer->model = 0;
  4288. else {
  4289. ast_log(LOG_WARNING, "Unknown model '%s', should be 'none', 'outbound', 'inbound', or 'symmetric' at line %d\n",
  4290. v->value, v->lineno);
  4291. }
  4292. } else if (!strcasecmp(v->name, "precache")) {
  4293. if (!strcasecmp(v->value, "inbound"))
  4294. peer->pcmodel = DUNDI_MODEL_INBOUND;
  4295. else if (!strcasecmp(v->value, "outbound"))
  4296. peer->pcmodel = DUNDI_MODEL_OUTBOUND;
  4297. else if (!strcasecmp(v->value, "symmetric"))
  4298. peer->pcmodel = DUNDI_MODEL_SYMMETRIC;
  4299. else if (!strcasecmp(v->value, "none"))
  4300. peer->pcmodel = 0;
  4301. else {
  4302. ast_log(LOG_WARNING, "Unknown pcmodel '%s', should be 'none', 'outbound', 'inbound', or 'symmetric' at line %d\n",
  4303. v->value, v->lineno);
  4304. }
  4305. }
  4306. }
  4307. (*globalpcmode) |= peer->pcmodel;
  4308. if (!peer->model && !peer->pcmodel) {
  4309. ast_log(LOG_WARNING, "Peer '%s' lacks a model or pcmodel, discarding!\n",
  4310. ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid));
  4311. peer->dead = 1;
  4312. } else if ((peer->model & DUNDI_MODEL_INBOUND) && (peer->pcmodel & DUNDI_MODEL_OUTBOUND)) {
  4313. ast_log(LOG_WARNING, "Peer '%s' may not be both inbound/symmetric model and outbound/symmetric precache model, discarding!\n",
  4314. ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid));
  4315. peer->dead = 1;
  4316. } else if ((peer->model & DUNDI_MODEL_OUTBOUND) && (peer->pcmodel & DUNDI_MODEL_INBOUND)) {
  4317. ast_log(LOG_WARNING, "Peer '%s' may not be both outbound/symmetric model and inbound/symmetric precache model, discarding!\n",
  4318. ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid));
  4319. peer->dead = 1;
  4320. } else if (!AST_LIST_EMPTY(&peer->include) && !(peer->model & DUNDI_MODEL_OUTBOUND) && !(peer->pcmodel & DUNDI_MODEL_INBOUND)) {
  4321. ast_log(LOG_WARNING, "Peer '%s' is supposed to be included in outbound searches but isn't an outbound peer or inbound precache!\n",
  4322. ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid));
  4323. } else if (!AST_LIST_EMPTY(&peer->permit) && !(peer->model & DUNDI_MODEL_INBOUND) && !(peer->pcmodel & DUNDI_MODEL_OUTBOUND)) {
  4324. ast_log(LOG_WARNING, "Peer '%s' is supposed to have permission for some inbound searches but isn't an inbound peer or outbound precache!\n",
  4325. ast_eid_to_str(eid_str, sizeof(eid_str), &peer->eid));
  4326. } else {
  4327. if (ast_eid_cmp(&peer->eid, &empty_eid)) {
  4328. /* Schedule any items for explicitly configured peers. */
  4329. if (needregister) {
  4330. peer->registerid = ast_sched_add(sched, 2000, do_register, peer);
  4331. }
  4332. qualify_peer(peer, 1);
  4333. }
  4334. }
  4335. AST_LIST_UNLOCK(&peers);
  4336. }
  4337. static int dundi_helper(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *data, int flag)
  4338. {
  4339. struct dundi_result results[MAX_RESULTS];
  4340. int res;
  4341. int x;
  4342. int found = 0;
  4343. if (!strncasecmp(context, "macro-", 6)) {
  4344. if (!chan) {
  4345. ast_log(LOG_NOTICE, "Can't use macro mode without a channel!\n");
  4346. return -1;
  4347. }
  4348. /* If done as a macro, use macro extension */
  4349. if (!strcasecmp(exten, "s")) {
  4350. exten = pbx_builtin_getvar_helper(chan, "ARG1");
  4351. if (ast_strlen_zero(exten))
  4352. exten = ast_channel_macroexten(chan);
  4353. if (ast_strlen_zero(exten))
  4354. exten = ast_channel_exten(chan);
  4355. if (ast_strlen_zero(exten)) {
  4356. ast_log(LOG_WARNING, "Called in Macro mode with no ARG1 or MACRO_EXTEN?\n");
  4357. return -1;
  4358. }
  4359. }
  4360. if (ast_strlen_zero(data))
  4361. data = "e164";
  4362. } else {
  4363. if (ast_strlen_zero(data))
  4364. data = context;
  4365. }
  4366. res = dundi_lookup(results, MAX_RESULTS, chan, data, exten, 0);
  4367. for (x=0;x<res;x++) {
  4368. if (ast_test_flag(results + x, flag))
  4369. found++;
  4370. }
  4371. if (found >= priority)
  4372. return 1;
  4373. return 0;
  4374. }
  4375. static int dundi_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
  4376. {
  4377. return dundi_helper(chan, context, exten, priority, data, DUNDI_FLAG_EXISTS);
  4378. }
  4379. static int dundi_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
  4380. {
  4381. return dundi_helper(chan, context, exten, priority, data, DUNDI_FLAG_CANMATCH);
  4382. }
  4383. static int dundi_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
  4384. {
  4385. struct dundi_result results[MAX_RESULTS];
  4386. int res;
  4387. int x=0;
  4388. char req[1024];
  4389. const char *dundiargs;
  4390. struct ast_app *dial;
  4391. if (!strncasecmp(context, "macro-", 6)) {
  4392. if (!chan) {
  4393. ast_log(LOG_NOTICE, "Can't use macro mode without a channel!\n");
  4394. return -1;
  4395. }
  4396. /* If done as a macro, use macro extension */
  4397. if (!strcasecmp(exten, "s")) {
  4398. exten = pbx_builtin_getvar_helper(chan, "ARG1");
  4399. if (ast_strlen_zero(exten))
  4400. exten = ast_channel_macroexten(chan);
  4401. if (ast_strlen_zero(exten))
  4402. exten = ast_channel_exten(chan);
  4403. if (ast_strlen_zero(exten)) {
  4404. ast_log(LOG_WARNING, "Called in Macro mode with no ARG1 or MACRO_EXTEN?\n");
  4405. return -1;
  4406. }
  4407. }
  4408. if (ast_strlen_zero(data))
  4409. data = "e164";
  4410. } else {
  4411. if (ast_strlen_zero(data))
  4412. data = context;
  4413. }
  4414. res = dundi_lookup(results, MAX_RESULTS, chan, data, exten, 0);
  4415. if (res > 0) {
  4416. sort_results(results, res);
  4417. for (x=0;x<res;x++) {
  4418. if (ast_test_flag(results + x, DUNDI_FLAG_EXISTS)) {
  4419. if (!--priority)
  4420. break;
  4421. }
  4422. }
  4423. }
  4424. if (x < res) {
  4425. /* Got a hit! */
  4426. dundiargs = pbx_builtin_getvar_helper(chan, "DUNDIDIALARGS");
  4427. snprintf(req, sizeof(req), "%s/%s,,%s", results[x].tech, results[x].dest,
  4428. S_OR(dundiargs, ""));
  4429. dial = pbx_findapp("Dial");
  4430. if (dial)
  4431. res = pbx_exec(chan, dial, req);
  4432. } else
  4433. res = -1;
  4434. return res;
  4435. }
  4436. static int dundi_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
  4437. {
  4438. return dundi_helper(chan, context, exten, priority, data, DUNDI_FLAG_MATCHMORE);
  4439. }
  4440. static struct ast_switch dundi_switch = {
  4441. .name = "DUNDi",
  4442. .description = "DUNDi Discovered Dialplan Switch",
  4443. .exists = dundi_exists,
  4444. .canmatch = dundi_canmatch,
  4445. .exec = dundi_exec,
  4446. .matchmore = dundi_matchmore,
  4447. };
  4448. static int set_config(char *config_file, struct sockaddr_in* sin, int reload)
  4449. {
  4450. struct ast_config *cfg;
  4451. struct ast_variable *v;
  4452. char *cat;
  4453. int x;
  4454. struct ast_flags config_flags = { 0 };
  4455. char hn[MAXHOSTNAMELEN] = "";
  4456. struct ast_hostent he;
  4457. struct hostent *hp;
  4458. struct sockaddr_in sin2;
  4459. static int last_port = 0;
  4460. int globalpcmodel = 0;
  4461. dundi_eid testeid;
  4462. if (!(cfg = ast_config_load(config_file, config_flags)) || cfg == CONFIG_STATUS_FILEINVALID) {
  4463. ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
  4464. return -1;
  4465. }
  4466. dundi_ttl = DUNDI_DEFAULT_TTL;
  4467. dundi_cache_time = DUNDI_DEFAULT_CACHE_TIME;
  4468. any_peer = NULL;
  4469. ipaddr[0] = '\0';
  4470. if (!gethostname(hn, sizeof(hn)-1)) {
  4471. hp = ast_gethostbyname(hn, &he);
  4472. if (hp) {
  4473. memcpy(&sin2.sin_addr, hp->h_addr, sizeof(sin2.sin_addr));
  4474. ast_copy_string(ipaddr, ast_inet_ntoa(sin2.sin_addr), sizeof(ipaddr));
  4475. } else
  4476. ast_log(LOG_WARNING, "Unable to look up host '%s'\n", hn);
  4477. } else
  4478. ast_log(LOG_WARNING, "Unable to get host name!\n");
  4479. AST_LIST_LOCK(&peers);
  4480. if (ast_eid_is_empty(&ast_eid_default)) {
  4481. ast_log(LOG_WARNING, "Entity ID is not set.\n");
  4482. }
  4483. memcpy(&global_eid, &ast_eid_default, sizeof(global_eid));
  4484. global_storehistory = 0;
  4485. ast_copy_string(secretpath, "dundi", sizeof(secretpath));
  4486. v = ast_variable_browse(cfg, "general");
  4487. while(v) {
  4488. if (!strcasecmp(v->name, "port")){
  4489. sin->sin_port = htons(atoi(v->value));
  4490. if(last_port==0){
  4491. last_port=sin->sin_port;
  4492. } else if(sin->sin_port != last_port)
  4493. ast_log(LOG_WARNING, "change to port ignored until next asterisk re-start\n");
  4494. } else if (!strcasecmp(v->name, "bindaddr")) {
  4495. struct hostent *hep;
  4496. struct ast_hostent hent;
  4497. hep = ast_gethostbyname(v->value, &hent);
  4498. if (hep) {
  4499. memcpy(&sin->sin_addr, hep->h_addr, sizeof(sin->sin_addr));
  4500. } else
  4501. ast_log(LOG_WARNING, "Invalid host/IP '%s'\n", v->value);
  4502. } else if (!strcasecmp(v->name, "authdebug")) {
  4503. authdebug = ast_true(v->value);
  4504. } else if (!strcasecmp(v->name, "ttl")) {
  4505. if ((sscanf(v->value, "%30d", &x) == 1) && (x > 0) && (x < DUNDI_DEFAULT_TTL)) {
  4506. dundi_ttl = x;
  4507. } else {
  4508. ast_log(LOG_WARNING, "'%s' is not a valid TTL at line %d, must be number from 1 to %d\n",
  4509. v->value, v->lineno, DUNDI_DEFAULT_TTL);
  4510. }
  4511. } else if (!strcasecmp(v->name, "autokill")) {
  4512. if (sscanf(v->value, "%30d", &x) == 1) {
  4513. if (x >= 0)
  4514. global_autokilltimeout = x;
  4515. else
  4516. ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
  4517. } else if (ast_true(v->value)) {
  4518. global_autokilltimeout = DEFAULT_MAXMS;
  4519. } else {
  4520. global_autokilltimeout = 0;
  4521. }
  4522. } else if (!strcasecmp(v->name, "entityid")) {
  4523. if (!ast_str_to_eid(&testeid, v->value))
  4524. global_eid = testeid;
  4525. else
  4526. ast_log(LOG_WARNING, "Invalid global endpoint identifier '%s' at line %d\n", v->value, v->lineno);
  4527. } else if (!strcasecmp(v->name, "tos")) {
  4528. if (ast_str2tos(v->value, &tos))
  4529. ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
  4530. } else if (!strcasecmp(v->name, "department")) {
  4531. ast_copy_string(dept, v->value, sizeof(dept));
  4532. } else if (!strcasecmp(v->name, "organization")) {
  4533. ast_copy_string(org, v->value, sizeof(org));
  4534. } else if (!strcasecmp(v->name, "locality")) {
  4535. ast_copy_string(locality, v->value, sizeof(locality));
  4536. } else if (!strcasecmp(v->name, "stateprov")) {
  4537. ast_copy_string(stateprov, v->value, sizeof(stateprov));
  4538. } else if (!strcasecmp(v->name, "country")) {
  4539. ast_copy_string(country, v->value, sizeof(country));
  4540. } else if (!strcasecmp(v->name, "email")) {
  4541. ast_copy_string(email, v->value, sizeof(email));
  4542. } else if (!strcasecmp(v->name, "phone")) {
  4543. ast_copy_string(phone, v->value, sizeof(phone));
  4544. } else if (!strcasecmp(v->name, "storehistory")) {
  4545. global_storehistory = ast_true(v->value);
  4546. } else if (!strcasecmp(v->name, "cachetime")) {
  4547. if ((sscanf(v->value, "%30d", &x) == 1)) {
  4548. dundi_cache_time = x;
  4549. } else {
  4550. ast_log(LOG_WARNING, "'%s' is not a valid cache time at line %d. Using default value '%d'.\n",
  4551. v->value, v->lineno, DUNDI_DEFAULT_CACHE_TIME);
  4552. }
  4553. }
  4554. v = v->next;
  4555. }
  4556. AST_LIST_UNLOCK(&peers);
  4557. mark_mappings();
  4558. v = ast_variable_browse(cfg, "mappings");
  4559. while (v) {
  4560. AST_LIST_LOCK(&peers);
  4561. build_mapping(v->name, v->value);
  4562. AST_LIST_UNLOCK(&peers);
  4563. v = v->next;
  4564. }
  4565. prune_mappings();
  4566. mark_peers();
  4567. cat = ast_category_browse(cfg, NULL);
  4568. while(cat) {
  4569. if (strcasecmp(cat, "general") && strcasecmp(cat, "mappings")) {
  4570. /* Entries */
  4571. if (!ast_str_to_eid(&testeid, cat))
  4572. build_peer(&testeid, ast_variable_browse(cfg, cat), &globalpcmodel);
  4573. else if (!strcasecmp(cat, "*")) {
  4574. build_peer(&empty_eid, ast_variable_browse(cfg, cat), &globalpcmodel);
  4575. any_peer = find_peer(NULL);
  4576. } else
  4577. ast_log(LOG_NOTICE, "Ignoring invalid EID entry '%s'\n", cat);
  4578. }
  4579. cat = ast_category_browse(cfg, cat);
  4580. }
  4581. prune_peers();
  4582. ast_config_destroy(cfg);
  4583. load_password();
  4584. if (globalpcmodel & DUNDI_MODEL_OUTBOUND)
  4585. dundi_precache_full();
  4586. return 0;
  4587. }
  4588. static int unload_module(void)
  4589. {
  4590. ast_cli_unregister_multiple(cli_dundi, ARRAY_LEN(cli_dundi));
  4591. ast_unregister_switch(&dundi_switch);
  4592. ast_custom_function_unregister(&dundi_function);
  4593. ast_custom_function_unregister(&dundi_query_function);
  4594. ast_custom_function_unregister(&dundi_result_function);
  4595. /* Stop all currently running threads */
  4596. dundi_shutdown = 1;
  4597. if (netthreadid != AST_PTHREADT_NULL) {
  4598. pthread_kill(netthreadid, SIGURG);
  4599. pthread_join(netthreadid, NULL);
  4600. netthreadid = AST_PTHREADT_NULL;
  4601. }
  4602. if (precachethreadid != AST_PTHREADT_NULL) {
  4603. pthread_kill(precachethreadid, SIGURG);
  4604. pthread_join(precachethreadid, NULL);
  4605. precachethreadid = AST_PTHREADT_NULL;
  4606. }
  4607. if (clearcachethreadid != AST_PTHREADT_NULL) {
  4608. pthread_cancel(clearcachethreadid);
  4609. pthread_join(clearcachethreadid, NULL);
  4610. clearcachethreadid = AST_PTHREADT_NULL;
  4611. }
  4612. mark_mappings();
  4613. prune_mappings();
  4614. mark_peers();
  4615. prune_peers();
  4616. if (-1 < netsocket) {
  4617. close(netsocket);
  4618. netsocket = -1;
  4619. }
  4620. if (io) {
  4621. io_context_destroy(io);
  4622. io = NULL;
  4623. }
  4624. if (sched) {
  4625. ast_sched_context_destroy(sched);
  4626. sched = NULL;
  4627. }
  4628. return 0;
  4629. }
  4630. static int reload(void)
  4631. {
  4632. struct sockaddr_in sin;
  4633. if (set_config("dundi.conf", &sin, 1))
  4634. return AST_MODULE_LOAD_FAILURE;
  4635. return AST_MODULE_LOAD_SUCCESS;
  4636. }
  4637. static int load_module(void)
  4638. {
  4639. struct sockaddr_in sin;
  4640. dundi_set_output(dundi_debug_output);
  4641. dundi_set_error(dundi_error_output);
  4642. sin.sin_family = AF_INET;
  4643. sin.sin_port = htons(DUNDI_PORT);
  4644. sin.sin_addr.s_addr = INADDR_ANY;
  4645. /* Make a UDP socket */
  4646. io = io_context_create();
  4647. sched = ast_sched_context_create();
  4648. if (!io || !sched) {
  4649. goto declined;
  4650. }
  4651. if (set_config("dundi.conf", &sin, 0)) {
  4652. goto declined;
  4653. }
  4654. netsocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
  4655. if (netsocket < 0) {
  4656. ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
  4657. goto declined;
  4658. }
  4659. if (bind(netsocket, (struct sockaddr *) &sin, sizeof(sin))) {
  4660. ast_log(LOG_ERROR, "Unable to bind to %s port %d: %s\n",
  4661. ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), strerror(errno));
  4662. goto declined;
  4663. }
  4664. ast_set_qos(netsocket, tos, 0, "DUNDi");
  4665. if (start_network_thread()) {
  4666. ast_log(LOG_ERROR, "Unable to start network thread\n");
  4667. goto declined;
  4668. }
  4669. ast_cli_register_multiple(cli_dundi, ARRAY_LEN(cli_dundi));
  4670. if (ast_register_switch(&dundi_switch))
  4671. ast_log(LOG_ERROR, "Unable to register DUNDi switch\n");
  4672. ast_custom_function_register(&dundi_function);
  4673. ast_custom_function_register(&dundi_query_function);
  4674. ast_custom_function_register(&dundi_result_function);
  4675. ast_verb(2, "DUNDi Ready and Listening on %s port %d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
  4676. return AST_MODULE_LOAD_SUCCESS;
  4677. declined:
  4678. unload_module();
  4679. return AST_MODULE_LOAD_DECLINE;
  4680. }
  4681. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Distributed Universal Number Discovery (DUNDi)",
  4682. .support_level = AST_MODULE_SUPPORT_EXTENDED,
  4683. .load = load_module,
  4684. .unload = unload_module,
  4685. .reload = reload,
  4686. );