pbx_dundi.c 154 KB

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