chan_iax2.c 241 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588
  1. /*
  2. * Asterisk -- A telephony toolkit for Linux.
  3. *
  4. * Implementation of Inter-Asterisk eXchange Version 2
  5. *
  6. * Copyright (C) 2003-2004, Digium, Inc.
  7. *
  8. * Mark Spencer <markster@digium.com>
  9. *
  10. * This program is free software, distributed under the terms of
  11. * the GNU General Public License
  12. */
  13. #include <asterisk/lock.h>
  14. #include <asterisk/frame.h>
  15. #include <asterisk/channel.h>
  16. #include <asterisk/channel_pvt.h>
  17. #include <asterisk/logger.h>
  18. #include <asterisk/module.h>
  19. #include <asterisk/pbx.h>
  20. #include <asterisk/sched.h>
  21. #include <asterisk/io.h>
  22. #include <asterisk/config.h>
  23. #include <asterisk/options.h>
  24. #include <asterisk/cli.h>
  25. #include <asterisk/translate.h>
  26. #include <asterisk/md5.h>
  27. #include <asterisk/cdr.h>
  28. #include <asterisk/crypto.h>
  29. #include <asterisk/acl.h>
  30. #include <asterisk/manager.h>
  31. #include <asterisk/callerid.h>
  32. #include <asterisk/app.h>
  33. #include <asterisk/astdb.h>
  34. #include <asterisk/musiconhold.h>
  35. #include <asterisk/features.h>
  36. #include <asterisk/utils.h>
  37. #include <sys/mman.h>
  38. #include <arpa/inet.h>
  39. #include <dirent.h>
  40. #include <sys/socket.h>
  41. #include <netinet/in.h>
  42. #include <netinet/in_systm.h>
  43. #include <netinet/ip.h>
  44. #include <sys/time.h>
  45. #include <sys/signal.h>
  46. #include <signal.h>
  47. #include <stdlib.h>
  48. #include <stdio.h>
  49. #include <string.h>
  50. #include <errno.h>
  51. #include <unistd.h>
  52. #include <netdb.h>
  53. #include <fcntl.h>
  54. #include <sys/types.h>
  55. #include <sys/stat.h>
  56. #ifdef IAX_TRUNKING
  57. #include <sys/ioctl.h>
  58. #ifdef __linux__
  59. #include <linux/zaptel.h>
  60. #else
  61. #include <zaptel.h>
  62. #endif /* __linux__ */
  63. #endif
  64. #ifdef MYSQL_FRIENDS
  65. #include <mysql/mysql.h>
  66. #endif
  67. #include "iax2.h"
  68. #include "iax2-parser.h"
  69. #include "iax2-provision.h"
  70. #include "../astconf.h"
  71. #ifndef IPTOS_MINCOST
  72. #define IPTOS_MINCOST 0x02
  73. #endif
  74. /*
  75. * Uncomment to try experimental IAX bridge optimization,
  76. * designed to reduce latency when IAX calls cannot
  77. * be trasnferred
  78. */
  79. #define BRIDGE_OPTIMIZATION
  80. #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
  81. #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
  82. #define DEFAULT_RETRY_TIME 1000
  83. #define MEMORY_SIZE 100
  84. #define DEFAULT_DROP 3
  85. /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
  86. but keeps the division between trunked and non-trunked better. */
  87. #define TRUNK_CALL_START 0x4000
  88. #define DEBUG_SUPPORT
  89. #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
  90. /* Sample over last 100 units to determine historic jitter */
  91. #define GAMMA (0.01)
  92. #ifdef MYSQL_FRIENDS
  93. AST_MUTEX_DEFINE_STATIC(mysqllock);
  94. static MYSQL *mysql;
  95. static char mydbuser[80];
  96. static char mydbpass[80];
  97. static char mydbhost[80];
  98. static char mydbname[80];
  99. #endif
  100. static char *desc = "Inter Asterisk eXchange (Ver 2)";
  101. static char *tdesc = "Inter Asterisk eXchange Driver (Ver 2)";
  102. static char *type = "IAX2";
  103. static char context[80] = "default";
  104. static char language[MAX_LANGUAGE] = "";
  105. static char regcontext[AST_MAX_EXTENSION] = "";
  106. static int max_retries = 4;
  107. static int ping_time = 20;
  108. static int lagrq_time = 10;
  109. static int maxtrunkcall = TRUNK_CALL_START;
  110. static int maxnontrunkcall = 1;
  111. static int maxjitterbuffer=1000;
  112. static int jittershrinkrate=2;
  113. static int trunkfreq = 20;
  114. static int authdebug = 1;
  115. static int iaxcompat = 0;
  116. static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
  117. static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
  118. static int netsocket = -1;
  119. static int tos = 0;
  120. static int expirey = IAX_DEFAULT_REG_EXPIRE;
  121. static int timingfd = -1; /* Timing file descriptor */
  122. static int usecnt;
  123. AST_MUTEX_DEFINE_STATIC(usecnt_lock);
  124. int (*iax2_regfunk)(char *username, int onoff) = NULL;
  125. /* Ethernet, etc */
  126. #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
  127. /* T1, maybe ISDN */
  128. #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
  129. ~AST_FORMAT_SLINEAR & \
  130. ~AST_FORMAT_ULAW & \
  131. ~AST_FORMAT_ALAW)
  132. /* A modem */
  133. #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
  134. ~AST_FORMAT_G726 & \
  135. ~AST_FORMAT_ADPCM)
  136. #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
  137. ~AST_FORMAT_G723_1)
  138. #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
  139. #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
  140. #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
  141. static struct io_context *io;
  142. static struct sched_context *sched;
  143. static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
  144. static int iax2_dropcount = DEFAULT_DROP;
  145. static int globalusejitterbuf = 0;
  146. static int iaxdebug = 0;
  147. static int iaxtrunkdebug = 0;
  148. static char accountcode[20];
  149. static int amaflags = 0;
  150. static int globalnotransfer = 0;
  151. static int delayreject = 0;
  152. static int globalmessagedetail = 0;
  153. static pthread_t netthreadid = AST_PTHREADT_NULL;
  154. #define IAX_STATE_STARTED (1 << 0)
  155. #define IAX_STATE_AUTHENTICATED (1 << 1)
  156. #define IAX_STATE_TBD (1 << 2)
  157. struct iax2_context {
  158. char context[AST_MAX_EXTENSION];
  159. struct iax2_context *next;
  160. };
  161. struct iax2_user {
  162. char name[80];
  163. char secret[80];
  164. int authmethods;
  165. char accountcode[20];
  166. char inkeys[80]; /* Key(s) this user can use to authenticate to us */
  167. char language[MAX_LANGUAGE];
  168. int amaflags;
  169. int hascallerid;
  170. int delme;
  171. int temponly;
  172. int capability;
  173. int trunk;
  174. char callerid[AST_MAX_EXTENSION];
  175. struct ast_ha *ha;
  176. struct iax2_context *contexts;
  177. struct iax2_user *next;
  178. int notransfer;
  179. int usejitterbuf;
  180. };
  181. struct iax2_peer {
  182. char name[80];
  183. char username[80];
  184. char secret[80];
  185. char outkey[80]; /* What key we use to talk to this peer */
  186. char context[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
  187. char regexten[AST_MAX_EXTENSION]; /* Extension to register (if regcontext is used) */
  188. char peercontext[AST_MAX_EXTENSION]; /* Context to pass to peer */
  189. char mailbox[AST_MAX_EXTENSION]; /* Mailbox */
  190. struct sockaddr_in addr;
  191. int formats;
  192. struct in_addr mask;
  193. /* Dynamic Registration fields */
  194. int dynamic; /* If this is a dynamic peer */
  195. struct sockaddr_in defaddr; /* Default address if there is one */
  196. int authmethods; /* Authentication methods (IAX_AUTH_*) */
  197. char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
  198. int hascallerid;
  199. /* Suggested caller id if registering */
  200. char callerid[AST_MAX_EXTENSION];
  201. /* Whether or not to send ANI */
  202. int sendani;
  203. int expire; /* Schedule entry for expirey */
  204. int expirey; /* How soon to expire */
  205. int capability; /* Capability */
  206. int delme; /* I need to be deleted */
  207. int temponly; /* I'm only a temp */
  208. int trunk; /* Treat as an IAX trunking */
  209. int messagedetail; /* Show exact numbers? */
  210. /* Qualification */
  211. int callno; /* Call number of POKE request */
  212. int pokeexpire; /* When to expire poke */
  213. int lastms; /* How long last response took (in ms), or -1 for no response */
  214. int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
  215. struct ast_ha *ha;
  216. struct iax2_peer *next;
  217. int notransfer;
  218. int usejitterbuf;
  219. };
  220. #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
  221. static struct iax2_trunk_peer {
  222. ast_mutex_t lock;
  223. struct sockaddr_in addr;
  224. struct timeval txtrunktime; /* Transmit trunktime */
  225. struct timeval rxtrunktime; /* Receive trunktime */
  226. struct timeval lasttxtime; /* Last transmitted trunktime */
  227. struct timeval trunkact; /* Last trunk activity */
  228. unsigned int lastsent; /* Last sent time */
  229. /* Trunk data and length */
  230. unsigned char *trunkdata;
  231. unsigned int trunkdatalen;
  232. unsigned int trunkdataalloc;
  233. struct iax2_trunk_peer *next;
  234. int trunkerror;
  235. int calls;
  236. } *tpeers = NULL;
  237. AST_MUTEX_DEFINE_STATIC(tpeerlock);
  238. struct iax_firmware {
  239. struct iax_firmware *next;
  240. int fd;
  241. int mmaplen;
  242. int dead;
  243. struct ast_iax2_firmware_header *fwh;
  244. unsigned char *buf;
  245. };
  246. #define REG_STATE_UNREGISTERED 0
  247. #define REG_STATE_REGSENT 1
  248. #define REG_STATE_AUTHSENT 2
  249. #define REG_STATE_REGISTERED 3
  250. #define REG_STATE_REJECTED 4
  251. #define REG_STATE_TIMEOUT 5
  252. #define REG_STATE_NOAUTH 6
  253. #define TRANSFER_NONE 0
  254. #define TRANSFER_BEGIN 1
  255. #define TRANSFER_READY 2
  256. #define TRANSFER_RELEASED 3
  257. #define TRANSFER_PASSTHROUGH 4
  258. struct iax2_registry {
  259. struct sockaddr_in addr; /* Who we connect to for registration purposes */
  260. char username[80];
  261. char secret[80]; /* Password or key name in []'s */
  262. char random[80];
  263. int expire; /* Sched ID of expiration */
  264. int refresh; /* How often to refresh */
  265. int regstate;
  266. int messages; /* Message count */
  267. int callno; /* Associated call number if applicable */
  268. struct sockaddr_in us; /* Who the server thinks we are */
  269. struct iax2_registry *next;
  270. };
  271. static struct iax2_registry *registrations;
  272. /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
  273. #define MIN_RETRY_TIME 100
  274. #define MAX_RETRY_TIME 10000
  275. #define MAX_JITTER_BUFFER 50
  276. #define MIN_JITTER_BUFFER 10
  277. #define DEFAULT_TRUNKDATA 640 * 10 /* 40ms, uncompressed linear * 10 channels */
  278. #define MAX_TRUNKDATA 640 * 200 /* 40ms, uncompressed linear * 200 channels */
  279. #define MAX_TIMESTAMP_SKEW 640
  280. /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
  281. #define TS_GAP_FOR_JB_RESYNC 5000
  282. /* If we have more than this much excess real jitter buffer, shrink it. */
  283. static int max_jitter_buffer = MAX_JITTER_BUFFER;
  284. /* If we have less than this much excess real jitter buffer, enlarge it. */
  285. static int min_jitter_buffer = MIN_JITTER_BUFFER;
  286. struct chan_iax2_pvt {
  287. /* Pipes for communication. pipe[1] belongs to the
  288. network thread (write), and pipe[0] belongs to the individual
  289. channel (read) */
  290. /* Whether or not we Quelch audio */
  291. int quelch;
  292. /* Last received voice format */
  293. int voiceformat;
  294. /* Last received voice format */
  295. int videoformat;
  296. /* Last sent voice format */
  297. int svoiceformat;
  298. /* Last sent video format */
  299. int svideoformat;
  300. /* What we are capable of sending */
  301. int capability;
  302. /* Last received timestamp */
  303. unsigned int last;
  304. /* Last sent timestamp - never send the same timestamp twice in a single call */
  305. unsigned int lastsent;
  306. /* Next outgoing timestamp if everything is good */
  307. unsigned int nextpred;
  308. /* True if the last voice we transmitted was not silence/CNG */
  309. int notsilenttx;
  310. /* Ping time */
  311. unsigned int pingtime;
  312. /* Max time for initial response */
  313. int maxtime;
  314. /* Peer Address */
  315. struct sockaddr_in addr;
  316. /* Our call number */
  317. unsigned short callno;
  318. /* Peer callno */
  319. unsigned short peercallno;
  320. /* Peer selected format */
  321. int peerformat;
  322. /* Peer capability */
  323. int peercapability;
  324. /* timeval that we base our transmission on */
  325. struct timeval offset;
  326. /* timeval that we base our delivery on */
  327. struct timeval rxcore;
  328. /* Historical delivery time */
  329. int history[MEMORY_SIZE];
  330. /* Current base jitterbuffer */
  331. int jitterbuffer;
  332. /* Current jitter measure */
  333. int jitter;
  334. /* Historic jitter value */
  335. int historicjitter;
  336. /* LAG */
  337. int lag;
  338. /* Error, as discovered by the manager */
  339. int error;
  340. /* Owner if we have one */
  341. struct ast_channel *owner;
  342. /* What's our state? */
  343. int state;
  344. /* Expirey (optional) */
  345. int expirey;
  346. /* Next outgoing sequence number */
  347. unsigned char oseqno;
  348. /* Next sequence number they have not yet acknowledged */
  349. unsigned char rseqno;
  350. /* Next incoming sequence number */
  351. unsigned char iseqno;
  352. /* Last incoming sequence number we have acknowledged */
  353. unsigned char aseqno;
  354. /* Peer name */
  355. char peer[80];
  356. /* Default Context */
  357. char context[80];
  358. /* Caller ID if available */
  359. char callerid[80];
  360. /* Hidden Caller ID (i.e. ANI) if appropriate */
  361. char ani[80];
  362. /* Whether or not ani should be transmitted in addition to Caller*ID */
  363. int sendani;
  364. /* Whether to request autoanswer */
  365. int autoanswer;
  366. /* DNID */
  367. char dnid[80];
  368. /* Requested Extension */
  369. char exten[AST_MAX_EXTENSION];
  370. /* Expected Username */
  371. char username[80];
  372. /* Expected Secret */
  373. char secret[80];
  374. /* permitted authentication methods */
  375. int authmethods;
  376. /* MD5 challenge */
  377. char challenge[10];
  378. /* Public keys permitted keys for incoming authentication */
  379. char inkeys[80];
  380. /* Private key for outgoing authentication */
  381. char outkey[80];
  382. /* Preferred language */
  383. char language[MAX_LANGUAGE];
  384. /* Hostname/peername for naming purposes */
  385. char host[80];
  386. /* Associated registry */
  387. struct iax2_registry *reg;
  388. /* Associated peer for poking */
  389. struct iax2_peer *peerpoke;
  390. /* Transferring status */
  391. int transferring;
  392. /* Transfer identifier */
  393. int transferid;
  394. /* Already disconnected */
  395. int alreadygone;
  396. /* Who we are IAX transfering to */
  397. struct sockaddr_in transfer;
  398. /* What's the new call number for the transfer */
  399. unsigned short transfercallno;
  400. /* Status of knowledge of peer ADSI capability */
  401. int peeradsicpe;
  402. /* Who we are bridged to */
  403. unsigned short bridgecallno;
  404. unsigned int bridgesfmt;
  405. struct ast_trans_pvt *bridgetrans;
  406. /* If this is a provisioning request */
  407. int provision;
  408. int pingid; /* Transmit PING request */
  409. int lagid; /* Retransmit lag request */
  410. int autoid; /* Auto hangup for Dialplan requestor */
  411. int authid; /* Authentication rejection ID */
  412. int authfail; /* Reason to report failure */
  413. int initid; /* Initial peer auto-congest ID (based on qualified peers) */
  414. char dproot[AST_MAX_EXTENSION];
  415. char accountcode[20];
  416. int amaflags;
  417. /* This is part of a trunk interface */
  418. int trunk;
  419. struct iax2_dpcache *dpentries;
  420. int notransfer; /* do we want native bridging */
  421. int usejitterbuf; /* use jitter buffer on this channel? */
  422. };
  423. static struct ast_iax2_queue {
  424. struct iax_frame *head;
  425. struct iax_frame *tail;
  426. int count;
  427. ast_mutex_t lock;
  428. } iaxq;
  429. static struct ast_user_list {
  430. struct iax2_user *users;
  431. ast_mutex_t lock;
  432. } userl;
  433. static struct ast_peer_list {
  434. struct iax2_peer *peers;
  435. ast_mutex_t lock;
  436. } peerl;
  437. static struct ast_firmware_list {
  438. struct iax_firmware *wares;
  439. ast_mutex_t lock;
  440. } waresl;
  441. /* Extension exists */
  442. #define CACHE_FLAG_EXISTS (1 << 0)
  443. /* Extension is nonexistent */
  444. #define CACHE_FLAG_NONEXISTENT (1 << 1)
  445. /* Extension can exist */
  446. #define CACHE_FLAG_CANEXIST (1 << 2)
  447. /* Waiting to hear back response */
  448. #define CACHE_FLAG_PENDING (1 << 3)
  449. /* Timed out */
  450. #define CACHE_FLAG_TIMEOUT (1 << 4)
  451. /* Request transmitted */
  452. #define CACHE_FLAG_TRANSMITTED (1 << 5)
  453. /* Timeout */
  454. #define CACHE_FLAG_UNKNOWN (1 << 6)
  455. /* Matchmore */
  456. #define CACHE_FLAG_MATCHMORE (1 << 7)
  457. static struct iax2_dpcache {
  458. char peercontext[AST_MAX_EXTENSION];
  459. char exten[AST_MAX_EXTENSION];
  460. struct timeval orig;
  461. struct timeval expirey;
  462. int flags;
  463. unsigned short callno;
  464. int waiters[256];
  465. struct iax2_dpcache *next;
  466. struct iax2_dpcache *peer; /* For linking in peers */
  467. } *dpcache;
  468. AST_MUTEX_DEFINE_STATIC(dpcache_lock);
  469. static void iax_debug_output(const char *data)
  470. {
  471. if (iaxdebug)
  472. ast_verbose("%s", data);
  473. }
  474. static void iax_error_output(const char *data)
  475. {
  476. ast_log(LOG_WARNING, "%s", data);
  477. }
  478. /* XXX We probably should use a mutex when working with this XXX */
  479. static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
  480. static ast_mutex_t iaxsl[IAX_MAX_CALLS];
  481. static struct timeval lastused[IAX_MAX_CALLS];
  482. static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
  483. static int send_command_locked(unsigned short callno, char, int, unsigned int, char *, int, int);
  484. static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
  485. static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
  486. static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, char *, int);
  487. static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f);
  488. static int send_ping(void *data)
  489. {
  490. int callno = (long)data;
  491. /* Ping only if it's real, not if it's bridged */
  492. if (iaxs[callno]) {
  493. #ifdef BRIDGE_OPTIMIZATION
  494. if (!iaxs[callno]->bridgecallno)
  495. #endif
  496. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
  497. return 1;
  498. } else
  499. return 0;
  500. }
  501. static int send_lagrq(void *data)
  502. {
  503. int callno = (long)data;
  504. /* Ping only if it's real not if it's bridged */
  505. if (iaxs[callno]) {
  506. #ifdef BRIDGE_OPTIMIZATION
  507. if (!iaxs[callno]->bridgecallno)
  508. #endif
  509. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
  510. return 1;
  511. } else
  512. return 0;
  513. }
  514. static unsigned char compress_subclass(int subclass)
  515. {
  516. int x;
  517. int power=-1;
  518. /* If it's 128 or smaller, just return it */
  519. if (subclass < IAX_FLAG_SC_LOG)
  520. return subclass;
  521. /* Otherwise find its power */
  522. for (x = 0; x < IAX_MAX_SHIFT; x++) {
  523. if (subclass & (1 << x)) {
  524. if (power > -1) {
  525. ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
  526. return 0;
  527. } else
  528. power = x;
  529. }
  530. }
  531. return power | IAX_FLAG_SC_LOG;
  532. }
  533. static int uncompress_subclass(unsigned char csub)
  534. {
  535. /* If the SC_LOG flag is set, return 2^csub otherwise csub */
  536. if (csub & IAX_FLAG_SC_LOG) {
  537. /* special case for 'compressed' -1 */
  538. if (csub == 0xff)
  539. return -1;
  540. else
  541. return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
  542. }
  543. else
  544. return csub;
  545. }
  546. static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
  547. {
  548. struct iax2_peer *peer;
  549. int res = 0;
  550. if (lockpeer)
  551. ast_mutex_lock(&peerl.lock);
  552. peer = peerl.peers;
  553. while(peer) {
  554. if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
  555. (peer->addr.sin_port == sin.sin_port)) {
  556. strncpy(host, peer->name, len-1);
  557. res = 1;
  558. break;
  559. }
  560. peer = peer->next;
  561. }
  562. if (lockpeer)
  563. ast_mutex_unlock(&peerl.lock);
  564. return res;
  565. }
  566. static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
  567. {
  568. struct chan_iax2_pvt *tmp;
  569. tmp = malloc(sizeof(struct chan_iax2_pvt));
  570. if (tmp) {
  571. memset(tmp, 0, sizeof(struct chan_iax2_pvt));
  572. tmp->callno = 0;
  573. tmp->peercallno = 0;
  574. tmp->transfercallno = 0;
  575. tmp->bridgecallno = 0;
  576. tmp->pingid = -1;
  577. tmp->lagid = -1;
  578. tmp->autoid = -1;
  579. tmp->authid = -1;
  580. tmp->initid = -1;
  581. /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
  582. strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
  583. strncpy(tmp->host, host, sizeof(tmp->host)-1);
  584. }
  585. return tmp;
  586. }
  587. static int get_samples(struct ast_frame *f)
  588. {
  589. int samples=0;
  590. switch(f->subclass) {
  591. case AST_FORMAT_SPEEX:
  592. samples = 160; /* XXX Not necessarily true XXX */
  593. break;
  594. case AST_FORMAT_G723_1:
  595. samples = 240 /* XXX Not necessarily true XXX */;
  596. break;
  597. case AST_FORMAT_ILBC:
  598. samples = 240 * (f->datalen / 50);
  599. break;
  600. case AST_FORMAT_GSM:
  601. samples = 160 * (f->datalen / 33);
  602. break;
  603. case AST_FORMAT_G729A:
  604. samples = 160 * (f->datalen / 20);
  605. break;
  606. case AST_FORMAT_SLINEAR:
  607. samples = f->datalen / 2;
  608. break;
  609. case AST_FORMAT_LPC10:
  610. samples = 22 * 8;
  611. samples += (((char *)(f->data))[7] & 0x1) * 8;
  612. break;
  613. case AST_FORMAT_ULAW:
  614. samples = f->datalen;
  615. break;
  616. case AST_FORMAT_ALAW:
  617. samples = f->datalen;
  618. break;
  619. case AST_FORMAT_ADPCM:
  620. case AST_FORMAT_G726:
  621. samples = f->datalen *2;
  622. break;
  623. default:
  624. ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
  625. }
  626. return samples;
  627. }
  628. static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
  629. {
  630. /* Malloc() a copy of a frame */
  631. struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
  632. if (new) {
  633. memcpy(new, fr, sizeof(struct iax_frame));
  634. iax_frame_wrap(new, &fr->af);
  635. new->data = NULL;
  636. new->datalen = 0;
  637. new->direction = DIRECTION_INGRESS;
  638. new->retrans = -1;
  639. }
  640. return new;
  641. }
  642. #define NEW_PREVENT 0
  643. #define NEW_ALLOW 1
  644. #define NEW_FORCE 2
  645. static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
  646. {
  647. if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
  648. (cur->addr.sin_port == sin->sin_port)) {
  649. /* This is the main host */
  650. if ((cur->peercallno == callno) ||
  651. ((dcallno == cur->callno) && !cur->peercallno)) {
  652. /* That's us. Be sure we keep track of the peer call number */
  653. return 1;
  654. }
  655. }
  656. if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
  657. (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
  658. /* We're transferring */
  659. if (dcallno == cur->callno)
  660. return 1;
  661. }
  662. return 0;
  663. }
  664. static void update_max_trunk(void)
  665. {
  666. int max = TRUNK_CALL_START;
  667. int x;
  668. /* XXX Prolly don't need locks here XXX */
  669. for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
  670. if (iaxs[x])
  671. max = x + 1;
  672. }
  673. maxtrunkcall = max;
  674. if (option_debug)
  675. ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
  676. }
  677. static void update_max_nontrunk(void)
  678. {
  679. int max = 1;
  680. int x;
  681. /* XXX Prolly don't need locks here XXX */
  682. for (x=1;x<TRUNK_CALL_START - 1; x++) {
  683. if (iaxs[x])
  684. max = x + 1;
  685. }
  686. maxnontrunkcall = max;
  687. if (option_debug)
  688. ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
  689. }
  690. static int make_trunk(unsigned short callno, int locked)
  691. {
  692. int x;
  693. int res= 0;
  694. struct timeval now;
  695. if (iaxs[callno]->oseqno) {
  696. ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
  697. return -1;
  698. }
  699. if (callno & TRUNK_CALL_START) {
  700. ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
  701. return -1;
  702. }
  703. gettimeofday(&now, NULL);
  704. for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
  705. ast_mutex_lock(&iaxsl[x]);
  706. if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
  707. iaxs[x] = iaxs[callno];
  708. iaxs[x]->callno = x;
  709. iaxs[callno] = NULL;
  710. /* Update the two timers that should have been started */
  711. if (iaxs[x]->pingid > -1)
  712. ast_sched_del(sched, iaxs[x]->pingid);
  713. if (iaxs[x]->lagid > -1)
  714. ast_sched_del(sched, iaxs[x]->lagid);
  715. iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
  716. iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
  717. if (locked)
  718. ast_mutex_unlock(&iaxsl[callno]);
  719. res = x;
  720. if (!locked)
  721. ast_mutex_unlock(&iaxsl[x]);
  722. break;
  723. }
  724. ast_mutex_unlock(&iaxsl[x]);
  725. }
  726. if (x >= IAX_MAX_CALLS - 1) {
  727. ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
  728. return -1;
  729. }
  730. ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
  731. /* We move this call from a non-trunked to a trunked call */
  732. update_max_trunk();
  733. update_max_nontrunk();
  734. return res;
  735. }
  736. static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer)
  737. {
  738. int res = 0;
  739. int x;
  740. struct timeval now;
  741. char iabuf[INET_ADDRSTRLEN];
  742. char host[80];
  743. if (new <= NEW_ALLOW) {
  744. /* Look for an existing connection first */
  745. for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
  746. ast_mutex_lock(&iaxsl[x]);
  747. if (iaxs[x]) {
  748. /* Look for an exact match */
  749. if (match(sin, callno, dcallno, iaxs[x])) {
  750. res = x;
  751. }
  752. }
  753. ast_mutex_unlock(&iaxsl[x]);
  754. }
  755. for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
  756. ast_mutex_lock(&iaxsl[x]);
  757. if (iaxs[x]) {
  758. /* Look for an exact match */
  759. if (match(sin, callno, dcallno, iaxs[x])) {
  760. res = x;
  761. }
  762. }
  763. ast_mutex_unlock(&iaxsl[x]);
  764. }
  765. }
  766. if ((res < 1) && (new >= NEW_ALLOW)) {
  767. if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
  768. snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
  769. gettimeofday(&now, NULL);
  770. for (x=1;x<TRUNK_CALL_START;x++) {
  771. /* Find first unused call number that hasn't been used in a while */
  772. ast_mutex_lock(&iaxsl[x]);
  773. if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
  774. ast_mutex_unlock(&iaxsl[x]);
  775. }
  776. /* We've still got lock held if we found a spot */
  777. if (x >= TRUNK_CALL_START) {
  778. ast_log(LOG_WARNING, "No more space\n");
  779. return 0;
  780. }
  781. iaxs[x] = new_iax(sin, lockpeer, host);
  782. update_max_nontrunk();
  783. if (iaxs[x]) {
  784. if (option_debug)
  785. ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
  786. iaxs[x]->addr.sin_port = sin->sin_port;
  787. iaxs[x]->addr.sin_family = sin->sin_family;
  788. iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
  789. iaxs[x]->peercallno = callno;
  790. iaxs[x]->callno = x;
  791. iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
  792. iaxs[x]->expirey = expirey;
  793. iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
  794. iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
  795. iaxs[x]->amaflags = amaflags;
  796. iaxs[x]->notransfer = globalnotransfer;
  797. iaxs[x]->usejitterbuf = globalusejitterbuf;
  798. strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
  799. } else {
  800. ast_log(LOG_WARNING, "Out of resources\n");
  801. ast_mutex_unlock(&iaxsl[x]);
  802. return 0;
  803. }
  804. ast_mutex_unlock(&iaxsl[x]);
  805. res = x;
  806. }
  807. return res;
  808. }
  809. static void iax2_frame_free(struct iax_frame *fr)
  810. {
  811. if (fr->retrans > -1)
  812. ast_sched_del(sched, fr->retrans);
  813. iax_frame_free(fr);
  814. }
  815. static int iax2_queue_frame(int callno, struct ast_frame *f)
  816. {
  817. /* Assumes lock for callno is already held... */
  818. for (;;) {
  819. if (iaxs[callno] && iaxs[callno]->owner) {
  820. if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
  821. /* Avoid deadlock by pausing and trying again */
  822. ast_mutex_unlock(&iaxsl[callno]);
  823. usleep(1);
  824. ast_mutex_lock(&iaxsl[callno]);
  825. } else {
  826. ast_queue_frame(iaxs[callno]->owner, f);
  827. ast_mutex_unlock(&iaxs[callno]->owner->lock);
  828. break;
  829. }
  830. } else
  831. break;
  832. }
  833. return 0;
  834. }
  835. static void destroy_firmware(struct iax_firmware *cur)
  836. {
  837. /* Close firmware */
  838. if (cur->fwh) {
  839. munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
  840. }
  841. close(cur->fd);
  842. free(cur);
  843. }
  844. static int try_firmware(char *s)
  845. {
  846. struct stat stbuf;
  847. struct iax_firmware *cur;
  848. int ifd;
  849. int fd;
  850. int res;
  851. struct ast_iax2_firmware_header *fwh, fwh2;
  852. struct MD5Context md5;
  853. unsigned char sum[16];
  854. unsigned char buf[1024];
  855. int len, chunk;
  856. char *s2;
  857. char *last;
  858. s2 = alloca(strlen(s) + 100);
  859. if (!s2) {
  860. ast_log(LOG_WARNING, "Alloca failed!\n");
  861. return -1;
  862. }
  863. last = strrchr(s, '/');
  864. if (last)
  865. last++;
  866. else
  867. last = s;
  868. snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)rand());
  869. res = stat(s, &stbuf);
  870. if (res < 0) {
  871. ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
  872. return -1;
  873. }
  874. /* Make sure it's not a directory */
  875. if (S_ISDIR(stbuf.st_mode))
  876. return -1;
  877. ifd = open(s, O_RDONLY);
  878. if (ifd < 0) {
  879. ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
  880. return -1;
  881. }
  882. fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
  883. if (fd < 0) {
  884. ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
  885. close(ifd);
  886. return -1;
  887. }
  888. /* Unlink our newly created file */
  889. unlink(s2);
  890. /* Now copy the firmware into it */
  891. len = stbuf.st_size;
  892. while(len) {
  893. chunk = len;
  894. if (chunk > sizeof(buf))
  895. chunk = sizeof(buf);
  896. res = read(ifd, buf, chunk);
  897. if (res != chunk) {
  898. ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
  899. close(ifd);
  900. close(fd);
  901. return -1;
  902. }
  903. res = write(fd, buf, chunk);
  904. if (res != chunk) {
  905. ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
  906. close(ifd);
  907. close(fd);
  908. return -1;
  909. }
  910. len -= chunk;
  911. }
  912. close(ifd);
  913. /* Return to the beginning */
  914. lseek(fd, 0, SEEK_SET);
  915. if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
  916. ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
  917. close(fd);
  918. return -1;
  919. }
  920. if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
  921. ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
  922. close(fd);
  923. return -1;
  924. }
  925. if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
  926. ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
  927. close(fd);
  928. return -1;
  929. }
  930. if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero(fwh2.devname)) {
  931. ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
  932. close(fd);
  933. return -1;
  934. }
  935. fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
  936. if (!fwh) {
  937. ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
  938. close(fd);
  939. return -1;
  940. }
  941. MD5Init(&md5);
  942. MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
  943. MD5Final(sum, &md5);
  944. if (memcmp(sum, fwh->chksum, sizeof(sum))) {
  945. ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
  946. munmap(fwh, stbuf.st_size);
  947. close(fd);
  948. return -1;
  949. }
  950. cur = waresl.wares;
  951. while(cur) {
  952. if (!strcmp(cur->fwh->devname, fwh->devname)) {
  953. /* Found a candidate */
  954. if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
  955. /* The version we have on loaded is older, load this one instead */
  956. break;
  957. /* This version is no newer than what we have. Don't worry about it.
  958. We'll consider it a proper load anyhow though */
  959. munmap(fwh, stbuf.st_size);
  960. close(fd);
  961. return 0;
  962. }
  963. cur = cur->next;
  964. }
  965. if (!cur) {
  966. /* Allocate a new one and link it */
  967. cur = malloc(sizeof(struct iax_firmware));
  968. if (cur) {
  969. memset(cur, 0, sizeof(struct iax_firmware));
  970. cur->fd = -1;
  971. cur->next = waresl.wares;
  972. waresl.wares = cur;
  973. }
  974. }
  975. if (cur) {
  976. if (cur->fwh) {
  977. munmap(cur->fwh, cur->mmaplen);
  978. }
  979. if (cur->fd > -1)
  980. close(cur->fd);
  981. cur->fwh = fwh;
  982. cur->fd = fd;
  983. cur->mmaplen = stbuf.st_size;
  984. cur->dead = 0;
  985. }
  986. return 0;
  987. }
  988. static int iax_check_version(char *dev)
  989. {
  990. int res = 0;
  991. struct iax_firmware *cur;
  992. if (dev && !ast_strlen_zero(dev)) {
  993. ast_mutex_lock(&waresl.lock);
  994. cur = waresl.wares;
  995. while(cur) {
  996. if (!strcmp(dev, cur->fwh->devname)) {
  997. res = ntohs(cur->fwh->version);
  998. break;
  999. }
  1000. cur = cur->next;
  1001. }
  1002. ast_mutex_unlock(&waresl.lock);
  1003. }
  1004. return res;
  1005. }
  1006. static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
  1007. {
  1008. int res = -1;
  1009. unsigned int bs = desc & 0xff;
  1010. unsigned int start = (desc >> 8) & 0xffffff;
  1011. unsigned int bytes;
  1012. struct iax_firmware *cur;
  1013. if (dev && !ast_strlen_zero(dev) && bs) {
  1014. start *= bs;
  1015. ast_mutex_lock(&waresl.lock);
  1016. cur = waresl.wares;
  1017. while(cur) {
  1018. if (!strcmp(dev, cur->fwh->devname)) {
  1019. iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
  1020. if (start < ntohl(cur->fwh->datalen)) {
  1021. bytes = ntohl(cur->fwh->datalen) - start;
  1022. if (bytes > bs)
  1023. bytes = bs;
  1024. iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
  1025. } else {
  1026. bytes = 0;
  1027. iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
  1028. }
  1029. if (bytes == bs)
  1030. res = 0;
  1031. else
  1032. res = 1;
  1033. break;
  1034. }
  1035. cur = cur->next;
  1036. }
  1037. ast_mutex_unlock(&waresl.lock);
  1038. }
  1039. return res;
  1040. }
  1041. static void reload_firmware(void)
  1042. {
  1043. struct iax_firmware *cur, *curl, *curp;
  1044. DIR *fwd;
  1045. struct dirent *de;
  1046. char dir[256];
  1047. char fn[256];
  1048. /* Mark all as dead */
  1049. ast_mutex_lock(&waresl.lock);
  1050. cur = waresl.wares;
  1051. while(cur) {
  1052. cur->dead = 1;
  1053. cur = cur->next;
  1054. }
  1055. /* Now that we've freed them, load the new ones */
  1056. snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
  1057. fwd = opendir(dir);
  1058. if (fwd) {
  1059. while((de = readdir(fwd))) {
  1060. if (de->d_name[0] != '.') {
  1061. snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
  1062. if (!try_firmware(fn)) {
  1063. if (option_verbose > 1)
  1064. ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
  1065. }
  1066. }
  1067. }
  1068. closedir(fwd);
  1069. } else
  1070. ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
  1071. /* Clean up leftovers */
  1072. cur = waresl.wares;
  1073. curp = NULL;
  1074. while(cur) {
  1075. curl = cur;
  1076. cur = cur->next;
  1077. if (curl->dead) {
  1078. if (curp) {
  1079. curp->next = cur;
  1080. } else {
  1081. waresl.wares = cur;
  1082. }
  1083. destroy_firmware(curl);
  1084. } else {
  1085. curp = cur;
  1086. }
  1087. }
  1088. ast_mutex_unlock(&waresl.lock);
  1089. }
  1090. static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
  1091. static int __do_deliver(void *data)
  1092. {
  1093. /* Just deliver the packet by using queueing. This is called by
  1094. the IAX thread with the iaxsl lock held. */
  1095. struct iax_frame *fr = data;
  1096. fr->retrans = -1;
  1097. if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone)
  1098. iax2_queue_frame(fr->callno, &fr->af);
  1099. /* Free our iax frame */
  1100. iax2_frame_free(fr);
  1101. /* And don't run again */
  1102. return 0;
  1103. }
  1104. static int do_deliver(void *data)
  1105. {
  1106. /* Locking version of __do_deliver */
  1107. struct iax_frame *fr = data;
  1108. int callno = fr->callno;
  1109. int res;
  1110. ast_mutex_lock(&iaxsl[callno]);
  1111. res = __do_deliver(data);
  1112. ast_mutex_unlock(&iaxsl[callno]);
  1113. return res;
  1114. }
  1115. static int handle_error(void)
  1116. {
  1117. /* XXX Ideally we should figure out why an error occured and then abort those
  1118. rather than continuing to try. Unfortunately, the published interface does
  1119. not seem to work XXX */
  1120. #if 0
  1121. struct sockaddr_in *sin;
  1122. int res;
  1123. struct msghdr m;
  1124. struct sock_extended_err e;
  1125. m.msg_name = NULL;
  1126. m.msg_namelen = 0;
  1127. m.msg_iov = NULL;
  1128. m.msg_control = &e;
  1129. m.msg_controllen = sizeof(e);
  1130. m.msg_flags = 0;
  1131. res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
  1132. if (res < 0)
  1133. ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
  1134. else {
  1135. if (m.msg_controllen) {
  1136. sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
  1137. if (sin)
  1138. ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
  1139. else
  1140. ast_log(LOG_WARNING, "No address detected??\n");
  1141. } else {
  1142. ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
  1143. }
  1144. }
  1145. #endif
  1146. return 0;
  1147. }
  1148. static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin)
  1149. {
  1150. int res;
  1151. res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)sin,
  1152. sizeof(*sin));
  1153. if (res < 0) {
  1154. if (option_debug)
  1155. ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
  1156. handle_error();
  1157. } else
  1158. res = 0;
  1159. return res;
  1160. }
  1161. static int send_packet(struct iax_frame *f)
  1162. {
  1163. int res;
  1164. char iabuf[INET_ADDRSTRLEN];
  1165. /* Called with iaxsl held */
  1166. if (option_debug)
  1167. ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, f->callno, iaxs[f->callno]->peercallno, ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[f->callno]->addr.sin_addr), ntohs(iaxs[f->callno]->addr.sin_port));
  1168. /* Don't send if there was an error, but return error instead */
  1169. if (!f->callno) {
  1170. ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
  1171. return -1;
  1172. }
  1173. if (!iaxs[f->callno])
  1174. return -1;
  1175. if (iaxs[f->callno]->error)
  1176. return -1;
  1177. if (f->transfer) {
  1178. if (iaxdebug)
  1179. iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
  1180. res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
  1181. sizeof(iaxs[f->callno]->transfer));
  1182. } else {
  1183. if (iaxdebug)
  1184. iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
  1185. res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
  1186. sizeof(iaxs[f->callno]->addr));
  1187. }
  1188. if (res < 0) {
  1189. if (option_debug)
  1190. ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
  1191. handle_error();
  1192. } else
  1193. res = 0;
  1194. return res;
  1195. }
  1196. static int iax2_predestroy(int callno)
  1197. {
  1198. struct ast_channel *c;
  1199. struct chan_iax2_pvt *pvt;
  1200. ast_mutex_lock(&iaxsl[callno]);
  1201. pvt = iaxs[callno];
  1202. if (!pvt) {
  1203. ast_mutex_unlock(&iaxsl[callno]);
  1204. return -1;
  1205. }
  1206. if (!pvt->alreadygone) {
  1207. /* No more pings or lagrq's */
  1208. if (pvt->pingid > -1)
  1209. ast_sched_del(sched, pvt->pingid);
  1210. if (pvt->lagid > -1)
  1211. ast_sched_del(sched, pvt->lagid);
  1212. if (pvt->autoid > -1)
  1213. ast_sched_del(sched, pvt->autoid);
  1214. if (pvt->authid > -1)
  1215. ast_sched_del(sched, pvt->authid);
  1216. if (pvt->initid > -1)
  1217. ast_sched_del(sched, pvt->initid);
  1218. pvt->pingid = -1;
  1219. pvt->lagid = -1;
  1220. pvt->autoid = -1;
  1221. pvt->initid = -1;
  1222. pvt->authid = -1;
  1223. pvt->alreadygone = 1;
  1224. }
  1225. c = pvt->owner;
  1226. if (c) {
  1227. c->_softhangup |= AST_SOFTHANGUP_DEV;
  1228. c->pvt->pvt = NULL;
  1229. ast_queue_hangup(c);
  1230. pvt->owner = NULL;
  1231. ast_mutex_lock(&usecnt_lock);
  1232. usecnt--;
  1233. if (usecnt < 0)
  1234. ast_log(LOG_WARNING, "Usecnt < 0???\n");
  1235. ast_mutex_unlock(&usecnt_lock);
  1236. }
  1237. ast_mutex_unlock(&iaxsl[callno]);
  1238. ast_update_use_count();
  1239. return 0;
  1240. }
  1241. static int iax2_predestroy_nolock(int callno)
  1242. {
  1243. int res;
  1244. ast_mutex_unlock(&iaxsl[callno]);
  1245. res = iax2_predestroy(callno);
  1246. ast_mutex_lock(&iaxsl[callno]);
  1247. return res;
  1248. }
  1249. static void iax2_destroy(int callno)
  1250. {
  1251. struct chan_iax2_pvt *pvt;
  1252. struct iax_frame *cur;
  1253. struct ast_channel *owner;
  1254. retry:
  1255. ast_mutex_lock(&iaxsl[callno]);
  1256. pvt = iaxs[callno];
  1257. gettimeofday(&lastused[callno], NULL);
  1258. if (pvt)
  1259. owner = pvt->owner;
  1260. else
  1261. owner = NULL;
  1262. if (owner) {
  1263. if (ast_mutex_trylock(&owner->lock)) {
  1264. ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
  1265. ast_mutex_unlock(&iaxsl[callno]);
  1266. usleep(1);
  1267. goto retry;
  1268. }
  1269. }
  1270. if (!owner)
  1271. iaxs[callno] = NULL;
  1272. if (pvt) {
  1273. if (!owner)
  1274. pvt->owner = NULL;
  1275. /* No more pings or lagrq's */
  1276. if (pvt->pingid > -1)
  1277. ast_sched_del(sched, pvt->pingid);
  1278. if (pvt->lagid > -1)
  1279. ast_sched_del(sched, pvt->lagid);
  1280. if (pvt->autoid > -1)
  1281. ast_sched_del(sched, pvt->autoid);
  1282. if (pvt->authid > -1)
  1283. ast_sched_del(sched, pvt->authid);
  1284. if (pvt->initid > -1)
  1285. ast_sched_del(sched, pvt->initid);
  1286. pvt->pingid = -1;
  1287. pvt->lagid = -1;
  1288. pvt->autoid = -1;
  1289. pvt->authid = -1;
  1290. pvt->initid = -1;
  1291. if (pvt->bridgetrans)
  1292. ast_translator_free_path(pvt->bridgetrans);
  1293. pvt->bridgetrans = NULL;
  1294. /* Already gone */
  1295. pvt->alreadygone = 1;
  1296. if (owner) {
  1297. /* If there's an owner, prod it to give up */
  1298. owner->_softhangup |= AST_SOFTHANGUP_DEV;
  1299. ast_queue_hangup(owner);
  1300. }
  1301. for (cur = iaxq.head; cur ; cur = cur->next) {
  1302. /* Cancel any pending transmissions */
  1303. if (cur->callno == pvt->callno)
  1304. cur->retries = -1;
  1305. }
  1306. if (pvt->reg) {
  1307. pvt->reg->callno = 0;
  1308. }
  1309. if (!owner)
  1310. free(pvt);
  1311. }
  1312. if (owner) {
  1313. ast_mutex_unlock(&owner->lock);
  1314. }
  1315. ast_mutex_unlock(&iaxsl[callno]);
  1316. if (callno & 0x4000)
  1317. update_max_trunk();
  1318. }
  1319. static void iax2_destroy_nolock(int callno)
  1320. {
  1321. /* Actually it's easier to unlock, kill it, and relock */
  1322. ast_mutex_unlock(&iaxsl[callno]);
  1323. iax2_destroy(callno);
  1324. ast_mutex_lock(&iaxsl[callno]);
  1325. }
  1326. static int update_packet(struct iax_frame *f)
  1327. {
  1328. /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
  1329. struct ast_iax2_full_hdr *fh = f->data;
  1330. /* Mark this as a retransmission */
  1331. fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
  1332. /* Update iseqno */
  1333. f->iseqno = iaxs[f->callno]->iseqno;
  1334. fh->iseqno = f->iseqno;
  1335. return 0;
  1336. }
  1337. static int attempt_transmit(void *data)
  1338. {
  1339. /* Attempt to transmit the frame to the remote peer...
  1340. Called without iaxsl held. */
  1341. struct iax_frame *f = data;
  1342. int freeme=0;
  1343. int callno = f->callno;
  1344. char iabuf[INET_ADDRSTRLEN];
  1345. /* Make sure this call is still active */
  1346. if (callno)
  1347. ast_mutex_lock(&iaxsl[callno]);
  1348. if ((f->callno) && iaxs[f->callno]) {
  1349. if ((f->retries < 0) /* Already ACK'd */ ||
  1350. (f->retries >= max_retries) /* Too many attempts */) {
  1351. /* Record an error if we've transmitted too many times */
  1352. if (f->retries >= max_retries) {
  1353. if (f->transfer) {
  1354. /* Transfer timeout */
  1355. send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
  1356. } else if (f->final) {
  1357. if (f->final)
  1358. iax2_destroy_nolock(f->callno);
  1359. } else {
  1360. if (iaxs[f->callno]->owner)
  1361. ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
  1362. iaxs[f->callno]->error = ETIMEDOUT;
  1363. if (iaxs[f->callno]->owner) {
  1364. struct ast_frame fr = { 0, };
  1365. /* Hangup the fd */
  1366. fr.frametype = AST_FRAME_CONTROL;
  1367. fr.subclass = AST_CONTROL_HANGUP;
  1368. iax2_queue_frame(f->callno, &fr);
  1369. } else {
  1370. if (iaxs[f->callno]->reg) {
  1371. memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
  1372. iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
  1373. iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
  1374. }
  1375. iax2_destroy_nolock(f->callno);
  1376. }
  1377. }
  1378. }
  1379. freeme++;
  1380. } else {
  1381. /* Update it if it needs it */
  1382. update_packet(f);
  1383. /* Attempt transmission */
  1384. send_packet(f);
  1385. f->retries++;
  1386. /* Try again later after 10 times as long */
  1387. f->retrytime *= 10;
  1388. if (f->retrytime > MAX_RETRY_TIME)
  1389. f->retrytime = MAX_RETRY_TIME;
  1390. /* Transfer messages max out at one second */
  1391. if (f->transfer && (f->retrytime > 1000))
  1392. f->retrytime = 1000;
  1393. f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
  1394. }
  1395. } else {
  1396. /* Make sure it gets freed */
  1397. f->retries = -1;
  1398. freeme++;
  1399. }
  1400. if (callno)
  1401. ast_mutex_unlock(&iaxsl[callno]);
  1402. /* Do not try again */
  1403. if (freeme) {
  1404. /* Don't attempt delivery, just remove it from the queue */
  1405. ast_mutex_lock(&iaxq.lock);
  1406. if (f->prev)
  1407. f->prev->next = f->next;
  1408. else
  1409. iaxq.head = f->next;
  1410. if (f->next)
  1411. f->next->prev = f->prev;
  1412. else
  1413. iaxq.tail = f->prev;
  1414. iaxq.count--;
  1415. ast_mutex_unlock(&iaxq.lock);
  1416. f->retrans = -1;
  1417. /* Free the IAX frame */
  1418. iax2_frame_free(f);
  1419. }
  1420. return 0;
  1421. }
  1422. static int iax2_set_jitter(int fd, int argc, char *argv[])
  1423. {
  1424. if ((argc != 4) && (argc != 5))
  1425. return RESULT_SHOWUSAGE;
  1426. if (argc == 4) {
  1427. max_jitter_buffer = atoi(argv[3]);
  1428. if (max_jitter_buffer < 0)
  1429. max_jitter_buffer = 0;
  1430. } else {
  1431. if (argc == 5) {
  1432. if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
  1433. if (iaxs[atoi(argv[3])]) {
  1434. iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
  1435. if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
  1436. iaxs[atoi(argv[3])]->jitterbuffer = 0;
  1437. } else
  1438. ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
  1439. } else
  1440. ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
  1441. }
  1442. }
  1443. return RESULT_SUCCESS;
  1444. }
  1445. static char jitter_usage[] =
  1446. "Usage: iax set jitter [callid] <value>\n"
  1447. " If used with a callid, it sets the jitter buffer to the given static\n"
  1448. "value (until its next calculation). If used without a callid, the value is used\n"
  1449. "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
  1450. "buffer size is reduced.";
  1451. static int iax2_show_stats(int fd, int argc, char *argv[])
  1452. {
  1453. struct iax_frame *cur;
  1454. int cnt = 0, dead=0, final=0;
  1455. if (argc != 3)
  1456. return RESULT_SHOWUSAGE;
  1457. for (cur = iaxq.head; cur ; cur = cur->next) {
  1458. if (cur->retries < 0)
  1459. dead++;
  1460. if (cur->final)
  1461. final++;
  1462. cnt++;
  1463. }
  1464. ast_cli(fd, " IAX Statistics\n");
  1465. ast_cli(fd, "---------------------\n");
  1466. ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
  1467. ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
  1468. return RESULT_SUCCESS;
  1469. }
  1470. static int iax2_show_cache(int fd, int argc, char *argv[])
  1471. {
  1472. struct iax2_dpcache *dp;
  1473. char tmp[1024] = "", *pc;
  1474. int s;
  1475. int x,y;
  1476. struct timeval tv;
  1477. gettimeofday(&tv, NULL);
  1478. ast_mutex_lock(&dpcache_lock);
  1479. dp = dpcache;
  1480. ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
  1481. while(dp) {
  1482. s = dp->expirey.tv_sec - tv.tv_sec;
  1483. tmp[0] = '\0';
  1484. if (dp->flags & CACHE_FLAG_EXISTS)
  1485. strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
  1486. if (dp->flags & CACHE_FLAG_NONEXISTENT)
  1487. strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
  1488. if (dp->flags & CACHE_FLAG_CANEXIST)
  1489. strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
  1490. if (dp->flags & CACHE_FLAG_PENDING)
  1491. strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
  1492. if (dp->flags & CACHE_FLAG_TIMEOUT)
  1493. strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
  1494. if (dp->flags & CACHE_FLAG_TRANSMITTED)
  1495. strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
  1496. if (dp->flags & CACHE_FLAG_MATCHMORE)
  1497. strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
  1498. if (dp->flags & CACHE_FLAG_UNKNOWN)
  1499. strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
  1500. /* Trim trailing pipe */
  1501. if (!ast_strlen_zero(tmp))
  1502. tmp[strlen(tmp) - 1] = '\0';
  1503. else
  1504. strncpy(tmp, "(none)", sizeof(tmp) - 1);
  1505. y=0;
  1506. pc = strchr(dp->peercontext, '@');
  1507. if (!pc)
  1508. pc = dp->peercontext;
  1509. else
  1510. pc++;
  1511. for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
  1512. if (dp->waiters[x] > -1)
  1513. y++;
  1514. if (s > 0)
  1515. ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
  1516. else
  1517. ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
  1518. dp = dp->next;
  1519. }
  1520. ast_mutex_unlock(&dpcache_lock);
  1521. return RESULT_SUCCESS;
  1522. }
  1523. static char show_stats_usage[] =
  1524. "Usage: iax show stats\n"
  1525. " Display statistics on IAX channel driver.\n";
  1526. static char show_cache_usage[] =
  1527. "Usage: iax show cache\n"
  1528. " Display currently cached IAX Dialplan results.\n";
  1529. static struct ast_cli_entry cli_set_jitter =
  1530. { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
  1531. static struct ast_cli_entry cli_show_stats =
  1532. { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
  1533. static struct ast_cli_entry cli_show_cache =
  1534. { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
  1535. static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
  1536. #ifdef BRIDGE_OPTIMIZATION
  1537. static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
  1538. static int forward_delivery(struct iax_frame *fr)
  1539. {
  1540. struct chan_iax2_pvt *p1, *p2;
  1541. char iabuf[INET_ADDRSTRLEN];
  1542. int res, orig_ts;
  1543. p1 = iaxs[fr->callno];
  1544. p2 = iaxs[p1->bridgecallno];
  1545. if (!p1)
  1546. return -1;
  1547. if (!p2)
  1548. return -1;
  1549. if (option_debug)
  1550. ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
  1551. fr->ts,
  1552. p1->callno, p1->peercallno,
  1553. p2->callno, p2->peercallno,
  1554. ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
  1555. ntohs(p2->addr.sin_port));
  1556. /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
  1557. This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
  1558. send full frame on timestamp wrap when doing optimized bridging
  1559. (actually current code STILL doesn't)
  1560. */
  1561. if (fr->ts + 50000 <= p1->last) {
  1562. fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
  1563. if (option_debug)
  1564. ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
  1565. }
  1566. /* Send with timestamp adjusted to the origin of the outbound leg */
  1567. /* But don't destroy inbound timestamp still needed later to set "last" */
  1568. orig_ts = fr->ts;
  1569. fr->ts = calc_fakestamp(p1, p2, fr->ts);
  1570. res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
  1571. fr->ts = orig_ts;
  1572. return res;
  1573. }
  1574. #endif
  1575. static void unwrap_timestamp(struct iax_frame *fr)
  1576. {
  1577. int x;
  1578. if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
  1579. x = fr->ts - iaxs[fr->callno]->last;
  1580. if (x < -50000) {
  1581. /* Sudden big jump backwards in timestamp:
  1582. What likely happened here is that miniframe timestamp has circled but we haven't
  1583. gotten the update from the main packet. We'll just pretend that we did, and
  1584. update the timestamp appropriately. */
  1585. fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
  1586. if (option_debug)
  1587. ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
  1588. }
  1589. if (x > 50000) {
  1590. /* Sudden apparent big jump forwards in timestamp:
  1591. What's likely happened is this is an old miniframe belonging to the previous
  1592. top-16-bit timestamp that has turned up out of order.
  1593. Adjust the timestamp appropriately. */
  1594. fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
  1595. if (option_debug)
  1596. ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
  1597. }
  1598. }
  1599. }
  1600. static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory, int fromtrunk)
  1601. {
  1602. int ms,x;
  1603. int delay;
  1604. unsigned int orig_ts;
  1605. int drops[MEMORY_SIZE];
  1606. int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
  1607. /* Remember current jitterbuffer so we can log any change */
  1608. prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
  1609. /* Similarly for the frame timestamp */
  1610. orig_ts = fr->ts;
  1611. #if 0
  1612. if (option_debug)
  1613. ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, really=%d, update=%d\n",
  1614. fr->ts, iaxs[fr->callno]->last, reallydeliver, updatehistory);
  1615. #endif
  1616. /* Attempt to recover wrapped timestamps */
  1617. unwrap_timestamp(fr);
  1618. if (updatehistory) {
  1619. /* Attempt to spot a change of timebase on timestamps coming from the other side
  1620. We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
  1621. by network jitter or reordering. Sometimes, also, the peer stops sending us frames
  1622. for a while - in this case this code might also resync us. But that's not a bad thing.
  1623. Be careful of non-voice frames which are timestamped differently (especially ACKS!)
  1624. [that's why we only do this when updatehistory is true]
  1625. */
  1626. x = fr->ts - iaxs[fr->callno]->last;
  1627. if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
  1628. if (option_debug)
  1629. ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped. resyncing rxcore (ts=%d, last=%d)\n",
  1630. fr->callno, fr->ts, iaxs[fr->callno]->last);
  1631. /* zap rxcore - calc_rxstamp will make a new one based on this frame */
  1632. iaxs[fr->callno]->rxcore.tv_sec = 0;
  1633. iaxs[fr->callno]->rxcore.tv_usec = 0;
  1634. /* wipe "last" if stamps have jumped backwards */
  1635. if (x<0)
  1636. iaxs[fr->callno]->last = 0;
  1637. /* should we also empty history? */
  1638. }
  1639. /* ms is a measure of the "lateness" of the frame relative to the "reference"
  1640. frame we received. (initially the very first, but also see code just above here).
  1641. Understand that "ms" can easily be -ve if lag improves since the reference frame.
  1642. Called by IAX thread, with iaxsl lock held. */
  1643. ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
  1644. /* Rotate our history queue of "lateness". Don't worry about those initial
  1645. zeros because the first entry will always be zero */
  1646. for (x=0;x<MEMORY_SIZE - 1;x++)
  1647. iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
  1648. /* Add a history entry for this one */
  1649. iaxs[fr->callno]->history[x] = ms;
  1650. }
  1651. else
  1652. ms = 0;
  1653. /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
  1654. if ( (!fromtrunk) && (iaxs[fr->callno]->rxcore.tv_sec || iaxs[fr->callno]->rxcore.tv_usec) ) {
  1655. fr->af.delivery.tv_sec = iaxs[fr->callno]->rxcore.tv_sec;
  1656. fr->af.delivery.tv_usec = iaxs[fr->callno]->rxcore.tv_usec;
  1657. fr->af.delivery.tv_sec += fr->ts / 1000;
  1658. fr->af.delivery.tv_usec += (fr->ts % 1000) * 1000;
  1659. if (fr->af.delivery.tv_usec >= 1000000) {
  1660. fr->af.delivery.tv_usec -= 1000000;
  1661. fr->af.delivery.tv_sec += 1;
  1662. }
  1663. }
  1664. else {
  1665. #if 0
  1666. if (reallydeliver)
  1667. ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
  1668. #endif
  1669. fr->af.delivery.tv_sec = 0;
  1670. fr->af.delivery.tv_usec = 0;
  1671. }
  1672. /* Initialize the minimum to reasonable values. It's too much
  1673. work to do the same for the maximum, repeatedly */
  1674. min=iaxs[fr->callno]->history[0];
  1675. for (z=0;z < iax2_dropcount + 1;z++) {
  1676. /* Start very optimistic ;-) */
  1677. max=-999999999;
  1678. for (x=0;x<MEMORY_SIZE;x++) {
  1679. if (max < iaxs[fr->callno]->history[x]) {
  1680. /* We have a candidate new maximum value. Make
  1681. sure it's not in our drop list */
  1682. match = 0;
  1683. for (y=0;!match && (y<z);y++)
  1684. match |= (drops[y] == x);
  1685. if (!match) {
  1686. /* It's not in our list, use it as the new maximum */
  1687. max = iaxs[fr->callno]->history[x];
  1688. maxone = x;
  1689. }
  1690. }
  1691. if (!z) {
  1692. /* On our first pass, find the minimum too */
  1693. if (min > iaxs[fr->callno]->history[x])
  1694. min = iaxs[fr->callno]->history[x];
  1695. }
  1696. }
  1697. #if 1
  1698. drops[z] = maxone;
  1699. #endif
  1700. }
  1701. /* Just for reference, keep the "jitter" value, the difference between the
  1702. earliest and the latest. */
  1703. if (max >= min)
  1704. iaxs[fr->callno]->jitter = max - min;
  1705. /* IIR filter for keeping track of historic jitter, but always increase
  1706. historic jitter immediately for increase */
  1707. if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
  1708. iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
  1709. else
  1710. iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
  1711. iaxs[fr->callno]->historicjitter;
  1712. /* If our jitter buffer is too big (by a significant margin), then we slowly
  1713. shrink it to avoid letting the change be perceived */
  1714. if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
  1715. iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
  1716. /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
  1717. /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
  1718. in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
  1719. disruption. Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
  1720. if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
  1721. iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
  1722. /* If our jitter buffer is smaller than our maximum delay, grow the jitter
  1723. buffer immediately to accomodate it (and a little more). */
  1724. if (max > iaxs[fr->callno]->jitterbuffer)
  1725. iaxs[fr->callno]->jitterbuffer = max
  1726. /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
  1727. /* If the caller just wanted us to update, return now */
  1728. if (!reallydeliver)
  1729. return 0;
  1730. /* Subtract the lateness from our jitter buffer to know how long to wait
  1731. before sending our packet. */
  1732. delay = iaxs[fr->callno]->jitterbuffer - ms;
  1733. /* Whatever happens, no frame waits longer than maxjitterbuffer */
  1734. if (delay > maxjitterbuffer)
  1735. delay = maxjitterbuffer;
  1736. /* If jitter buffer is disabled then just pretend the frame is "right on time" */
  1737. /* If frame came from trunk, also don't do any delay */
  1738. if ( (!iaxs[fr->callno]->usejitterbuf) || fromtrunk )
  1739. delay = 0;
  1740. if (option_debug) {
  1741. /* Log jitter stats for possible offline analysis */
  1742. ast_log(LOG_DEBUG, "Jitter: call=%d ts=%d orig=%d last=%d %s: min=%d max=%d jb=%d %+d lateness=%d jbdelay=%d jitter=%d historic=%d\n",
  1743. fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
  1744. (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
  1745. min, max, iaxs[fr->callno]->jitterbuffer,
  1746. iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
  1747. ms, delay,
  1748. iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
  1749. }
  1750. if (delay < 1) {
  1751. /* Don't deliver it more than 4 ms late */
  1752. if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
  1753. if (option_debug)
  1754. ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
  1755. __do_deliver(fr);
  1756. } else {
  1757. if (option_debug)
  1758. ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
  1759. /* Free our iax frame */
  1760. iax2_frame_free(fr);
  1761. }
  1762. } else {
  1763. if (option_debug)
  1764. ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
  1765. fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
  1766. }
  1767. return 0;
  1768. }
  1769. static int iax2_transmit(struct iax_frame *fr)
  1770. {
  1771. /* Lock the queue and place this packet at the end */
  1772. fr->next = NULL;
  1773. fr->prev = NULL;
  1774. /* By setting this to 0, the network thread will send it for us, and
  1775. queue retransmission if necessary */
  1776. fr->sentyet = 0;
  1777. ast_mutex_lock(&iaxq.lock);
  1778. if (!iaxq.head) {
  1779. /* Empty queue */
  1780. iaxq.head = fr;
  1781. iaxq.tail = fr;
  1782. } else {
  1783. /* Double link */
  1784. iaxq.tail->next = fr;
  1785. fr->prev = iaxq.tail;
  1786. iaxq.tail = fr;
  1787. }
  1788. iaxq.count++;
  1789. ast_mutex_unlock(&iaxq.lock);
  1790. /* Wake up the network thread */
  1791. pthread_kill(netthreadid, SIGURG);
  1792. return 0;
  1793. }
  1794. static int iax2_digit(struct ast_channel *c, char digit)
  1795. {
  1796. return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
  1797. }
  1798. static int iax2_sendtext(struct ast_channel *c, char *text)
  1799. {
  1800. return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_TEXT,
  1801. 0, 0, text, strlen(text) + 1, -1);
  1802. }
  1803. static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
  1804. {
  1805. return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
  1806. }
  1807. static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
  1808. {
  1809. return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
  1810. }
  1811. static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
  1812. {
  1813. unsigned short callno = PTR_TO_CALLNO(newchan->pvt->pvt);
  1814. ast_mutex_lock(&iaxsl[callno]);
  1815. if (iaxs[callno])
  1816. iaxs[callno]->owner = newchan;
  1817. else
  1818. ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
  1819. ast_mutex_unlock(&iaxsl[callno]);
  1820. return 0;
  1821. }
  1822. #ifdef MYSQL_FRIENDS
  1823. static void mysql_update_peer(char *peer, struct sockaddr_in *sin)
  1824. {
  1825. if (mysql && (strlen(peer) < 128)) {
  1826. char query[512];
  1827. char *name;
  1828. char iabuf[INET_ADDRSTRLEN];
  1829. time_t nowtime;
  1830. name = alloca(strlen(peer) * 2 + 1);
  1831. time(&nowtime);
  1832. mysql_real_escape_string(mysql, name, peer, strlen(peer));
  1833. snprintf(query, sizeof(query), "UPDATE iaxfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"",
  1834. ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
  1835. ast_mutex_lock(&mysqllock);
  1836. if (mysql_real_query(mysql, query, strlen(query)))
  1837. ast_log(LOG_WARNING, "Unable to update database\n");
  1838. ast_mutex_unlock(&mysqllock);
  1839. }
  1840. }
  1841. static struct iax2_peer *mysql_peer(char *peer)
  1842. {
  1843. struct iax2_peer *p;
  1844. int success = 0;
  1845. p = malloc(sizeof(struct iax2_peer));
  1846. memset(p, 0, sizeof(struct iax2_peer));
  1847. if (mysql && (strlen(peer) < 128)) {
  1848. char query[512];
  1849. char *name;
  1850. int numfields, x;
  1851. int port;
  1852. time_t regseconds, nowtime;
  1853. MYSQL_RES *result;
  1854. MYSQL_FIELD *fields;
  1855. MYSQL_ROW rowval;
  1856. name = alloca(strlen(peer) * 2 + 1);
  1857. mysql_real_escape_string(mysql, name, peer, strlen(peer));
  1858. snprintf(query, sizeof(query), "SELECT name, secret, context, ipaddr, port, regseconds FROM iaxfriends WHERE name=\"%s\"", name);
  1859. ast_mutex_lock(&mysqllock);
  1860. mysql_query(mysql, query);
  1861. if ((result = mysql_store_result(mysql))) {
  1862. if ((rowval = mysql_fetch_row(result))) {
  1863. numfields = mysql_num_fields(result);
  1864. fields = mysql_fetch_fields(result);
  1865. success = 1;
  1866. for (x=0;x<numfields;x++) {
  1867. if (rowval[x]) {
  1868. if (!strcasecmp(fields[x].name, "secret")) {
  1869. strncpy(p->secret, rowval[x], sizeof(p->secret) - 1);
  1870. } else if (!strcasecmp(fields[x].name, "context")) {
  1871. strncpy(p->context, rowval[x], sizeof(p->context) - 1);
  1872. } else if (!strcasecmp(fields[x].name, "ipaddr")) {
  1873. inet_aton(rowval[x], &p->addr.sin_addr);
  1874. } else if (!strcasecmp(fields[x].name, "port")) {
  1875. if (sscanf(rowval[x], "%i", &port) != 1)
  1876. port = 0;
  1877. p->addr.sin_port = htons(port);
  1878. } else if (!strcasecmp(fields[x].name, "regseconds")) {
  1879. if (sscanf(rowval[x], "%li", &regseconds) != 1)
  1880. regseconds = 0;
  1881. }
  1882. }
  1883. }
  1884. time(&nowtime);
  1885. if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE)
  1886. memset(&p->addr, 0, sizeof(p->addr));
  1887. }
  1888. mysql_free_result(result);
  1889. result = NULL;
  1890. }
  1891. ast_mutex_unlock(&mysqllock);
  1892. }
  1893. if (!success) {
  1894. free(p);
  1895. p = NULL;
  1896. } else {
  1897. strncpy(p->name, peer, sizeof(p->name) - 1);
  1898. p->dynamic = 1;
  1899. p->temponly = 1;
  1900. p->expire = -1;
  1901. p->capability = iax2_capability;
  1902. p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
  1903. }
  1904. return p;
  1905. }
  1906. static struct iax2_user *mysql_user(char *user)
  1907. {
  1908. struct iax2_user *p;
  1909. struct iax2_context *con;
  1910. int success = 0;
  1911. p = malloc(sizeof(struct iax2_user));
  1912. memset(p, 0, sizeof(struct iax2_user));
  1913. con = malloc(sizeof(struct iax2_context));
  1914. memset(con, 0, sizeof(struct iax2_context));
  1915. strncpy(con->context, "default", sizeof(con->context) - 1);
  1916. p->contexts = con;
  1917. if (mysql && (strlen(user) < 128)) {
  1918. char query[512];
  1919. char *name;
  1920. int numfields, x;
  1921. MYSQL_RES *result;
  1922. MYSQL_FIELD *fields;
  1923. MYSQL_ROW rowval;
  1924. name = alloca(strlen(user) * 2 + 1);
  1925. mysql_real_escape_string(mysql, name, user, strlen(user));
  1926. snprintf(query, sizeof(query), "SELECT name, secret, context, ipaddr, port, regseconds, accountcode FROM iaxfriends WHERE name=\"%s\"", name);
  1927. ast_mutex_lock(&mysqllock);
  1928. mysql_query(mysql, query);
  1929. if ((result = mysql_store_result(mysql))) {
  1930. if ((rowval = mysql_fetch_row(result))) {
  1931. numfields = mysql_num_fields(result);
  1932. fields = mysql_fetch_fields(result);
  1933. success = 1;
  1934. for (x=0;x<numfields;x++) {
  1935. if (rowval[x]) {
  1936. if (!strcasecmp(fields[x].name, "secret")) {
  1937. strncpy(p->secret, rowval[x], sizeof(p->secret) - 1);
  1938. } else if (!strcasecmp(fields[x].name, "context")) {
  1939. strncpy(p->contexts->context, rowval[x], sizeof(p->contexts->context) - 1);
  1940. } else if (!strcasecmp(fields[x].name, "accountcode")) {
  1941. strncpy(p->accountcode, rowval[x], sizeof(p->accountcode) - 1);
  1942. }
  1943. }
  1944. }
  1945. }
  1946. mysql_free_result(result);
  1947. result = NULL;
  1948. }
  1949. ast_mutex_unlock(&mysqllock);
  1950. }
  1951. if (!success) {
  1952. if (p->contexts)
  1953. free(p->contexts);
  1954. free(p);
  1955. p = NULL;
  1956. } else {
  1957. strncpy(p->name, user, sizeof(p->name) - 1);
  1958. p->temponly = 1;
  1959. p->capability = iax2_capability;
  1960. p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
  1961. }
  1962. return p;
  1963. }
  1964. #endif /* MYSQL_FRIENDS */
  1965. static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, int *maxtime, char *peer, char *context, int *trunk, int *notransfer, int *usejitterbuf, char *username, int usernlen, char *secret, int seclen, int *ofound, char *peercontext)
  1966. {
  1967. struct ast_hostent ahp; struct hostent *hp;
  1968. struct iax2_peer *p;
  1969. int found=0;
  1970. if (sendani)
  1971. *sendani = 0;
  1972. if (maxtime)
  1973. *maxtime = 0;
  1974. if (trunk)
  1975. *trunk = 0;
  1976. sin->sin_family = AF_INET;
  1977. ast_mutex_lock(&peerl.lock);
  1978. p = peerl.peers;
  1979. while(p) {
  1980. if (!strcasecmp(p->name, peer)) {
  1981. break;
  1982. }
  1983. p = p->next;
  1984. }
  1985. ast_mutex_unlock(&peerl.lock);
  1986. #ifdef MYSQL_FRIENDS
  1987. if (!p)
  1988. p = mysql_peer(peer);
  1989. #endif
  1990. if (p) {
  1991. found++;
  1992. if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
  1993. (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
  1994. if (sendani)
  1995. *sendani = p->sendani; /* Whether we transmit ANI */
  1996. if (maxtime)
  1997. *maxtime = p->maxms; /* Max time they should take */
  1998. if (context)
  1999. strncpy(context, p->context, AST_MAX_EXTENSION - 1);
  2000. if (peercontext)
  2001. strncpy(peercontext, p->peercontext, AST_MAX_EXTENSION - 1);
  2002. if (trunk)
  2003. *trunk = p->trunk;
  2004. if (capability)
  2005. *capability = p->capability;
  2006. if (username)
  2007. strncpy(username, p->username, usernlen);
  2008. if (secret)
  2009. strncpy(secret, p->secret, seclen); /* safe */
  2010. if (p->addr.sin_addr.s_addr) {
  2011. sin->sin_addr = p->addr.sin_addr;
  2012. sin->sin_port = p->addr.sin_port;
  2013. } else {
  2014. sin->sin_addr = p->defaddr.sin_addr;
  2015. sin->sin_port = p->defaddr.sin_port;
  2016. }
  2017. if (notransfer)
  2018. *notransfer=p->notransfer;
  2019. if (usejitterbuf)
  2020. *usejitterbuf=p->usejitterbuf;
  2021. } else {
  2022. if (p->temponly)
  2023. free(p);
  2024. p = NULL;
  2025. }
  2026. }
  2027. if (ofound)
  2028. *ofound = found;
  2029. if (!p && !found) {
  2030. hp = ast_gethostbyname(peer, &ahp);
  2031. if (hp) {
  2032. memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
  2033. sin->sin_port = htons(IAX_DEFAULT_PORTNO);
  2034. return 0;
  2035. } else {
  2036. ast_log(LOG_WARNING, "No such host: %s\n", peer);
  2037. return -1;
  2038. }
  2039. } else if (!p)
  2040. return -1;
  2041. if (p->temponly)
  2042. free(p);
  2043. return 0;
  2044. }
  2045. static int auto_congest(void *nothing)
  2046. {
  2047. int callno = PTR_TO_CALLNO(nothing);
  2048. struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
  2049. ast_mutex_lock(&iaxsl[callno]);
  2050. if (iaxs[callno]) {
  2051. iaxs[callno]->initid = -1;
  2052. iax2_queue_frame(callno, &f);
  2053. ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
  2054. }
  2055. ast_mutex_unlock(&iaxsl[callno]);
  2056. return 0;
  2057. }
  2058. static unsigned int iax2_datetime(void)
  2059. {
  2060. time_t t;
  2061. struct tm tm;
  2062. unsigned int tmp;
  2063. time(&t);
  2064. localtime_r(&t, &tm);
  2065. tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
  2066. tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
  2067. tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
  2068. tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
  2069. tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
  2070. tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
  2071. return tmp;
  2072. }
  2073. static int iax2_call(struct ast_channel *c, char *dest, int timeout)
  2074. {
  2075. struct sockaddr_in sin;
  2076. char host[256];
  2077. char *rdest;
  2078. char *rcontext;
  2079. char *username;
  2080. char *secret = NULL;
  2081. char *hname;
  2082. char cid[256] = "";
  2083. char *l=NULL, *n=NULL;
  2084. struct iax_ie_data ied;
  2085. char myrdest [5] = "s";
  2086. char context[AST_MAX_EXTENSION] ="";
  2087. char peercontext[AST_MAX_EXTENSION] ="";
  2088. char *portno = NULL;
  2089. char *opts = "";
  2090. unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
  2091. char *stringp=NULL;
  2092. char storedusern[80], storedsecret[80];
  2093. if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
  2094. ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
  2095. return -1;
  2096. }
  2097. strncpy(host, dest, sizeof(host)-1);
  2098. stringp=host;
  2099. strsep(&stringp, "/");
  2100. /* If no destination extension specified, use 's' */
  2101. rdest = strsep(&stringp, "/");
  2102. if (!rdest)
  2103. rdest = myrdest;
  2104. else {
  2105. /* Check for trailing options */
  2106. opts = strsep(&stringp, "/");
  2107. if (!opts)
  2108. opts = "";
  2109. }
  2110. stringp=rdest;
  2111. strsep(&stringp, "@");
  2112. rcontext = strsep(&stringp, "@");
  2113. stringp=host;
  2114. strsep(&stringp, "@");
  2115. username = strsep(&stringp, "@");
  2116. if (username) {
  2117. /* Really the second argument is the host, not the username */
  2118. hname = username;
  2119. username = host;
  2120. } else {
  2121. hname = host;
  2122. }
  2123. if (username) {
  2124. stringp=username;
  2125. username = strsep(&stringp, ":");
  2126. secret = strsep(&stringp, ":");
  2127. }
  2128. stringp=hname;
  2129. if (strsep(&stringp, ":")) {
  2130. stringp=hname;
  2131. strsep(&stringp, ":");
  2132. portno = strsep(&stringp, ":");
  2133. }
  2134. if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL, NULL, NULL, storedusern, sizeof(storedusern) - 1, storedsecret, sizeof(storedsecret) - 1, NULL, peercontext)) {
  2135. ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
  2136. return -1;
  2137. }
  2138. /* Keep track of the context for outgoing calls too */
  2139. strncpy(c->context, context, sizeof(c->context) - 1);
  2140. if (portno) {
  2141. sin.sin_port = htons(atoi(portno));
  2142. }
  2143. if (c->callerid) {
  2144. strncpy(cid, c->callerid, sizeof(cid) - 1);
  2145. ast_callerid_parse(cid, &n, &l);
  2146. if (l)
  2147. ast_shrink_phone_number(l);
  2148. }
  2149. /* Now build request */
  2150. memset(&ied, 0, sizeof(ied));
  2151. /* On new call, first IE MUST be IAX version of caller */
  2152. iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
  2153. iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
  2154. if (strchr(opts, 'a')) {
  2155. /* Request auto answer */
  2156. iax_ie_append(&ied, IAX_IE_AUTOANSWER);
  2157. }
  2158. if (l)
  2159. iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
  2160. if (n)
  2161. iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
  2162. if (iaxs[callno]->sendani && c->ani) {
  2163. l = n = NULL;
  2164. strncpy(cid, c->ani, sizeof(cid) - 1);
  2165. ast_callerid_parse(cid, &n, &l);
  2166. if (l) {
  2167. ast_shrink_phone_number(l);
  2168. iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, l);
  2169. }
  2170. }
  2171. if (c->language && !ast_strlen_zero(c->language))
  2172. iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
  2173. if (c->dnid && !ast_strlen_zero(c->dnid))
  2174. iax_ie_append_str(&ied, IAX_IE_DNID, c->dnid);
  2175. if (rcontext)
  2176. iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
  2177. else if (strlen(peercontext))
  2178. iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, peercontext);
  2179. if (!username && !ast_strlen_zero(storedusern))
  2180. username = storedusern;
  2181. if (username)
  2182. iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
  2183. if (!secret && !ast_strlen_zero(storedsecret))
  2184. secret = storedsecret;
  2185. ast_mutex_lock(&iaxsl[callno]);
  2186. if (!ast_strlen_zero(c->context))
  2187. strncpy(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context) - 1);
  2188. if (username)
  2189. strncpy(iaxs[callno]->username, username, sizeof(iaxs[callno]->username)-1);
  2190. if (secret) {
  2191. if (secret[0] == '[') {
  2192. /* This is an RSA key, not a normal secret */
  2193. strncpy(iaxs[callno]->outkey, secret + 1, sizeof(iaxs[callno]->outkey)-1);
  2194. if (!ast_strlen_zero(iaxs[callno]->outkey)) {
  2195. iaxs[callno]->outkey[strlen(iaxs[callno]->outkey) - 1] = '\0';
  2196. }
  2197. } else
  2198. strncpy(iaxs[callno]->secret, secret, sizeof(iaxs[callno]->secret)-1);
  2199. }
  2200. iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
  2201. iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
  2202. iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
  2203. iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime());
  2204. /* Transmit the string in a "NEW" request */
  2205. #if 0
  2206. /* XXX We have no equivalent XXX */
  2207. if (option_verbose > 2)
  2208. ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
  2209. #endif
  2210. if (iaxs[callno]->maxtime) {
  2211. /* Initialize pingtime and auto-congest time */
  2212. iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
  2213. iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
  2214. }
  2215. send_command(iaxs[callno], AST_FRAME_IAX,
  2216. IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
  2217. ast_mutex_unlock(&iaxsl[callno]);
  2218. ast_setstate(c, AST_STATE_RINGING);
  2219. return 0;
  2220. }
  2221. static int iax2_hangup(struct ast_channel *c)
  2222. {
  2223. unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
  2224. int alreadygone;
  2225. ast_mutex_lock(&iaxsl[callno]);
  2226. if (callno && iaxs[callno]) {
  2227. ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
  2228. alreadygone = iaxs[callno]->alreadygone;
  2229. /* Send the hangup unless we have had a transmission error or are already gone */
  2230. if (!iaxs[callno]->error && !alreadygone)
  2231. send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
  2232. /* Explicitly predestroy it */
  2233. iax2_predestroy_nolock(callno);
  2234. /* If we were already gone to begin with, destroy us now */
  2235. if (alreadygone) {
  2236. ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
  2237. iax2_destroy_nolock(callno);
  2238. }
  2239. }
  2240. ast_mutex_unlock(&iaxsl[callno]);
  2241. if (option_verbose > 2)
  2242. ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
  2243. return 0;
  2244. }
  2245. static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
  2246. {
  2247. struct ast_option_header *h;
  2248. int res;
  2249. h = malloc(datalen + sizeof(struct ast_option_header));
  2250. if (h) {
  2251. h->flag = AST_OPTION_FLAG_REQUEST;
  2252. h->option = htons(option);
  2253. memcpy(h->data, data, datalen);
  2254. res = send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_CONTROL,
  2255. AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
  2256. free(h);
  2257. return res;
  2258. } else
  2259. ast_log(LOG_WARNING, "Out of memory\n");
  2260. return -1;
  2261. }
  2262. static struct ast_frame *iax2_read(struct ast_channel *c)
  2263. {
  2264. static struct ast_frame f = { AST_FRAME_NULL, };
  2265. ast_log(LOG_NOTICE, "I should never be called!\n");
  2266. return &f;
  2267. }
  2268. static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
  2269. {
  2270. int res;
  2271. struct iax_ie_data ied0;
  2272. struct iax_ie_data ied1;
  2273. unsigned int transferid = rand();
  2274. memset(&ied0, 0, sizeof(ied0));
  2275. iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
  2276. iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
  2277. iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
  2278. memset(&ied1, 0, sizeof(ied1));
  2279. iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
  2280. iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
  2281. iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
  2282. res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
  2283. if (res)
  2284. return -1;
  2285. res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
  2286. if (res)
  2287. return -1;
  2288. iaxs[callno0]->transferring = TRANSFER_BEGIN;
  2289. iaxs[callno1]->transferring = TRANSFER_BEGIN;
  2290. return 0;
  2291. }
  2292. static void lock_both(unsigned short callno0, unsigned short callno1)
  2293. {
  2294. ast_mutex_lock(&iaxsl[callno0]);
  2295. while (ast_mutex_trylock(&iaxsl[callno1])) {
  2296. ast_mutex_unlock(&iaxsl[callno0]);
  2297. usleep(10);
  2298. ast_mutex_lock(&iaxsl[callno0]);
  2299. }
  2300. }
  2301. static void unlock_both(unsigned short callno0, unsigned short callno1)
  2302. {
  2303. ast_mutex_unlock(&iaxsl[callno1]);
  2304. ast_mutex_unlock(&iaxsl[callno0]);
  2305. }
  2306. static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
  2307. {
  2308. struct ast_channel *cs[3];
  2309. struct ast_channel *who;
  2310. int to = -1;
  2311. int res = -1;
  2312. int transferstarted=0;
  2313. struct ast_frame *f;
  2314. unsigned short callno0 = PTR_TO_CALLNO(c0->pvt->pvt);
  2315. unsigned short callno1 = PTR_TO_CALLNO(c1->pvt->pvt);
  2316. struct timeval waittimer = {0, 0}, tv;
  2317. lock_both(callno0, callno1);
  2318. /* Put them in native bridge mode */
  2319. iaxs[callno0]->bridgecallno = callno1;
  2320. iaxs[callno1]->bridgecallno = callno0;
  2321. unlock_both(callno0, callno1);
  2322. /* If not, try to bridge until we can execute a transfer, if we can */
  2323. cs[0] = c0;
  2324. cs[1] = c1;
  2325. for (/* ever */;;) {
  2326. /* Check in case we got masqueraded into */
  2327. if ((c0->type != type) || (c1->type != type)) {
  2328. if (option_verbose > 2)
  2329. ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
  2330. /* Remove from native mode */
  2331. if (c0->type == type) {
  2332. ast_mutex_lock(&iaxsl[callno0]);
  2333. iaxs[callno0]->bridgecallno = 0;
  2334. ast_mutex_unlock(&iaxsl[callno0]);
  2335. }
  2336. if (c1->type == type) {
  2337. ast_mutex_lock(&iaxsl[callno1]);
  2338. iaxs[callno1]->bridgecallno = 0;
  2339. ast_mutex_unlock(&iaxsl[callno1]);
  2340. }
  2341. return -2;
  2342. }
  2343. if (c0->nativeformats != c1->nativeformats) {
  2344. ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
  2345. /* Remove from native mode */
  2346. lock_both(callno0, callno1);
  2347. iaxs[callno0]->bridgecallno = 0;
  2348. iaxs[callno1]->bridgecallno = 0;
  2349. unlock_both(callno0, callno1);
  2350. return -2;
  2351. }
  2352. /* check if transfered and if we really want native bridging */
  2353. if (!transferstarted && !iaxs[callno0]->notransfer && !iaxs[callno1]->notransfer) {
  2354. /* Try the transfer */
  2355. if (iax2_start_transfer(callno0, callno1))
  2356. ast_log(LOG_WARNING, "Unable to start the transfer\n");
  2357. transferstarted = 1;
  2358. }
  2359. if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
  2360. /* Call has been transferred. We're no longer involved */
  2361. gettimeofday(&tv, NULL);
  2362. if (!waittimer.tv_sec && !waittimer.tv_usec) {
  2363. waittimer.tv_sec = tv.tv_sec;
  2364. waittimer.tv_usec = tv.tv_usec;
  2365. } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
  2366. c0->_softhangup |= AST_SOFTHANGUP_DEV;
  2367. c1->_softhangup |= AST_SOFTHANGUP_DEV;
  2368. *fo = NULL;
  2369. *rc = c0;
  2370. res = 0;
  2371. break;
  2372. }
  2373. }
  2374. to = 1000;
  2375. who = ast_waitfor_n(cs, 2, &to);
  2376. if (!who) {
  2377. if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
  2378. res = -1;
  2379. break;
  2380. }
  2381. continue;
  2382. }
  2383. f = ast_read(who);
  2384. if (!f) {
  2385. *fo = NULL;
  2386. *rc = who;
  2387. res = 0;
  2388. break;
  2389. }
  2390. if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
  2391. *fo = f;
  2392. *rc = who;
  2393. res = 0;
  2394. break;
  2395. }
  2396. if ((f->frametype == AST_FRAME_VOICE) ||
  2397. (f->frametype == AST_FRAME_TEXT) ||
  2398. (f->frametype == AST_FRAME_VIDEO) ||
  2399. (f->frametype == AST_FRAME_IMAGE) ||
  2400. (f->frametype == AST_FRAME_DTMF)) {
  2401. if ((f->frametype == AST_FRAME_DTMF) &&
  2402. (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
  2403. if ((who == c0)) {
  2404. if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
  2405. *rc = c0;
  2406. *fo = f;
  2407. /* Take out of conference mode */
  2408. res = 0;
  2409. /* Remove from native mode */
  2410. break;
  2411. } else
  2412. goto tackygoto;
  2413. } else
  2414. if ((who == c1)) {
  2415. if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
  2416. *rc = c1;
  2417. *fo = f;
  2418. res = 0;
  2419. /* Remove from native mode */
  2420. break;
  2421. } else
  2422. goto tackygoto;
  2423. }
  2424. } else {
  2425. #if 0
  2426. ast_log(LOG_DEBUG, "Read from %s\n", who->name);
  2427. if (who == last)
  2428. ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
  2429. last = who;
  2430. #endif
  2431. tackygoto:
  2432. if (who == c0)
  2433. ast_write(c1, f);
  2434. else
  2435. ast_write(c0, f);
  2436. }
  2437. ast_frfree(f);
  2438. } else
  2439. ast_frfree(f);
  2440. /* Swap who gets priority */
  2441. cs[2] = cs[0];
  2442. cs[0] = cs[1];
  2443. cs[1] = cs[2];
  2444. }
  2445. lock_both(callno0, callno1);
  2446. if(iaxs[callno0])
  2447. iaxs[callno0]->bridgecallno = 0;
  2448. if(iaxs[callno1])
  2449. iaxs[callno1]->bridgecallno = 0;
  2450. unlock_both(callno0, callno1);
  2451. return res;
  2452. }
  2453. static int iax2_answer(struct ast_channel *c)
  2454. {
  2455. unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
  2456. if (option_debug)
  2457. ast_log(LOG_DEBUG, "Answering\n");
  2458. return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
  2459. }
  2460. static int iax2_indicate(struct ast_channel *c, int condition)
  2461. {
  2462. unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
  2463. if (option_debug)
  2464. ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
  2465. return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
  2466. }
  2467. static int iax2_transfer(struct ast_channel *c, char *dest)
  2468. {
  2469. unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
  2470. struct iax_ie_data ied;
  2471. char tmp[256] = "", *context;
  2472. strncpy(tmp, dest, sizeof(tmp) - 1);
  2473. context = strchr(tmp, '@');
  2474. if (context) {
  2475. *context = '\0';
  2476. context++;
  2477. }
  2478. memset(&ied, 0, sizeof(ied));
  2479. iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
  2480. if (context)
  2481. iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
  2482. if (option_debug)
  2483. ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
  2484. return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
  2485. }
  2486. static int iax2_write(struct ast_channel *c, struct ast_frame *f);
  2487. static int iax2_getpeertrunk(struct sockaddr_in sin)
  2488. {
  2489. struct iax2_peer *peer;
  2490. int res = 0;
  2491. ast_mutex_lock(&peerl.lock);
  2492. peer = peerl.peers;
  2493. while(peer) {
  2494. if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
  2495. (peer->addr.sin_port == sin.sin_port)) {
  2496. res = peer->trunk;
  2497. break;
  2498. }
  2499. peer = peer->next;
  2500. }
  2501. ast_mutex_unlock(&peerl.lock);
  2502. return res;
  2503. }
  2504. static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
  2505. {
  2506. struct ast_channel *tmp;
  2507. struct chan_iax2_pvt *i;
  2508. /* Don't hold call lock */
  2509. ast_mutex_unlock(&iaxsl[callno]);
  2510. tmp = ast_channel_alloc(1);
  2511. ast_mutex_lock(&iaxsl[callno]);
  2512. i = iaxs[callno];
  2513. if (i && tmp) {
  2514. if (!ast_strlen_zero(i->username))
  2515. snprintf(tmp->name, sizeof(tmp->name), "IAX2/%s@%s/%d", i->username, i->host, i->callno);
  2516. else
  2517. snprintf(tmp->name, sizeof(tmp->name), "IAX2/%s/%d", i->host, i->callno);
  2518. tmp->type = type;
  2519. /* We can support any format by default, until we get restricted */
  2520. tmp->nativeformats = capability;
  2521. tmp->readformat = ast_best_codec(capability);
  2522. tmp->writeformat = ast_best_codec(capability);
  2523. tmp->pvt->pvt = CALLNO_TO_PTR(i->callno);
  2524. tmp->pvt->send_digit = iax2_digit;
  2525. tmp->pvt->send_text = iax2_sendtext;
  2526. tmp->pvt->send_image = iax2_sendimage;
  2527. tmp->pvt->send_html = iax2_sendhtml;
  2528. tmp->pvt->call = iax2_call;
  2529. tmp->pvt->hangup = iax2_hangup;
  2530. tmp->pvt->answer = iax2_answer;
  2531. tmp->pvt->read = iax2_read;
  2532. tmp->pvt->write = iax2_write;
  2533. tmp->pvt->write_video = iax2_write;
  2534. tmp->pvt->indicate = iax2_indicate;
  2535. tmp->pvt->setoption = iax2_setoption;
  2536. tmp->pvt->bridge = iax2_bridge;
  2537. tmp->pvt->transfer = iax2_transfer;
  2538. if (!ast_strlen_zero(i->callerid))
  2539. tmp->callerid = strdup(i->callerid);
  2540. if (!ast_strlen_zero(i->ani))
  2541. tmp->ani = strdup(i->ani);
  2542. if (!ast_strlen_zero(i->language))
  2543. strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
  2544. if (!ast_strlen_zero(i->dnid))
  2545. tmp->dnid = strdup(i->dnid);
  2546. if (!ast_strlen_zero(i->accountcode))
  2547. strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
  2548. if (i->amaflags)
  2549. tmp->amaflags = i->amaflags;
  2550. strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
  2551. strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
  2552. tmp->adsicpe = i->peeradsicpe;
  2553. tmp->pvt->fixup = iax2_fixup;
  2554. i->owner = tmp;
  2555. i->capability = capability;
  2556. ast_setstate(tmp, state);
  2557. ast_mutex_lock(&usecnt_lock);
  2558. usecnt++;
  2559. ast_mutex_unlock(&usecnt_lock);
  2560. ast_update_use_count();
  2561. if (state != AST_STATE_DOWN) {
  2562. if (ast_pbx_start(tmp)) {
  2563. ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
  2564. ast_hangup(tmp);
  2565. tmp = NULL;
  2566. }
  2567. }
  2568. }
  2569. return tmp;
  2570. }
  2571. static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
  2572. {
  2573. unsigned long int mssincetx; /* unsigned to handle overflows */
  2574. long int ms, pred;
  2575. tpeer->trunkact = *tv;
  2576. mssincetx = (tv->tv_sec - tpeer->lasttxtime.tv_sec) * 1000 +
  2577. (1000000 + tv->tv_usec - tpeer->lasttxtime.tv_usec) / 1000 - 1000;
  2578. if (mssincetx > 5000 || (!tpeer->txtrunktime.tv_sec && !tpeer->txtrunktime.tv_usec)) {
  2579. /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
  2580. tpeer->txtrunktime.tv_sec = tv->tv_sec;
  2581. tpeer->txtrunktime.tv_usec = tv->tv_usec;
  2582. tpeer->lastsent = 999999;
  2583. }
  2584. /* Update last transmit time now */
  2585. tpeer->lasttxtime.tv_sec = tv->tv_sec;
  2586. tpeer->lasttxtime.tv_usec = tv->tv_usec;
  2587. /* Calculate ms offset */
  2588. ms = (tv->tv_sec - tpeer->txtrunktime.tv_sec) * 1000 +
  2589. (1000000 + tv->tv_usec - tpeer->txtrunktime.tv_usec) / 1000 - 1000;
  2590. /* Predict from last value */
  2591. pred = tpeer->lastsent + sampms;
  2592. if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
  2593. ms = pred;
  2594. /* We never send the same timestamp twice, so fudge a little if we must */
  2595. if (ms == tpeer->lastsent)
  2596. ms = tpeer->lastsent + 1;
  2597. tpeer->lastsent = ms;
  2598. return ms;
  2599. }
  2600. static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
  2601. {
  2602. long ms; /* NOT unsigned */
  2603. if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
  2604. /* Initialize rxcore time if appropriate */
  2605. gettimeofday(&iaxs[callno]->rxcore, NULL);
  2606. /* Round to nearest 20ms so traces look pretty */
  2607. iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
  2608. }
  2609. /* Calculate difference between trunk and channel */
  2610. ms = (tv->tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 +
  2611. (1000000 + tv->tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000 - 1000;
  2612. /* Return as the sum of trunk time and the difference between trunk and real time */
  2613. return ms + ts;
  2614. }
  2615. static void add_ms(struct timeval *tv, int ms) {
  2616. tv->tv_usec += ms * 1000;
  2617. if(tv->tv_usec > 1000000) {
  2618. tv->tv_usec -= 1000000;
  2619. tv->tv_sec++;
  2620. }
  2621. if(tv->tv_usec < 0) {
  2622. tv->tv_usec += 1000000;
  2623. tv->tv_sec--;
  2624. }
  2625. }
  2626. static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
  2627. {
  2628. struct timeval tv;
  2629. int ms;
  2630. int voice = 0;
  2631. int genuine = 0;
  2632. struct timeval *delivery = NULL;
  2633. /* What sort of frame do we have?: voice is self-explanatory
  2634. "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
  2635. non-genuine frames are CONTROL frames [ringing etc], DTMF
  2636. The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
  2637. the others need a timestamp slaved to the voice frames so that they go in sequence
  2638. */
  2639. if (f) {
  2640. if (f->frametype == AST_FRAME_VOICE) {
  2641. voice = 1;
  2642. delivery = &f->delivery;
  2643. } else if (f->frametype == AST_FRAME_IAX) {
  2644. genuine = 1;
  2645. } else if (f->frametype == AST_FRAME_CNG) {
  2646. p->notsilenttx = 0;
  2647. }
  2648. }
  2649. if (!p->offset.tv_sec && !p->offset.tv_usec) {
  2650. gettimeofday(&p->offset, NULL);
  2651. /* Round to nearest 20ms for nice looking traces */
  2652. p->offset.tv_usec -= p->offset.tv_usec % 20000;
  2653. }
  2654. /* If the timestamp is specified, just send it as is */
  2655. if (ts)
  2656. return ts;
  2657. /* If we have a time that the frame arrived, always use it to make our timestamp */
  2658. if (delivery && (delivery->tv_sec || delivery->tv_usec)) {
  2659. ms = (delivery->tv_sec - p->offset.tv_sec) * 1000 +
  2660. (1000000 + delivery->tv_usec - p->offset.tv_usec) / 1000 - 1000;
  2661. if (option_debug)
  2662. ast_log(LOG_DEBUG, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
  2663. } else {
  2664. gettimeofday(&tv, NULL);
  2665. ms = (tv.tv_sec - p->offset.tv_sec) * 1000 +
  2666. (1000000 + tv.tv_usec - p->offset.tv_usec) / 1000 - 1000;
  2667. if (ms < 0)
  2668. ms = 0;
  2669. if (voice) {
  2670. /* On a voice frame, use predicted values if appropriate */
  2671. if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
  2672. /* Adjust our txcore, keeping voice and
  2673. non-voice synchronized */
  2674. add_ms(&p->offset, (int)(ms - p->nextpred)/10);
  2675. if (!p->nextpred) {
  2676. p->nextpred = ms; /*f->samples / 8;*/
  2677. if (p->nextpred <= p->lastsent)
  2678. p->nextpred = p->lastsent + 3;
  2679. }
  2680. ms = p->nextpred;
  2681. } else {
  2682. /* in this case, just use the actual
  2683. * time, since we're either way off
  2684. * (shouldn't happen), or we're ending a
  2685. * silent period -- and seed the next
  2686. * predicted time. Also, round ms to the
  2687. * next multiple of frame size (so our
  2688. * silent periods are multiples of
  2689. * frame size too) */
  2690. int adj = f->samples / 8;
  2691. if (adj) {
  2692. int diff = ms % adj;
  2693. if(diff)
  2694. ms += adj - diff;
  2695. }
  2696. p->nextpred = ms;
  2697. p->notsilenttx = 1;
  2698. }
  2699. } else {
  2700. /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
  2701. it's a genuine frame */
  2702. if (genuine) {
  2703. /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
  2704. if (ms <= p->lastsent)
  2705. ms = p->lastsent + 3;
  2706. } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
  2707. /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
  2708. ms = p->lastsent + 3;
  2709. }
  2710. }
  2711. }
  2712. p->lastsent = ms;
  2713. if (voice)
  2714. p->nextpred = p->nextpred + f->samples / 8;
  2715. #if 0
  2716. printf("TS: %s - %dms\n", voice ? "Audio" : "Control", ms);
  2717. #endif
  2718. return ms;
  2719. }
  2720. #ifdef BRIDGE_OPTIMIZATION
  2721. static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
  2722. {
  2723. int ms;
  2724. /* Receive from p1, send to p2 */
  2725. /* Setup rxcore if necessary on outgoing channel */
  2726. if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
  2727. gettimeofday(&p1->rxcore, NULL);
  2728. /* Setup txcore if necessary on outgoing channel */
  2729. if (!p2->offset.tv_sec && !p2->offset.tv_usec)
  2730. gettimeofday(&p2->offset, NULL);
  2731. /* Now, ts is the timestamp of the original packet in the orignal context.
  2732. Adding rxcore to it gives us when we would want the packet to be delivered normally.
  2733. Subtracting txcore of the outgoing channel gives us what we'd expect */
  2734. ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 +
  2735. (1000000 + p1->rxcore.tv_usec - p2->offset.tv_usec) / 1000 - 1000;
  2736. fakets += ms;
  2737. p2->lastsent = fakets;
  2738. return fakets;
  2739. }
  2740. #endif
  2741. static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
  2742. {
  2743. /* Returns where in "receive time" we are. That is, how many ms
  2744. since we received (or would have received) the frame with timestamp 0 */
  2745. struct timeval tv;
  2746. int ms;
  2747. /* Setup rxcore if necessary */
  2748. if (!p->rxcore.tv_sec && !p->rxcore.tv_usec) {
  2749. gettimeofday(&p->rxcore, NULL);
  2750. if (option_debug)
  2751. ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
  2752. p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
  2753. p->rxcore.tv_sec -= offset / 1000;
  2754. p->rxcore.tv_usec -= (offset % 1000) * 1000;
  2755. if (p->rxcore.tv_usec < 0) {
  2756. p->rxcore.tv_usec += 1000000;
  2757. p->rxcore.tv_sec -= 1;
  2758. }
  2759. #if 1
  2760. if (option_debug)
  2761. ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
  2762. p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
  2763. #endif
  2764. }
  2765. gettimeofday(&tv, NULL);
  2766. ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 +
  2767. (1000000 + tv.tv_usec - p->rxcore.tv_usec) / 1000 - 1000;
  2768. return ms;
  2769. }
  2770. static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin)
  2771. {
  2772. struct iax2_trunk_peer *tpeer;
  2773. char iabuf[INET_ADDRSTRLEN];
  2774. /* Finds and locks trunk peer */
  2775. ast_mutex_lock(&tpeerlock);
  2776. tpeer = tpeers;
  2777. while(tpeer) {
  2778. /* We don't lock here because tpeer->addr *never* changes */
  2779. if (!inaddrcmp(&tpeer->addr, sin)) {
  2780. ast_mutex_lock(&tpeer->lock);
  2781. break;
  2782. }
  2783. tpeer = tpeer->next;
  2784. }
  2785. if (!tpeer) {
  2786. tpeer = malloc(sizeof(struct iax2_trunk_peer));
  2787. if (tpeer) {
  2788. memset(tpeer, 0, sizeof(struct iax2_trunk_peer));
  2789. ast_mutex_init(&tpeer->lock);
  2790. tpeer->lastsent = 9999;
  2791. memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
  2792. gettimeofday(&tpeer->trunkact, NULL);
  2793. ast_mutex_lock(&tpeer->lock);
  2794. tpeer->next = tpeers;
  2795. tpeers = tpeer;
  2796. ast_log(LOG_DEBUG, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
  2797. }
  2798. }
  2799. ast_mutex_unlock(&tpeerlock);
  2800. return tpeer;
  2801. }
  2802. static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct ast_frame *f)
  2803. {
  2804. struct iax2_trunk_peer *tpeer;
  2805. void *tmp, *ptr;
  2806. struct ast_iax2_meta_trunk_entry *met;
  2807. char iabuf[INET_ADDRSTRLEN];
  2808. tpeer = find_tpeer(&pvt->addr);
  2809. if (tpeer) {
  2810. if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
  2811. /* Need to reallocate space */
  2812. if (tpeer->trunkdataalloc < MAX_TRUNKDATA) {
  2813. tmp = realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE);
  2814. if (tmp) {
  2815. tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
  2816. tpeer->trunkdata = tmp;
  2817. ast_log(LOG_DEBUG, "Expanded trunk '%s:%d' to %d bytes\n", ast_inet_ntoa(iabuf, sizeof(iabuf), tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), tpeer->trunkdataalloc);
  2818. } else {
  2819. ast_log(LOG_WARNING, "Insufficient memory to expand trunk data to %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
  2820. ast_mutex_unlock(&tpeer->lock);
  2821. return -1;
  2822. }
  2823. } else {
  2824. ast_log(LOG_WARNING, "Maximum trunk data space exceeded to %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
  2825. ast_mutex_unlock(&tpeer->lock);
  2826. return -1;
  2827. }
  2828. }
  2829. /* Append to meta frame */
  2830. ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
  2831. met = (struct ast_iax2_meta_trunk_entry *)ptr;
  2832. /* Store call number and length in meta header */
  2833. met->callno = htons(pvt->callno);
  2834. met->len = htons(f->datalen);
  2835. /* Advance pointers/decrease length past trunk entry header */
  2836. ptr += sizeof(struct ast_iax2_meta_trunk_entry);
  2837. tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
  2838. /* Copy actual trunk data */
  2839. memcpy(ptr, f->data, f->datalen);
  2840. tpeer->trunkdatalen += f->datalen;
  2841. tpeer->calls++;
  2842. ast_mutex_unlock(&tpeer->lock);
  2843. }
  2844. return 0;
  2845. }
  2846. static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
  2847. {
  2848. /* Queue a packet for delivery on a given private structure. Use "ts" for
  2849. timestamp, or calculate if ts is 0. Send immediately without retransmission
  2850. or delayed, with retransmission */
  2851. struct ast_iax2_full_hdr *fh;
  2852. struct ast_iax2_mini_hdr *mh;
  2853. struct ast_iax2_video_hdr *vh;
  2854. struct {
  2855. struct iax_frame fr2;
  2856. unsigned char buffer[4096];
  2857. } frb;
  2858. struct iax_frame *fr;
  2859. int res;
  2860. int sendmini=0;
  2861. unsigned int lastsent;
  2862. unsigned int fts;
  2863. if (!pvt) {
  2864. ast_log(LOG_WARNING, "No private structure for packet?\n");
  2865. return -1;
  2866. }
  2867. lastsent = pvt->lastsent;
  2868. /* Calculate actual timestamp */
  2869. fts = calc_timestamp(pvt, ts, f);
  2870. if ((pvt->trunk || ((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)))
  2871. /* High two bytes are the same on timestamp, or sending on a trunk */ &&
  2872. (f->frametype == AST_FRAME_VOICE)
  2873. /* is a voice frame */ &&
  2874. (f->subclass == pvt->svoiceformat)
  2875. /* is the same type */ ) {
  2876. /* Force immediate rather than delayed transmission */
  2877. now = 1;
  2878. /* Mark that mini-style frame is appropriate */
  2879. sendmini = 1;
  2880. }
  2881. if (((fts & 0xFFFF8000L) == (lastsent & 0xFFFF8000L)) &&
  2882. (f->frametype == AST_FRAME_VIDEO) &&
  2883. ((f->subclass & ~0x1) == pvt->svideoformat)) {
  2884. now = 1;
  2885. sendmini = 1;
  2886. }
  2887. /* Allocate an iax_frame */
  2888. if (now) {
  2889. fr = &frb.fr2;
  2890. } else
  2891. fr = iax_frame_new(DIRECTION_OUTGRESS, f->datalen);
  2892. if (!fr) {
  2893. ast_log(LOG_WARNING, "Out of memory\n");
  2894. return -1;
  2895. }
  2896. /* Copy our prospective frame into our immediate or retransmitted wrapper */
  2897. iax_frame_wrap(fr, f);
  2898. fr->ts = fts;
  2899. fr->callno = pvt->callno;
  2900. fr->transfer = transfer;
  2901. fr->final = final;
  2902. if (!sendmini) {
  2903. /* We need a full frame */
  2904. if (seqno > -1)
  2905. fr->oseqno = seqno;
  2906. else
  2907. fr->oseqno = pvt->oseqno++;
  2908. fr->iseqno = pvt->iseqno;
  2909. fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
  2910. fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
  2911. fh->ts = htonl(fr->ts);
  2912. fh->oseqno = fr->oseqno;
  2913. if (transfer) {
  2914. fh->iseqno = 0;
  2915. } else
  2916. fh->iseqno = fr->iseqno;
  2917. /* Keep track of the last thing we've acknowledged */
  2918. if (!transfer)
  2919. pvt->aseqno = fr->iseqno;
  2920. fh->type = fr->af.frametype & 0xFF;
  2921. if (fr->af.frametype == AST_FRAME_VIDEO)
  2922. fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
  2923. else
  2924. fh->csub = compress_subclass(fr->af.subclass);
  2925. if (transfer) {
  2926. fr->dcallno = pvt->transfercallno;
  2927. } else
  2928. fr->dcallno = pvt->peercallno;
  2929. fh->dcallno = htons(fr->dcallno);
  2930. fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
  2931. fr->data = fh;
  2932. fr->retries = 0;
  2933. /* Retry after 2x the ping time has passed */
  2934. fr->retrytime = pvt->pingtime * 2;
  2935. if (fr->retrytime < MIN_RETRY_TIME)
  2936. fr->retrytime = MIN_RETRY_TIME;
  2937. if (fr->retrytime > MAX_RETRY_TIME)
  2938. fr->retrytime = MAX_RETRY_TIME;
  2939. /* Acks' don't get retried */
  2940. if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
  2941. fr->retries = -1;
  2942. else if (f->frametype == AST_FRAME_VOICE)
  2943. pvt->svoiceformat = f->subclass;
  2944. else if (f->frametype == AST_FRAME_VIDEO)
  2945. pvt->svideoformat = f->subclass & ~0x1;
  2946. if (now) {
  2947. res = send_packet(fr);
  2948. } else
  2949. res = iax2_transmit(fr);
  2950. } else {
  2951. if (pvt->trunk) {
  2952. iax2_trunk_queue(pvt, &fr->af);
  2953. res = 0;
  2954. } else if (fr->af.frametype == AST_FRAME_VIDEO) {
  2955. /* Video frame have no sequence number */
  2956. fr->oseqno = -1;
  2957. fr->iseqno = -1;
  2958. vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
  2959. vh->zeros = 0;
  2960. vh->callno = htons(0x8000 | fr->callno);
  2961. vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
  2962. fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
  2963. fr->data = vh;
  2964. fr->retries = -1;
  2965. res = send_packet(fr);
  2966. } else {
  2967. /* Mini-frames have no sequence number */
  2968. fr->oseqno = -1;
  2969. fr->iseqno = -1;
  2970. /* Mini frame will do */
  2971. mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
  2972. mh->callno = htons(fr->callno);
  2973. mh->ts = htons(fr->ts & 0xFFFF);
  2974. fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
  2975. fr->data = mh;
  2976. fr->retries = -1;
  2977. res = send_packet(fr);
  2978. }
  2979. }
  2980. return res;
  2981. }
  2982. static int iax2_show_users(int fd, int argc, char *argv[])
  2983. {
  2984. #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s\n"
  2985. #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s\n"
  2986. struct iax2_user *user;
  2987. char auth[90] = "";
  2988. if (argc != 3)
  2989. return RESULT_SHOWUSAGE;
  2990. ast_mutex_lock(&userl.lock);
  2991. ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
  2992. for(user=userl.users;user;user=user->next) {
  2993. if (!ast_strlen_zero(user->secret)) {
  2994. strncpy(auth,user->secret,sizeof(auth)-1);
  2995. } else if (!ast_strlen_zero(user->inkeys)) {
  2996. snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
  2997. } else
  2998. strncpy(auth, "-no secret-", sizeof(auth) - 1);
  2999. ast_cli(fd, FORMAT2, user->name, auth, user->authmethods,
  3000. user->contexts ? user->contexts->context : context,
  3001. user->ha ? "Yes" : "No");
  3002. }
  3003. ast_mutex_unlock(&userl.lock);
  3004. return RESULT_SUCCESS;
  3005. #undef FORMAT
  3006. #undef FORMAT2
  3007. }
  3008. static int iax2_show_peers(int fd, int argc, char *argv[])
  3009. {
  3010. #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
  3011. #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %-10s\n"
  3012. struct iax2_peer *peer;
  3013. char name[256] = "";
  3014. char iabuf[INET_ADDRSTRLEN];
  3015. int registeredonly=0;
  3016. if ((argc != 3) && (argc != 4) && (argc != 5))
  3017. return RESULT_SHOWUSAGE;
  3018. if ((argc == 4)) {
  3019. if (!strcasecmp(argv[3], "registered")) {
  3020. registeredonly = 1;
  3021. } else
  3022. return RESULT_SHOWUSAGE;
  3023. }
  3024. ast_mutex_lock(&peerl.lock);
  3025. ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", "Status");
  3026. for (peer = peerl.peers;peer;peer = peer->next) {
  3027. char nm[20];
  3028. char status[20] = "";
  3029. int print_line = -1;
  3030. char srch[2000] = "";
  3031. if (registeredonly && !peer->addr.sin_addr.s_addr)
  3032. continue;
  3033. if (!ast_strlen_zero(peer->username))
  3034. snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
  3035. else
  3036. strncpy(name, peer->name, sizeof(name) - 1);
  3037. if (peer->maxms) {
  3038. if (peer->lastms < 0)
  3039. strncpy(status, "UNREACHABLE", sizeof(status) - 1);
  3040. else if (peer->lastms > peer->maxms)
  3041. snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
  3042. else if (peer->lastms)
  3043. snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
  3044. else
  3045. strncpy(status, "UNKNOWN", sizeof(status) - 1);
  3046. } else
  3047. strncpy(status, "Unmonitored", sizeof(status) - 1);
  3048. strncpy(nm, ast_inet_ntoa(iabuf, sizeof(iabuf), peer->mask), sizeof(nm)-1);
  3049. snprintf(srch, sizeof(srch), FORMAT, name,
  3050. peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)",
  3051. peer->dynamic ? "(D)" : "(S)",
  3052. nm,
  3053. ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : " ", status);
  3054. if (argc == 5) {
  3055. if (!strcasecmp(argv[3],"include") && strstr(srch,argv[4])) {
  3056. print_line = -1;
  3057. } else if (!strcasecmp(argv[3],"exclude") && !strstr(srch,argv[4])) {
  3058. print_line = 1;
  3059. } else if (!strcasecmp(argv[3],"begin") && !strncasecmp(srch,argv[4],strlen(argv[4]))) {
  3060. print_line = -1;
  3061. } else {
  3062. print_line = 0;
  3063. }
  3064. }
  3065. if (print_line) {
  3066. ast_cli(fd, FORMAT, name,
  3067. peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)",
  3068. peer->dynamic ? "(D)" : "(S)",
  3069. nm,
  3070. ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : " ", status);
  3071. }
  3072. }
  3073. ast_mutex_unlock(&peerl.lock);
  3074. return RESULT_SUCCESS;
  3075. #undef FORMAT
  3076. #undef FORMAT2
  3077. }
  3078. static int iax2_show_firmware(int fd, int argc, char *argv[])
  3079. {
  3080. #define FORMAT2 "%-15.15s %-15.15s %-15.15s\n"
  3081. #define FORMAT "%-15.15s %-15d %-15d\n"
  3082. struct iax_firmware *cur;
  3083. if ((argc != 3) && (argc != 4))
  3084. return RESULT_SHOWUSAGE;
  3085. ast_mutex_lock(&waresl.lock);
  3086. ast_cli(fd, FORMAT2, "Device", "Version", "Size");
  3087. for (cur = waresl.wares;cur;cur = cur->next) {
  3088. if ((argc == 3) || (!strcasecmp(argv[3], cur->fwh->devname)))
  3089. ast_cli(fd, FORMAT, cur->fwh->devname, ntohs(cur->fwh->version),
  3090. ntohl(cur->fwh->datalen));
  3091. }
  3092. ast_mutex_unlock(&waresl.lock);
  3093. return RESULT_SUCCESS;
  3094. #undef FORMAT
  3095. #undef FORMAT2
  3096. }
  3097. /* JDG: callback to display iax peers in manager */
  3098. static int manager_iax2_show_peers( struct mansession *s, struct message *m )
  3099. {
  3100. char *a[] = { "iax2", "show", "users" };
  3101. int ret;
  3102. ret = iax2_show_peers( s->fd, 3, a );
  3103. ast_cli( s->fd, "\r\n" );
  3104. return ret;
  3105. } /* /JDG */
  3106. static char *regstate2str(int regstate)
  3107. {
  3108. switch(regstate) {
  3109. case REG_STATE_UNREGISTERED:
  3110. return "Unregistered";
  3111. case REG_STATE_REGSENT:
  3112. return "Request Sent";
  3113. case REG_STATE_AUTHSENT:
  3114. return "Auth. Sent";
  3115. case REG_STATE_REGISTERED:
  3116. return "Registered";
  3117. case REG_STATE_REJECTED:
  3118. return "Rejected";
  3119. case REG_STATE_TIMEOUT:
  3120. return "Timeout";
  3121. case REG_STATE_NOAUTH:
  3122. return "No Authentication";
  3123. default:
  3124. return "Unknown";
  3125. }
  3126. }
  3127. static int iax2_show_registry(int fd, int argc, char *argv[])
  3128. {
  3129. #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
  3130. #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
  3131. struct iax2_registry *reg;
  3132. char host[80];
  3133. char perceived[80] = "";
  3134. char iabuf[INET_ADDRSTRLEN];
  3135. if (argc != 3)
  3136. return RESULT_SHOWUSAGE;
  3137. ast_mutex_lock(&peerl.lock);
  3138. ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
  3139. for (reg = registrations;reg;reg = reg->next) {
  3140. snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), reg->addr.sin_addr), ntohs(reg->addr.sin_port));
  3141. if (reg->us.sin_addr.s_addr)
  3142. snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), reg->us.sin_addr), ntohs(reg->us.sin_port));
  3143. else
  3144. strncpy(perceived, "<Unregistered>", sizeof(perceived) - 1);
  3145. ast_cli(fd, FORMAT, host,
  3146. reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
  3147. }
  3148. ast_mutex_unlock(&peerl.lock);
  3149. return RESULT_SUCCESS;
  3150. #undef FORMAT
  3151. #undef FORMAT2
  3152. }
  3153. static int jitterbufsize(struct chan_iax2_pvt *pvt) {
  3154. int min, i;
  3155. min = 99999999;
  3156. for (i=0; i<MEMORY_SIZE; i++) {
  3157. if (pvt->history[i] < min)
  3158. min = pvt->history[i];
  3159. }
  3160. if (pvt->jitterbuffer - min > maxjitterbuffer)
  3161. return maxjitterbuffer;
  3162. else
  3163. return pvt->jitterbuffer - min;
  3164. }
  3165. static int iax2_show_channels(int fd, int argc, char *argv[])
  3166. {
  3167. #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s\n"
  3168. #define FORMAT "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-4.4dms %-6.6s\n"
  3169. #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
  3170. int x;
  3171. int numchans = 0;
  3172. char iabuf[INET_ADDRSTRLEN];
  3173. if (argc != 3)
  3174. return RESULT_SHOWUSAGE;
  3175. ast_cli(fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format");
  3176. for (x=0;x<IAX_MAX_CALLS;x++) {
  3177. ast_mutex_lock(&iaxsl[x]);
  3178. if (iaxs[x]) {
  3179. #ifdef BRIDGE_OPTIMIZATION
  3180. if (iaxs[x]->bridgecallno)
  3181. ast_cli(fd, FORMATB,
  3182. iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
  3183. ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[x]->addr.sin_addr),
  3184. !ast_strlen_zero(iaxs[x]->username) ? iaxs[x]->username : "(None)",
  3185. iaxs[x]->callno, iaxs[x]->peercallno,
  3186. iaxs[x]->oseqno, iaxs[x]->iseqno,
  3187. iaxs[x]->bridgecallno );
  3188. else
  3189. #endif
  3190. ast_cli(fd, FORMAT,
  3191. iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
  3192. ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[x]->addr.sin_addr),
  3193. !ast_strlen_zero(iaxs[x]->username) ? iaxs[x]->username : "(None)",
  3194. iaxs[x]->callno, iaxs[x]->peercallno,
  3195. iaxs[x]->oseqno, iaxs[x]->iseqno,
  3196. iaxs[x]->lag,
  3197. iaxs[x]->jitter,
  3198. iaxs[x]->usejitterbuf ? jitterbufsize(iaxs[x]) : 0,
  3199. ast_getformatname(iaxs[x]->voiceformat) );
  3200. numchans++;
  3201. }
  3202. ast_mutex_unlock(&iaxsl[x]);
  3203. }
  3204. ast_cli(fd, "%d active IAX channel(s)\n", numchans);
  3205. return RESULT_SUCCESS;
  3206. #undef FORMAT
  3207. #undef FORMAT2
  3208. }
  3209. static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
  3210. {
  3211. if (argc != 3)
  3212. return RESULT_SHOWUSAGE;
  3213. iaxtrunkdebug = 1;
  3214. ast_cli(fd, "IAX2 Trunk Debug Requested\n");
  3215. return RESULT_SUCCESS;
  3216. }
  3217. static int iax2_do_debug(int fd, int argc, char *argv[])
  3218. {
  3219. if (argc != 2)
  3220. return RESULT_SHOWUSAGE;
  3221. iaxdebug = 1;
  3222. ast_cli(fd, "IAX2 Debugging Enabled\n");
  3223. return RESULT_SUCCESS;
  3224. }
  3225. static int iax2_no_debug(int fd, int argc, char *argv[])
  3226. {
  3227. if (argc != 3)
  3228. return RESULT_SHOWUSAGE;
  3229. iaxdebug = 0;
  3230. ast_cli(fd, "IAX2 Debugging Disabled\n");
  3231. return RESULT_SUCCESS;
  3232. }
  3233. static char show_users_usage[] =
  3234. "Usage: iax2 show users\n"
  3235. " Lists all users known to the IAX (Inter-Asterisk eXchange rev 2) subsystem.\n";
  3236. static char show_channels_usage[] =
  3237. "Usage: iax2 show channels\n"
  3238. " Lists all currently active IAX channels.\n";
  3239. static char show_peers_usage[] =
  3240. "Usage: iax2 show peers\n"
  3241. " Lists all known IAX peers.\n";
  3242. static char show_firmware_usage[] =
  3243. "Usage: iax2 show firmware\n"
  3244. " Lists all known IAX firmware images.\n";
  3245. static char show_reg_usage[] =
  3246. "Usage: iax2 show registry\n"
  3247. " Lists all registration requests and status.\n";
  3248. static char debug_usage[] =
  3249. "Usage: iax2 debug\n"
  3250. " Enables dumping of IAX packets for debugging purposes\n";
  3251. static char no_debug_usage[] =
  3252. "Usage: iax2 no debug\n"
  3253. " Disables dumping of IAX packets for debugging purposes\n";
  3254. static char debug_trunk_usage[] =
  3255. "Usage: iax2 trunk debug\n"
  3256. " Requests current status of IAX trunking\n";
  3257. static struct ast_cli_entry cli_show_users =
  3258. { { "iax2", "show", "users", NULL }, iax2_show_users, "Show defined IAX users", show_users_usage };
  3259. static struct ast_cli_entry cli_show_firmware =
  3260. { { "iax2", "show", "firmware", NULL }, iax2_show_firmware, "Show available IAX firmwares", show_firmware_usage };
  3261. static struct ast_cli_entry cli_show_channels =
  3262. { { "iax2", "show", "channels", NULL }, iax2_show_channels, "Show active IAX channels", show_channels_usage };
  3263. static struct ast_cli_entry cli_show_peers =
  3264. { { "iax2", "show", "peers", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
  3265. static struct ast_cli_entry cli_show_peers_include =
  3266. { { "iax2", "show", "peers", "include", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
  3267. static struct ast_cli_entry cli_show_peers_exclude =
  3268. { { "iax2", "show", "peers", "exclude", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
  3269. static struct ast_cli_entry cli_show_peers_begin =
  3270. { { "iax2", "show", "peers", "begin", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
  3271. static struct ast_cli_entry cli_show_registry =
  3272. { { "iax2", "show", "registry", NULL }, iax2_show_registry, "Show IAX registration status", show_reg_usage };
  3273. static struct ast_cli_entry cli_debug =
  3274. { { "iax2", "debug", NULL }, iax2_do_debug, "Enable IAX debugging", debug_usage };
  3275. static struct ast_cli_entry cli_trunk_debug =
  3276. { { "iax2", "trunk", "debug", NULL }, iax2_do_trunk_debug, "Request IAX trunk debug", debug_trunk_usage };
  3277. static struct ast_cli_entry cli_no_debug =
  3278. { { "iax2", "no", "debug", NULL }, iax2_no_debug, "Disable IAX debugging", no_debug_usage };
  3279. static int iax2_write(struct ast_channel *c, struct ast_frame *f)
  3280. {
  3281. unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
  3282. int res = -1;
  3283. ast_mutex_lock(&iaxsl[callno]);
  3284. if (iaxs[callno]) {
  3285. /* If there's an outstanding error, return failure now */
  3286. if (!iaxs[callno]->error) {
  3287. if (iaxs[callno]->alreadygone)
  3288. res = 0;
  3289. /* Don't waste bandwidth sending null frames */
  3290. else if (f->frametype == AST_FRAME_NULL)
  3291. res = 0;
  3292. else if ((f->frametype == AST_FRAME_VOICE) && iaxs[callno]->quelch)
  3293. res = 0;
  3294. else if (!(iaxs[callno]->state & IAX_STATE_STARTED))
  3295. res = 0;
  3296. else
  3297. /* Simple, just queue for transmission */
  3298. res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
  3299. } else {
  3300. ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
  3301. }
  3302. }
  3303. /* If it's already gone, just return */
  3304. ast_mutex_unlock(&iaxsl[callno]);
  3305. return res;
  3306. }
  3307. static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno,
  3308. int now, int transfer, int final)
  3309. {
  3310. struct ast_frame f;
  3311. f.frametype = type;
  3312. f.subclass = command;
  3313. f.datalen = datalen;
  3314. f.samples = 0;
  3315. f.mallocd = 0;
  3316. f.offset = 0;
  3317. f.src = __FUNCTION__;
  3318. f.data = data;
  3319. return iax2_send(i, &f, ts, seqno, now, transfer, final);
  3320. }
  3321. static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
  3322. {
  3323. return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
  3324. }
  3325. static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
  3326. {
  3327. int res;
  3328. ast_mutex_lock(&iaxsl[callno]);
  3329. res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
  3330. ast_mutex_unlock(&iaxsl[callno]);
  3331. return res;
  3332. }
  3333. #ifdef BRIDGE_OPTIMIZATION
  3334. static int forward_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
  3335. {
  3336. return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
  3337. }
  3338. #endif
  3339. static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
  3340. {
  3341. /* It is assumed that the callno has already been locked */
  3342. iax2_predestroy_nolock(i->callno);
  3343. return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
  3344. }
  3345. static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
  3346. {
  3347. return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
  3348. }
  3349. static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
  3350. {
  3351. return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
  3352. }
  3353. static int apply_context(struct iax2_context *con, char *context)
  3354. {
  3355. while(con) {
  3356. if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
  3357. return -1;
  3358. con = con->next;
  3359. }
  3360. return 0;
  3361. }
  3362. static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
  3363. {
  3364. /* Start pessimistic */
  3365. int res = -1;
  3366. int version = 2;
  3367. struct iax2_user *user, *best = NULL;
  3368. int bestscore = 0;
  3369. int gotcapability=0;
  3370. char iabuf[INET_ADDRSTRLEN];
  3371. if (!iaxs[callno])
  3372. return res;
  3373. if (ies->called_number)
  3374. strncpy(iaxs[callno]->exten, ies->called_number, sizeof(iaxs[callno]->exten) - 1);
  3375. if (ies->calling_number) {
  3376. if (ies->calling_name)
  3377. snprintf(iaxs[callno]->callerid, sizeof(iaxs[callno]->callerid), "\"%s\" <%s>", ies->calling_name, ies->calling_number);
  3378. else
  3379. strncpy(iaxs[callno]->callerid, ies->calling_number, sizeof(iaxs[callno]->callerid) - 1);
  3380. } else if (ies->calling_name)
  3381. strncpy(iaxs[callno]->callerid, ies->calling_name, sizeof(iaxs[callno]->callerid) - 1);
  3382. if (ies->calling_ani)
  3383. strncpy(iaxs[callno]->ani, ies->calling_ani, sizeof(iaxs[callno]->ani) - 1);
  3384. if (ies->dnid)
  3385. strncpy(iaxs[callno]->dnid, ies->dnid, sizeof(iaxs[callno]->dnid)-1);
  3386. if (ies->called_context)
  3387. strncpy(iaxs[callno]->context, ies->called_context, sizeof(iaxs[callno]->context)-1);
  3388. if (ies->language)
  3389. strncpy(iaxs[callno]->language, ies->language, sizeof(iaxs[callno]->language)-1);
  3390. if (ies->username)
  3391. strncpy(iaxs[callno]->username, ies->username, sizeof(iaxs[callno]->username)-1);
  3392. if (ies->format)
  3393. iaxs[callno]->peerformat = ies->format;
  3394. if (ies->adsicpe)
  3395. iaxs[callno]->peeradsicpe = ies->adsicpe;
  3396. if (ies->capability) {
  3397. gotcapability = 1;
  3398. iaxs[callno]->peercapability = ies->capability;
  3399. }
  3400. if (ies->version)
  3401. version = ies->version;
  3402. if (!gotcapability)
  3403. iaxs[callno]->peercapability = iaxs[callno]->peerformat;
  3404. if (version > IAX_PROTO_VERSION) {
  3405. ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
  3406. ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), version);
  3407. return res;
  3408. }
  3409. ast_mutex_lock(&userl.lock);
  3410. /* Search the userlist for a compatible entry, and fill in the rest */
  3411. user = userl.users;
  3412. while(user) {
  3413. if ((ast_strlen_zero(iaxs[callno]->username) || /* No username specified */
  3414. !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
  3415. && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
  3416. && (ast_strlen_zero(iaxs[callno]->context) || /* No context specified */
  3417. apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
  3418. if (!ast_strlen_zero(iaxs[callno]->username)) {
  3419. /* Exact match, stop right now. */
  3420. best = user;
  3421. break;
  3422. } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->inkeys)) {
  3423. /* No required authentication */
  3424. if (user->ha) {
  3425. /* There was host authentication and we passed, bonus! */
  3426. if (bestscore < 4) {
  3427. bestscore = 4;
  3428. best = user;
  3429. }
  3430. } else {
  3431. /* No host access, but no secret, either, not bad */
  3432. if (bestscore < 3) {
  3433. bestscore = 3;
  3434. best = user;
  3435. }
  3436. }
  3437. } else {
  3438. if (user->ha) {
  3439. /* Authentication, but host access too, eh, it's something.. */
  3440. if (bestscore < 2) {
  3441. bestscore = 2;
  3442. best = user;
  3443. }
  3444. } else {
  3445. /* Authentication and no host access... This is our baseline */
  3446. if (bestscore < 1) {
  3447. bestscore = 1;
  3448. best = user;
  3449. }
  3450. }
  3451. }
  3452. }
  3453. user = user->next;
  3454. }
  3455. ast_mutex_unlock(&userl.lock);
  3456. user = best;
  3457. #ifdef MYSQL_FRIENDS
  3458. if (!user && mysql && !ast_strlen_zero(iaxs[callno]->username) && (strlen(iaxs[callno]->username) < 128)) {
  3459. user = mysql_user(iaxs[callno]->username);
  3460. if (user && !ast_strlen_zero(iaxs[callno]->context) && /* No context specified */
  3461. !apply_context(user->contexts, iaxs[callno]->context)) { /* Context is permitted */
  3462. if (user->contexts)
  3463. free(user->contexts);
  3464. free(user);
  3465. user = NULL;
  3466. }
  3467. }
  3468. #endif
  3469. if (user) {
  3470. /* We found our match (use the first) */
  3471. /* Store the requested username if not specified */
  3472. if (ast_strlen_zero(iaxs[callno]->username))
  3473. strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
  3474. /* Store whether this is a trunked call, too, of course, and move if appropriate */
  3475. iaxs[callno]->trunk = user->trunk;
  3476. iaxs[callno]->capability = user->capability;
  3477. /* And use the default context */
  3478. if (ast_strlen_zero(iaxs[callno]->context)) {
  3479. if (user->contexts)
  3480. strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
  3481. else
  3482. strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
  3483. }
  3484. /* Copy the secret */
  3485. strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
  3486. /* And any input keys */
  3487. strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys) - 1);
  3488. /* And the permitted authentication methods */
  3489. iaxs[callno]->authmethods = user->authmethods;
  3490. /* If they have callerid, override the given caller id. Always store the ANI */
  3491. if (!ast_strlen_zero(iaxs[callno]->callerid)) {
  3492. if (user->hascallerid)
  3493. strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
  3494. strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
  3495. }
  3496. if (!ast_strlen_zero(user->accountcode))
  3497. strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
  3498. if (user->amaflags)
  3499. iaxs[callno]->amaflags = user->amaflags;
  3500. if (!ast_strlen_zero(user->language))
  3501. strncpy(iaxs[callno]->language, user->language, sizeof(iaxs[callno]->language)-1);
  3502. iaxs[callno]->notransfer = user->notransfer;
  3503. iaxs[callno]->usejitterbuf = user->usejitterbuf;
  3504. res = 0;
  3505. }
  3506. iaxs[callno]->trunk = iax2_getpeertrunk(*sin);
  3507. return res;
  3508. }
  3509. static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst)
  3510. {
  3511. struct ast_iax2_full_hdr fh;
  3512. char iabuf[INET_ADDRSTRLEN];
  3513. fh.scallno = htons(src | IAX_FLAG_FULL);
  3514. fh.dcallno = htons(dst);
  3515. fh.ts = 0;
  3516. fh.oseqno = 0;
  3517. fh.iseqno = 0;
  3518. fh.type = AST_FRAME_IAX;
  3519. fh.csub = compress_subclass(IAX_COMMAND_INVAL);
  3520. #if 0
  3521. if (option_debug)
  3522. #endif
  3523. ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
  3524. ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port), src, dst);
  3525. return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
  3526. }
  3527. static int authenticate_request(struct chan_iax2_pvt *p)
  3528. {
  3529. struct iax_ie_data ied;
  3530. memset(&ied, 0, sizeof(ied));
  3531. iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
  3532. if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
  3533. snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
  3534. iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
  3535. }
  3536. iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
  3537. return send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
  3538. }
  3539. static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
  3540. {
  3541. char requeststr[256] = "";
  3542. char md5secret[256] = "";
  3543. char secret[256] = "";
  3544. char rsasecret[256] = "";
  3545. int res = -1;
  3546. int x;
  3547. if (!(p->state & IAX_STATE_AUTHENTICATED))
  3548. return res;
  3549. if (ies->password)
  3550. strncpy(secret, ies->password, sizeof(secret) - 1);
  3551. if (ies->md5_result)
  3552. strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
  3553. if (ies->rsa_result)
  3554. strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
  3555. if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
  3556. struct ast_key *key;
  3557. char *keyn;
  3558. char tmpkey[256] = "";
  3559. char *stringp=NULL;
  3560. strncpy(tmpkey, p->inkeys, sizeof(tmpkey) - 1);
  3561. stringp=tmpkey;
  3562. keyn = strsep(&stringp, ":");
  3563. while(keyn) {
  3564. key = ast_key_get(keyn, AST_KEY_PUBLIC);
  3565. if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
  3566. res = 0;
  3567. break;
  3568. } else if (!key)
  3569. ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
  3570. keyn = strsep(&stringp, ":");
  3571. }
  3572. } else if (p->authmethods & IAX_AUTH_MD5) {
  3573. struct MD5Context md5;
  3574. unsigned char digest[16];
  3575. MD5Init(&md5);
  3576. MD5Update(&md5, p->challenge, strlen(p->challenge));
  3577. MD5Update(&md5, p->secret, strlen(p->secret));
  3578. MD5Final(digest, &md5);
  3579. /* If they support md5, authenticate with it. */
  3580. for (x=0;x<16;x++)
  3581. sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
  3582. if (!strcasecmp(requeststr, md5secret))
  3583. res = 0;
  3584. } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
  3585. if (!strcmp(secret, p->secret))
  3586. res = 0;
  3587. }
  3588. return res;
  3589. }
  3590. static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
  3591. {
  3592. char requeststr[256] = "";
  3593. char peer[256] = "";
  3594. char md5secret[256] = "";
  3595. char rsasecret[256] = "";
  3596. char secret[256] = "";
  3597. char iabuf[INET_ADDRSTRLEN];
  3598. struct iax2_peer *p;
  3599. struct ast_key *key;
  3600. char *keyn;
  3601. int x;
  3602. int expire = 0;
  3603. iaxs[callno]->state &= ~IAX_STATE_AUTHENTICATED;
  3604. iaxs[callno]->peer[0] = '\0';
  3605. if (ies->username)
  3606. strncpy(peer, ies->username, sizeof(peer) - 1);
  3607. if (ies->password)
  3608. strncpy(secret, ies->password, sizeof(secret) - 1);
  3609. if (ies->md5_result)
  3610. strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
  3611. if (ies->rsa_result)
  3612. strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
  3613. if (ies->refresh)
  3614. expire = ies->refresh;
  3615. if (ast_strlen_zero(peer)) {
  3616. ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
  3617. return -1;
  3618. }
  3619. /* We release the lock for the call to prevent a deadlock, but it's okay because
  3620. only the current thread could possibly make it go away or make changes */
  3621. ast_mutex_unlock(&iaxsl[callno]);
  3622. ast_mutex_lock(&peerl.lock);
  3623. for (p = peerl.peers; p ; p = p->next)
  3624. if (!strcasecmp(p->name, peer))
  3625. break;
  3626. ast_mutex_unlock(&peerl.lock);
  3627. ast_mutex_lock(&iaxsl[callno]);
  3628. #ifdef MYSQL_FRIENDS
  3629. if (!p)
  3630. p = mysql_peer(peer);
  3631. #endif
  3632. if (!p) {
  3633. if (authdebug)
  3634. ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
  3635. return -1;
  3636. }
  3637. if (!p->dynamic) {
  3638. if (authdebug)
  3639. ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
  3640. if (p->temponly)
  3641. free(p);
  3642. return -1;
  3643. }
  3644. if (!ast_apply_ha(p->ha, sin)) {
  3645. if (authdebug)
  3646. ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), p->name);
  3647. if (p->temponly)
  3648. free(p);
  3649. return -1;
  3650. }
  3651. strncpy(iaxs[callno]->secret, p->secret, sizeof(iaxs[callno]->secret)-1);
  3652. strncpy(iaxs[callno]->inkeys, p->inkeys, sizeof(iaxs[callno]->inkeys)-1);
  3653. /* Check secret against what we have on file */
  3654. if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
  3655. if (!ast_strlen_zero(p->inkeys)) {
  3656. char tmpkeys[256] = "";
  3657. char *stringp=NULL;
  3658. strncpy(tmpkeys, p->inkeys, sizeof(tmpkeys) - 1);
  3659. stringp=tmpkeys;
  3660. keyn = strsep(&stringp, ":");
  3661. while(keyn) {
  3662. key = ast_key_get(keyn, AST_KEY_PUBLIC);
  3663. if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
  3664. iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
  3665. break;
  3666. } else if (!key)
  3667. ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
  3668. keyn = strsep(&stringp, ":");
  3669. }
  3670. if (!keyn) {
  3671. if (authdebug)
  3672. ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
  3673. if (p->temponly)
  3674. free(p);
  3675. return -1;
  3676. }
  3677. } else {
  3678. if (authdebug)
  3679. ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
  3680. if (p->temponly)
  3681. free(p);
  3682. return -1;
  3683. }
  3684. } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
  3685. /* They've provided a plain text password and we support that */
  3686. if (strcmp(secret, p->secret)) {
  3687. if (authdebug)
  3688. ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), p->name);
  3689. if (p->temponly)
  3690. free(p);
  3691. return -1;
  3692. } else
  3693. iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
  3694. } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
  3695. struct MD5Context md5;
  3696. unsigned char digest[16];
  3697. MD5Init(&md5);
  3698. MD5Update(&md5, iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
  3699. MD5Update(&md5, p->secret, strlen(p->secret));
  3700. MD5Final(digest, &md5);
  3701. for (x=0;x<16;x++)
  3702. sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
  3703. if (strcasecmp(requeststr, md5secret)) {
  3704. if (authdebug)
  3705. ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), p->name, requeststr, md5secret);
  3706. if (p->temponly)
  3707. free(p);
  3708. return -1;
  3709. } else
  3710. iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
  3711. } else if (!ast_strlen_zero(md5secret) || !ast_strlen_zero(secret)) {
  3712. if (authdebug)
  3713. ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
  3714. if (p->temponly)
  3715. free(p);
  3716. return -1;
  3717. }
  3718. strncpy(iaxs[callno]->peer, peer, sizeof(iaxs[callno]->peer)-1);
  3719. /* Choose lowest expirey number */
  3720. if (expire && (expire < iaxs[callno]->expirey))
  3721. iaxs[callno]->expirey = expire;
  3722. if (p->temponly)
  3723. free(p);
  3724. return 0;
  3725. }
  3726. static int authenticate(char *challenge, char *secret, char *keyn, int authmethods, struct iax_ie_data *ied, struct sockaddr_in *sin)
  3727. {
  3728. int res = -1;
  3729. int x;
  3730. char iabuf[INET_ADDRSTRLEN];
  3731. if (keyn && !ast_strlen_zero(keyn)) {
  3732. if (!(authmethods & IAX_AUTH_RSA)) {
  3733. if (!secret || ast_strlen_zero(secret))
  3734. ast_log(LOG_NOTICE, "Asked to authenticate to %s with an RSA key, but they don't allow RSA authentication\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
  3735. } else if (ast_strlen_zero(challenge)) {
  3736. ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
  3737. } else {
  3738. char sig[256];
  3739. struct ast_key *key;
  3740. key = ast_key_get(keyn, AST_KEY_PRIVATE);
  3741. if (!key) {
  3742. ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
  3743. } else {
  3744. if (ast_sign(key, challenge, sig)) {
  3745. ast_log(LOG_NOTICE, "Unable to sign challenge withy key\n");
  3746. res = -1;
  3747. } else {
  3748. iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
  3749. res = 0;
  3750. }
  3751. }
  3752. }
  3753. }
  3754. /* Fall back */
  3755. if (res && secret && !ast_strlen_zero(secret)) {
  3756. if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
  3757. struct MD5Context md5;
  3758. unsigned char digest[16];
  3759. char digres[128] = "";
  3760. MD5Init(&md5);
  3761. MD5Update(&md5, challenge, strlen(challenge));
  3762. MD5Update(&md5, secret, strlen(secret));
  3763. MD5Final(digest, &md5);
  3764. /* If they support md5, authenticate with it. */
  3765. for (x=0;x<16;x++)
  3766. sprintf(digres + (x << 1), "%2.2x", digest[x]); /* safe */
  3767. iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
  3768. res = 0;
  3769. } else if (authmethods & IAX_AUTH_PLAINTEXT) {
  3770. iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
  3771. res = 0;
  3772. } else
  3773. ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), authmethods);
  3774. }
  3775. return res;
  3776. }
  3777. static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, char *override, char *okey)
  3778. {
  3779. struct iax2_peer *peer;
  3780. /* Start pessimistic */
  3781. int res = -1;
  3782. int authmethods = 0;
  3783. struct iax_ie_data ied;
  3784. memset(&ied, 0, sizeof(ied));
  3785. if (ies->username)
  3786. strncpy(p->username, ies->username, sizeof(p->username) - 1);
  3787. if (ies->challenge)
  3788. strncpy(p->challenge, ies->challenge, sizeof(p->challenge)-1);
  3789. if (ies->authmethods)
  3790. authmethods = ies->authmethods;
  3791. /* Check for override RSA authentication first */
  3792. if ((override && !ast_strlen_zero(override)) || (okey && !ast_strlen_zero(okey))) {
  3793. /* Normal password authentication */
  3794. res = authenticate(p->challenge, override, okey, authmethods, &ied, sin);
  3795. } else {
  3796. ast_mutex_lock(&peerl.lock);
  3797. peer = peerl.peers;
  3798. while(peer) {
  3799. if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
  3800. /* No peer specified at our end, or this is the peer */
  3801. && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
  3802. /* No username specified in peer rule, or this is the right username */
  3803. && (!peer->addr.sin_addr.s_addr || ((sin->sin_addr.s_addr & peer->mask.s_addr) == (peer->addr.sin_addr.s_addr & peer->mask.s_addr)))
  3804. /* No specified host, or this is our host */
  3805. ) {
  3806. res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin);
  3807. if (!res)
  3808. break;
  3809. }
  3810. peer = peer->next;
  3811. }
  3812. ast_mutex_unlock(&peerl.lock);
  3813. }
  3814. if (!res)
  3815. res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
  3816. return res;
  3817. }
  3818. static int iax2_do_register(struct iax2_registry *reg);
  3819. static int iax2_do_register_s(void *data)
  3820. {
  3821. struct iax2_registry *reg = data;
  3822. reg->expire = -1;
  3823. iax2_do_register(reg);
  3824. return 0;
  3825. }
  3826. static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
  3827. {
  3828. int newcall = 0;
  3829. char newip[256] = "";
  3830. struct iax_ie_data ied;
  3831. struct sockaddr_in new;
  3832. memset(&ied, 0, sizeof(ied));
  3833. if (ies->apparent_addr)
  3834. memcpy(&new, ies->apparent_addr, sizeof(new));
  3835. if (ies->callno)
  3836. newcall = ies->callno;
  3837. if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
  3838. ast_log(LOG_WARNING, "Invalid transfer request\n");
  3839. return -1;
  3840. }
  3841. pvt->transfercallno = newcall;
  3842. memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
  3843. inet_aton(newip, &pvt->transfer.sin_addr);
  3844. pvt->transfer.sin_family = AF_INET;
  3845. pvt->transferring = TRANSFER_BEGIN;
  3846. pvt->transferid = ies->transferid;
  3847. if (ies->transferid)
  3848. iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
  3849. send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
  3850. return 0;
  3851. }
  3852. static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
  3853. {
  3854. char exten[256] = "";
  3855. int status = CACHE_FLAG_UNKNOWN;
  3856. int expirey = iaxdefaultdpcache;
  3857. int x;
  3858. int matchmore = 0;
  3859. struct iax2_dpcache *dp, *prev;
  3860. if (ies->called_number)
  3861. strncpy(exten, ies->called_number, sizeof(exten)-1);
  3862. if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
  3863. status = CACHE_FLAG_EXISTS;
  3864. else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
  3865. status = CACHE_FLAG_CANEXIST;
  3866. else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
  3867. status = CACHE_FLAG_NONEXISTENT;
  3868. if (ies->dpstatus & IAX_DPSTATUS_IGNOREPAT) {
  3869. /* Don't really do anything with this */
  3870. }
  3871. if (ies->refresh)
  3872. expirey = ies->refresh;
  3873. if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
  3874. matchmore = CACHE_FLAG_MATCHMORE;
  3875. ast_mutex_lock(&dpcache_lock);
  3876. prev = NULL;
  3877. dp = pvt->dpentries;
  3878. while(dp) {
  3879. if (!strcmp(dp->exten, exten)) {
  3880. /* Let them go */
  3881. if (prev)
  3882. prev->peer = dp->peer;
  3883. else
  3884. pvt->dpentries = dp->peer;
  3885. dp->peer = NULL;
  3886. dp->callno = 0;
  3887. dp->expirey.tv_sec = dp->orig.tv_sec + expirey;
  3888. if (dp->flags & CACHE_FLAG_PENDING) {
  3889. dp->flags &= ~CACHE_FLAG_PENDING;
  3890. dp->flags |= status;
  3891. dp->flags |= matchmore;
  3892. }
  3893. /* Wake up waiters */
  3894. for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
  3895. if (dp->waiters[x] > -1)
  3896. write(dp->waiters[x], "asdf", 4);
  3897. }
  3898. prev = dp;
  3899. dp = dp->peer;
  3900. }
  3901. ast_mutex_unlock(&dpcache_lock);
  3902. return 0;
  3903. }
  3904. static int complete_transfer(int callno, struct iax_ies *ies)
  3905. {
  3906. int peercallno = 0;
  3907. struct chan_iax2_pvt *pvt = iaxs[callno];
  3908. struct iax_frame *cur;
  3909. if (ies->callno)
  3910. peercallno = ies->callno;
  3911. if (peercallno < 1) {
  3912. ast_log(LOG_WARNING, "Invalid transfer request\n");
  3913. return -1;
  3914. }
  3915. memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
  3916. memset(&pvt->transfer, 0, sizeof(pvt->transfer));
  3917. /* Reset sequence numbers */
  3918. pvt->oseqno = 0;
  3919. pvt->iseqno = 0;
  3920. pvt->aseqno = 0;
  3921. pvt->peercallno = peercallno;
  3922. pvt->transferring = TRANSFER_NONE;
  3923. pvt->svoiceformat = -1;
  3924. pvt->voiceformat = 0;
  3925. pvt->svideoformat = -1;
  3926. pvt->videoformat = 0;
  3927. pvt->transfercallno = -1;
  3928. memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
  3929. memset(&pvt->offset, 0, sizeof(pvt->offset));
  3930. memset(&pvt->history, 0, sizeof(pvt->history));
  3931. pvt->jitterbuffer = 0;
  3932. pvt->jitter = 0;
  3933. pvt->historicjitter = 0;
  3934. pvt->lag = 0;
  3935. pvt->last = 0;
  3936. pvt->lastsent = 0;
  3937. pvt->nextpred = 0;
  3938. pvt->pingtime = DEFAULT_RETRY_TIME;
  3939. ast_mutex_lock(&iaxq.lock);
  3940. for (cur = iaxq.head; cur ; cur = cur->next) {
  3941. /* We must cancel any packets that would have been transmitted
  3942. because now we're talking to someone new. It's okay, they
  3943. were transmitted to someone that didn't care anyway. */
  3944. if (callno == cur->callno)
  3945. cur->retries = -1;
  3946. }
  3947. ast_mutex_unlock(&iaxq.lock);
  3948. return 0;
  3949. }
  3950. static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
  3951. {
  3952. struct iax2_registry *reg;
  3953. /* Start pessimistic */
  3954. char peer[256] = "";
  3955. char msgstatus[40] = "";
  3956. int refresh = 0;
  3957. char ourip[256] = "<Unspecified>";
  3958. struct sockaddr_in oldus;
  3959. struct sockaddr_in us;
  3960. char iabuf[INET_ADDRSTRLEN];
  3961. int oldmsgs;
  3962. memset(&us, 0, sizeof(us));
  3963. if (ies->apparent_addr)
  3964. memcpy(&us, ies->apparent_addr, sizeof(us));
  3965. if (ies->username)
  3966. strncpy(peer, ies->username, sizeof(peer) - 1);
  3967. if (ies->refresh)
  3968. refresh = ies->refresh;
  3969. if (ies->calling_number) {
  3970. /* We don't do anything with it really, but maybe we should */
  3971. }
  3972. reg = iaxs[callno]->reg;
  3973. if (!reg) {
  3974. ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
  3975. return -1;
  3976. }
  3977. memcpy(&oldus, &reg->us, sizeof(oldus));
  3978. oldmsgs = reg->messages;
  3979. if (inaddrcmp(&reg->addr, sin)) {
  3980. ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
  3981. return -1;
  3982. }
  3983. memcpy(&reg->us, &us, sizeof(reg->us));
  3984. reg->messages = ies->msgcount;
  3985. if (refresh && (reg->refresh > refresh)) {
  3986. /* Refresh faster if necessary */
  3987. reg->refresh = refresh;
  3988. if (reg->expire > -1)
  3989. ast_sched_del(sched, reg->expire);
  3990. reg->expire = ast_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
  3991. }
  3992. if ((inaddrcmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) && (option_verbose > 2)) {
  3993. if (reg->messages > 65534)
  3994. snprintf(msgstatus, sizeof(msgstatus), " with message(s) waiting\n");
  3995. else if (reg->messages > 1)
  3996. snprintf(msgstatus, sizeof(msgstatus), " with %d messages waiting\n", reg->messages);
  3997. else if (reg->messages > 0)
  3998. snprintf(msgstatus, sizeof(msgstatus), " with 1 message waiting\n");
  3999. else if (reg->messages > -1)
  4000. snprintf(msgstatus, sizeof(msgstatus), " with no messages waiting\n");
  4001. snprintf(ourip, sizeof(ourip), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), reg->us.sin_addr), ntohs(reg->us.sin_port));
  4002. ast_verbose(VERBOSE_PREFIX_3 "Registered to '%s', who sees us as %s%s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ourip, msgstatus);
  4003. manager_event(EVENT_FLAG_SYSTEM, "Registry", "Channel: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
  4004. }
  4005. reg->regstate = REG_STATE_REGISTERED;
  4006. return 0;
  4007. }
  4008. static int iax2_register(char *value, int lineno)
  4009. {
  4010. struct iax2_registry *reg;
  4011. char copy[256];
  4012. char *username, *hostname, *secret;
  4013. char *porta;
  4014. char *stringp=NULL;
  4015. struct ast_hostent ahp; struct hostent *hp;
  4016. if (!value)
  4017. return -1;
  4018. strncpy(copy, value, sizeof(copy)-1);
  4019. stringp=copy;
  4020. username = strsep(&stringp, "@");
  4021. hostname = strsep(&stringp, "@");
  4022. if (!hostname) {
  4023. ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
  4024. return -1;
  4025. }
  4026. stringp=username;
  4027. username = strsep(&stringp, ":");
  4028. secret = strsep(&stringp, ":");
  4029. stringp=hostname;
  4030. hostname = strsep(&stringp, ":");
  4031. porta = strsep(&stringp, ":");
  4032. if (porta && !atoi(porta)) {
  4033. ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
  4034. return -1;
  4035. }
  4036. hp = ast_gethostbyname(hostname, &ahp);
  4037. if (!hp) {
  4038. ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
  4039. return -1;
  4040. }
  4041. reg = malloc(sizeof(struct iax2_registry));
  4042. if (reg) {
  4043. memset(reg, 0, sizeof(struct iax2_registry));
  4044. strncpy(reg->username, username, sizeof(reg->username)-1);
  4045. if (secret)
  4046. strncpy(reg->secret, secret, sizeof(reg->secret)-1);
  4047. reg->expire = -1;
  4048. reg->refresh = IAX_DEFAULT_REG_EXPIRE;
  4049. reg->addr.sin_family = AF_INET;
  4050. memcpy(&reg->addr.sin_addr, hp->h_addr, sizeof(&reg->addr.sin_addr));
  4051. reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(IAX_DEFAULT_PORTNO);
  4052. reg->next = registrations;
  4053. reg->callno = 0;
  4054. registrations = reg;
  4055. } else {
  4056. ast_log(LOG_ERROR, "Out of memory\n");
  4057. return -1;
  4058. }
  4059. return 0;
  4060. }
  4061. static void register_peer_exten(struct iax2_peer *peer, int onoff)
  4062. {
  4063. unsigned char multi[256]="";
  4064. char *stringp, *ext;
  4065. if (!ast_strlen_zero(regcontext)) {
  4066. strncpy(multi, ast_strlen_zero(peer->regexten) ? peer->name : peer->regexten, sizeof(multi) - 1);
  4067. stringp = multi;
  4068. while((ext = strsep(&stringp, "&"))) {
  4069. if (onoff)
  4070. ast_add_extension(regcontext, 1, ext, 1, NULL, "Noop", strdup(peer->name), free, type);
  4071. else
  4072. ast_context_remove_extension(regcontext, ext, 1, NULL);
  4073. }
  4074. }
  4075. }
  4076. static int expire_registry(void *data)
  4077. {
  4078. struct iax2_peer *p = data;
  4079. /* Reset the address */
  4080. memset(&p->addr, 0, sizeof(p->addr));
  4081. /* Reset expire notice */
  4082. p->expire = -1;
  4083. /* Reset expirey value */
  4084. p->expirey = expirey;
  4085. if (p->temponly !=1)
  4086. ast_db_del("IAX/Registry", p->name);
  4087. register_peer_exten(p, 0);
  4088. if (iax2_regfunk)
  4089. iax2_regfunk(p->name, 0);
  4090. return 0;
  4091. }
  4092. static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
  4093. static void reg_source_db(struct iax2_peer *p)
  4094. {
  4095. char data[80];
  4096. struct in_addr in;
  4097. char iabuf[INET_ADDRSTRLEN];
  4098. char *c, *d;
  4099. if ((p->temponly != 1) && (!ast_db_get("IAX/Registry", p->name, data, sizeof(data)))) {
  4100. c = strchr(data, ':');
  4101. if (c) {
  4102. *c = '\0';
  4103. c++;
  4104. if (inet_aton(data, &in)) {
  4105. d = strchr(c, ':');
  4106. if (d) {
  4107. *d = '\0';
  4108. d++;
  4109. if (option_verbose > 2)
  4110. ast_verbose(VERBOSE_PREFIX_3 "Seeding '%s' at %s:%d for %d\n", p->name,
  4111. ast_inet_ntoa(iabuf, sizeof(iabuf), in), atoi(c), atoi(d));
  4112. iax2_poke_peer(p, 0);
  4113. p->expirey = atoi(d);
  4114. memset(&p->addr, 0, sizeof(p->addr));
  4115. p->addr.sin_family = AF_INET;
  4116. p->addr.sin_addr = in;
  4117. p->addr.sin_port = htons(atoi(c));
  4118. if (p->expire > -1)
  4119. ast_sched_del(sched, p->expire);
  4120. p->expire = ast_sched_add(sched, p->expirey * 1000, expire_registry, (void *)p);
  4121. if (iax2_regfunk)
  4122. iax2_regfunk(p->name, 1);
  4123. register_peer_exten(p, 1);
  4124. }
  4125. }
  4126. }
  4127. }
  4128. }
  4129. static int update_registry(char *name, struct sockaddr_in *sin, int callno, char *devtype)
  4130. {
  4131. /* Called from IAX thread only, with proper iaxsl lock */
  4132. struct iax_ie_data ied;
  4133. struct iax2_peer *p;
  4134. int msgcount;
  4135. char data[80];
  4136. char iabuf[INET_ADDRSTRLEN];
  4137. int version;
  4138. memset(&ied, 0, sizeof(ied));
  4139. for (p = peerl.peers;p;p = p->next) {
  4140. if (!strcasecmp(name, p->name)) {
  4141. break;
  4142. }
  4143. }
  4144. #ifdef MYSQL_FRIENDS
  4145. if (!p)
  4146. p = mysql_peer(name);
  4147. #endif
  4148. if (p) {
  4149. #ifdef MYSQL_FRIENDS
  4150. if (p->temponly)
  4151. mysql_update_peer(name, sin);
  4152. #endif
  4153. if (inaddrcmp(&p->addr, sin)) {
  4154. if (iax2_regfunk)
  4155. iax2_regfunk(p->name, 1);
  4156. snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port), p->expirey);
  4157. if ((p->temponly != 1) && (sin->sin_addr.s_addr)) {
  4158. ast_db_put("IAX/Registry", p->name, data);
  4159. if (option_verbose > 2)
  4160. ast_verbose(VERBOSE_PREFIX_3 "Registered '%s' (%s) at %s:%d\n", p->name,
  4161. iaxs[callno]->state & IAX_STATE_AUTHENTICATED ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
  4162. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Registered\r\n", p->name);+ manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Registered\r\n", p->name);
  4163. register_peer_exten(p, 1);
  4164. } else {
  4165. if (option_verbose > 2)
  4166. ast_verbose(VERBOSE_PREFIX_3 "Unregistered '%s' (%s)\n", p->name,
  4167. iaxs[callno]->state & IAX_STATE_AUTHENTICATED ? "AUTHENTICATED" : "UNAUTHENTICATED");
  4168. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p->name);
  4169. register_peer_exten(p, 0);
  4170. ast_db_del("IAX/Registry", p->name);
  4171. }
  4172. /* Update the host */
  4173. memcpy(&p->addr, sin, sizeof(p->addr));
  4174. /* Verify that the host is really there */
  4175. iax2_poke_peer(p, callno);
  4176. }
  4177. /* Setup the expirey */
  4178. if (p->expire > -1)
  4179. ast_sched_del(sched, p->expire);
  4180. if (p->expirey && sin->sin_addr.s_addr)
  4181. p->expire = ast_sched_add(sched, p->expirey * 1000, expire_registry, (void *)p);
  4182. iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
  4183. iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime());
  4184. if (sin->sin_addr.s_addr) {
  4185. iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expirey);
  4186. iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &p->addr);
  4187. if (!ast_strlen_zero(p->mailbox)) {
  4188. if (p->messagedetail) {
  4189. int new, old;
  4190. ast_app_messagecount(p->mailbox, &new, &old);
  4191. if (new > 255)
  4192. new = 255;
  4193. if (old > 255)
  4194. old = 255;
  4195. msgcount = (old << 8) | new;
  4196. } else {
  4197. msgcount = ast_app_has_voicemail(p->mailbox);
  4198. if (msgcount)
  4199. msgcount = 65535;
  4200. }
  4201. iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
  4202. }
  4203. if (p->hascallerid)
  4204. iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->callerid);
  4205. }
  4206. version = iax_check_version(devtype);
  4207. if (version)
  4208. iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
  4209. if (p->temponly)
  4210. free(p);
  4211. return send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
  4212. }
  4213. ast_log(LOG_WARNING, "No such peer '%s'\n", name);
  4214. return -1;
  4215. }
  4216. static int registry_authrequest(char *name, int callno)
  4217. {
  4218. struct iax_ie_data ied;
  4219. struct iax2_peer *p;
  4220. ast_mutex_lock(&peerl.lock);
  4221. for (p = peerl.peers;p;p = p->next) {
  4222. if (!strcasecmp(name, p->name)) {
  4223. break;
  4224. }
  4225. }
  4226. ast_mutex_unlock(&peerl.lock);
  4227. #ifdef MYSQL_FRIENDS
  4228. if (!p)
  4229. p = mysql_peer(name);
  4230. #endif
  4231. if (p) {
  4232. memset(&ied, 0, sizeof(ied));
  4233. iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
  4234. if (p->authmethods & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
  4235. /* Build the challenge */
  4236. snprintf(iaxs[callno]->challenge, sizeof(iaxs[callno]->challenge), "%d", rand());
  4237. iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
  4238. }
  4239. iax_ie_append_str(&ied, IAX_IE_USERNAME, name);
  4240. if (p->temponly)
  4241. free(p);
  4242. return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1);;
  4243. }
  4244. ast_log(LOG_WARNING, "No such peer '%s'\n", name);
  4245. return 0;
  4246. }
  4247. static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
  4248. {
  4249. struct iax2_registry *reg;
  4250. /* Start pessimistic */
  4251. struct iax_ie_data ied;
  4252. char peer[256] = "";
  4253. char iabuf[INET_ADDRSTRLEN];
  4254. char challenge[256] = "";
  4255. int res;
  4256. int authmethods = 0;
  4257. if (ies->authmethods)
  4258. authmethods = ies->authmethods;
  4259. if (ies->username)
  4260. strncpy(peer, ies->username, sizeof(peer) - 1);
  4261. if (ies->challenge)
  4262. strncpy(challenge, ies->challenge, sizeof(challenge) - 1);
  4263. memset(&ied, 0, sizeof(ied));
  4264. reg = iaxs[callno]->reg;
  4265. if (reg) {
  4266. if (inaddrcmp(&reg->addr, sin)) {
  4267. ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
  4268. return -1;
  4269. }
  4270. if (ast_strlen_zero(reg->secret)) {
  4271. ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
  4272. reg->regstate = REG_STATE_NOAUTH;
  4273. return -1;
  4274. }
  4275. iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
  4276. iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
  4277. if (reg->secret[0] == '[') {
  4278. char tmpkey[256];
  4279. strncpy(tmpkey, reg->secret + 1, sizeof(tmpkey) - 1);
  4280. tmpkey[strlen(tmpkey) - 1] = '\0';
  4281. res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin);
  4282. } else
  4283. res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin);
  4284. if (!res) {
  4285. reg->regstate = REG_STATE_AUTHSENT;
  4286. return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
  4287. } else
  4288. return -1;
  4289. ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
  4290. } else
  4291. ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
  4292. return -1;
  4293. }
  4294. static int stop_stuff(int callno)
  4295. {
  4296. if (iaxs[callno]->lagid > -1)
  4297. ast_sched_del(sched, iaxs[callno]->lagid);
  4298. iaxs[callno]->lagid = -1;
  4299. if (iaxs[callno]->pingid > -1)
  4300. ast_sched_del(sched, iaxs[callno]->pingid);
  4301. iaxs[callno]->pingid = -1;
  4302. if (iaxs[callno]->autoid > -1)
  4303. ast_sched_del(sched, iaxs[callno]->autoid);
  4304. iaxs[callno]->autoid = -1;
  4305. if (iaxs[callno]->initid > -1)
  4306. ast_sched_del(sched, iaxs[callno]->initid);
  4307. iaxs[callno]->initid = -1;
  4308. if (iaxs[callno]->authid > -1)
  4309. ast_sched_del(sched, iaxs[callno]->authid);
  4310. iaxs[callno]->authid = -1;
  4311. return 0;
  4312. }
  4313. static int auth_reject(void *nothing)
  4314. {
  4315. /* Called from IAX thread only, without iaxs lock */
  4316. int callno = (int)(long)(nothing);
  4317. struct iax_ie_data ied;
  4318. ast_mutex_lock(&iaxsl[callno]);
  4319. if (iaxs[callno]) {
  4320. iaxs[callno]->authid = -1;
  4321. memset(&ied, 0, sizeof(ied));
  4322. if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
  4323. iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
  4324. } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
  4325. iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
  4326. }
  4327. send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
  4328. }
  4329. ast_mutex_unlock(&iaxsl[callno]);
  4330. return 0;
  4331. }
  4332. static int auth_fail(int callno, int failcode)
  4333. {
  4334. /* Schedule sending the authentication failure in one second, to prevent
  4335. guessing */
  4336. ast_mutex_lock(&iaxsl[callno]);
  4337. iaxs[callno]->authfail = failcode;
  4338. if (delayreject) {
  4339. ast_mutex_lock(&iaxsl[callno]);
  4340. if (iaxs[callno]->authid > -1)
  4341. ast_sched_del(sched, iaxs[callno]->authid);
  4342. iaxs[callno]->authid = ast_sched_add(sched, 1000, auth_reject, (void *)(long)callno);
  4343. ast_mutex_unlock(&iaxsl[callno]);
  4344. } else
  4345. auth_reject((void *)(long)callno);
  4346. ast_mutex_unlock(&iaxsl[callno]);
  4347. return 0;
  4348. }
  4349. static int auto_hangup(void *nothing)
  4350. {
  4351. /* Called from IAX thread only, without iaxs lock */
  4352. int callno = (int)(long)(nothing);
  4353. struct iax_ie_data ied;
  4354. ast_mutex_lock(&iaxsl[callno]);
  4355. if (iaxs[callno]) {
  4356. iaxs[callno]->autoid = -1;
  4357. memset(&ied, 0, sizeof(ied));
  4358. iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
  4359. send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
  4360. }
  4361. ast_mutex_unlock(&iaxsl[callno]);
  4362. return 0;
  4363. }
  4364. static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
  4365. {
  4366. struct iax_ie_data ied;
  4367. /* Auto-hangup with 30 seconds of inactivity */
  4368. if (iaxs[callno]->autoid > -1)
  4369. ast_sched_del(sched, iaxs[callno]->autoid);
  4370. iaxs[callno]->autoid = ast_sched_add(sched, 30000, auto_hangup, (void *)(long)callno);
  4371. memset(&ied, 0, sizeof(ied));
  4372. iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
  4373. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
  4374. dp->flags |= CACHE_FLAG_TRANSMITTED;
  4375. }
  4376. static int iax2_vnak(int callno)
  4377. {
  4378. return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
  4379. }
  4380. static void vnak_retransmit(int callno, int last)
  4381. {
  4382. struct iax_frame *f;
  4383. ast_mutex_lock(&iaxq.lock);
  4384. f = iaxq.head;
  4385. while(f) {
  4386. /* Send a copy immediately */
  4387. if ((f->callno == callno) && iaxs[f->callno] &&
  4388. (f->oseqno >= last)) {
  4389. send_packet(f);
  4390. }
  4391. f = f->next;
  4392. }
  4393. ast_mutex_unlock(&iaxq.lock);
  4394. }
  4395. static int iax2_poke_peer_s(void *data)
  4396. {
  4397. struct iax2_peer *peer = data;
  4398. peer->pokeexpire = -1;
  4399. iax2_poke_peer(peer, 0);
  4400. return 0;
  4401. }
  4402. static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
  4403. {
  4404. int res = 0;
  4405. struct iax_frame *fr;
  4406. struct ast_iax2_meta_hdr *meta;
  4407. struct ast_iax2_meta_trunk_hdr *mth;
  4408. int calls = 0;
  4409. /* Point to frame */
  4410. fr = (struct iax_frame *)tpeer->trunkdata;
  4411. /* Point to meta data */
  4412. meta = (struct ast_iax2_meta_hdr *)fr->afdata;
  4413. mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
  4414. if (tpeer->trunkdatalen) {
  4415. /* We're actually sending a frame, so fill the meta trunk header and meta header */
  4416. meta->zeros = 0;
  4417. meta->metacmd = IAX_META_TRUNK;
  4418. meta->cmddata = 0;
  4419. mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
  4420. /* And the rest of the ast_iax2 header */
  4421. fr->direction = DIRECTION_OUTGRESS;
  4422. fr->retrans = -1;
  4423. fr->transfer = 0;
  4424. /* Any appropriate call will do */
  4425. fr->data = fr->afdata;
  4426. fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
  4427. #if 0
  4428. ast_log(LOG_DEBUG, "Trunking %d calls in %d bytes, ts=%d\n", calls, fr->datalen, ntohl(mth->ts));
  4429. #endif
  4430. res = transmit_trunk(fr, &tpeer->addr);
  4431. calls = tpeer->calls;
  4432. /* Reset transmit trunk side data */
  4433. tpeer->trunkdatalen = 0;
  4434. tpeer->calls = 0;
  4435. }
  4436. if (res < 0)
  4437. return res;
  4438. return calls;
  4439. }
  4440. static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
  4441. {
  4442. /* Drop when trunk is about 5 seconds idle */
  4443. if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
  4444. return 1;
  4445. return 0;
  4446. }
  4447. static int timing_read(int *id, int fd, short events, void *cbdata)
  4448. {
  4449. char buf[1024];
  4450. int res;
  4451. char iabuf[INET_ADDRSTRLEN];
  4452. struct iax2_trunk_peer *tpeer, *prev = NULL, *drop=NULL;
  4453. int processed = 0;
  4454. int totalcalls = 0;
  4455. #ifdef ZT_TIMERACK
  4456. int x = 1;
  4457. #endif
  4458. struct timeval now;
  4459. if (iaxtrunkdebug)
  4460. ast_verbose("Beginning trunk processing\n");
  4461. gettimeofday(&now, NULL);
  4462. if (events & AST_IO_PRI) {
  4463. #ifdef ZT_TIMERACK
  4464. /* Great, this is a timing interface, just call the ioctl */
  4465. if (ioctl(fd, ZT_TIMERACK, &x))
  4466. ast_log(LOG_WARNING, "Unable to acknowledge zap timer\n");
  4467. res = 0;
  4468. #endif
  4469. } else {
  4470. /* Read and ignore from the pseudo channel for timing */
  4471. res = read(fd, buf, sizeof(buf));
  4472. if (res < 1) {
  4473. ast_log(LOG_WARNING, "Unable to read from timing fd\n");
  4474. ast_mutex_unlock(&peerl.lock);
  4475. return 1;
  4476. }
  4477. }
  4478. /* For each peer that supports trunking... */
  4479. ast_mutex_lock(&tpeerlock);
  4480. tpeer = tpeers;
  4481. while(tpeer) {
  4482. processed++;
  4483. res = 0;
  4484. ast_mutex_lock(&tpeer->lock);
  4485. /* We can drop a single tpeer per pass. That makes all this logic
  4486. substantially easier */
  4487. if (!drop && iax2_trunk_expired(tpeer, &now)) {
  4488. /* Take it out of the list, but don't free it yet, because it
  4489. could be in use */
  4490. if (prev)
  4491. prev->next = tpeer->next;
  4492. else
  4493. tpeers = tpeer->next;
  4494. drop = tpeer;
  4495. } else {
  4496. res = send_trunk(tpeer, &now);
  4497. if (iaxtrunkdebug)
  4498. ast_verbose("Processed trunk peer (%s:%d) with %d call(s)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), res);
  4499. }
  4500. totalcalls += res;
  4501. res = 0;
  4502. ast_mutex_unlock(&tpeer->lock);
  4503. prev = tpeer;
  4504. tpeer = tpeer->next;
  4505. }
  4506. ast_mutex_unlock(&tpeerlock);
  4507. if (drop) {
  4508. ast_mutex_lock(&drop->lock);
  4509. /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
  4510. because by the time they could get tpeerlock, we've already grabbed it */
  4511. ast_log(LOG_DEBUG, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), drop->addr.sin_addr), ntohs(drop->addr.sin_port));
  4512. free(drop->trunkdata);
  4513. ast_mutex_unlock(&drop->lock);
  4514. ast_mutex_destroy(&drop->lock);
  4515. free(drop);
  4516. }
  4517. if (iaxtrunkdebug)
  4518. ast_verbose("Ending trunk processing with %d peers and %d calls processed\n", processed, totalcalls);
  4519. iaxtrunkdebug =0;
  4520. return 1;
  4521. }
  4522. struct dpreq_data {
  4523. int callno;
  4524. char context[AST_MAX_EXTENSION];
  4525. char callednum[AST_MAX_EXTENSION];
  4526. char *callerid;
  4527. };
  4528. static void dp_lookup(int callno, char *context, char *callednum, char *callerid, int skiplock)
  4529. {
  4530. unsigned short dpstatus = 0;
  4531. struct iax_ie_data ied1;
  4532. int mm;
  4533. memset(&ied1, 0, sizeof(ied1));
  4534. mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
  4535. /* Must be started */
  4536. if (!strcmp(callednum, ast_parking_ext()) || ast_exists_extension(NULL, context, callednum, 1, callerid)) {
  4537. dpstatus = IAX_DPSTATUS_EXISTS;
  4538. } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
  4539. dpstatus = IAX_DPSTATUS_CANEXIST;
  4540. } else {
  4541. dpstatus = IAX_DPSTATUS_NONEXISTENT;
  4542. }
  4543. if (ast_ignore_pattern(context, callednum))
  4544. dpstatus |= IAX_DPSTATUS_IGNOREPAT;
  4545. if (mm)
  4546. dpstatus |= IAX_DPSTATUS_MATCHMORE;
  4547. if (!skiplock)
  4548. ast_mutex_lock(&iaxsl[callno]);
  4549. if (iaxs[callno]) {
  4550. iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
  4551. iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
  4552. iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
  4553. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
  4554. }
  4555. if (!skiplock)
  4556. ast_mutex_unlock(&iaxsl[callno]);
  4557. }
  4558. static void *dp_lookup_thread(void *data)
  4559. {
  4560. /* Look up for dpreq */
  4561. struct dpreq_data *dpr = data;
  4562. dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
  4563. if (dpr->callerid)
  4564. free(dpr->callerid);
  4565. free(dpr);
  4566. return NULL;
  4567. }
  4568. static void spawn_dp_lookup(int callno, char *context, char *callednum, char *callerid)
  4569. {
  4570. pthread_t newthread;
  4571. struct dpreq_data *dpr;
  4572. dpr = malloc(sizeof(struct dpreq_data));
  4573. if (dpr) {
  4574. memset(dpr, 0, sizeof(struct dpreq_data));
  4575. dpr->callno = callno;
  4576. strncpy(dpr->context, context, sizeof(dpr->context) - 1);
  4577. strncpy(dpr->callednum, callednum, sizeof(dpr->callednum) - 1);
  4578. if (callerid)
  4579. dpr->callerid = strdup(callerid);
  4580. if (ast_pthread_create(&newthread, NULL, dp_lookup_thread, dpr)) {
  4581. ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
  4582. }
  4583. } else
  4584. ast_log(LOG_WARNING, "Out of memory!\n");
  4585. }
  4586. struct iax_dual {
  4587. struct ast_channel *chan1;
  4588. struct ast_channel *chan2;
  4589. };
  4590. static void *iax_park_thread(void *stuff)
  4591. {
  4592. struct ast_channel *chan1, *chan2;
  4593. struct iax_dual *d;
  4594. struct ast_frame *f;
  4595. int ext;
  4596. int res;
  4597. d = stuff;
  4598. chan1 = d->chan1;
  4599. chan2 = d->chan2;
  4600. free(d);
  4601. f = ast_read(chan1);
  4602. if (f)
  4603. ast_frfree(f);
  4604. res = ast_park_call(chan1, chan2, 0, &ext);
  4605. ast_hangup(chan2);
  4606. ast_log(LOG_DEBUG, "Parked on extension '%d'\n", ext);
  4607. return NULL;
  4608. }
  4609. static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2)
  4610. {
  4611. struct iax_dual *d;
  4612. struct ast_channel *chan1m, *chan2m;
  4613. pthread_t th;
  4614. chan1m = ast_channel_alloc(0);
  4615. chan2m = ast_channel_alloc(0);
  4616. if (chan2m && chan1m) {
  4617. snprintf(chan1m->name, sizeof(chan1m->name), "Parking/%s", chan1->name);
  4618. /* Make formats okay */
  4619. chan1m->readformat = chan1->readformat;
  4620. chan1m->writeformat = chan1->writeformat;
  4621. ast_channel_masquerade(chan1m, chan1);
  4622. /* Setup the extensions and such */
  4623. strncpy(chan1m->context, chan1->context, sizeof(chan1m->context) - 1);
  4624. strncpy(chan1m->exten, chan1->exten, sizeof(chan1m->exten) - 1);
  4625. chan1m->priority = chan1->priority;
  4626. /* We make a clone of the peer channel too, so we can play
  4627. back the announcement */
  4628. snprintf(chan2m->name, sizeof (chan2m->name), "IAXPeer/%s",chan2->name);
  4629. /* Make formats okay */
  4630. chan2m->readformat = chan2->readformat;
  4631. chan2m->writeformat = chan2->writeformat;
  4632. ast_channel_masquerade(chan2m, chan2);
  4633. /* Setup the extensions and such */
  4634. strncpy(chan2m->context, chan2->context, sizeof(chan2m->context) - 1);
  4635. strncpy(chan2m->exten, chan2->exten, sizeof(chan2m->exten) - 1);
  4636. chan2m->priority = chan2->priority;
  4637. if (ast_do_masquerade(chan2m)) {
  4638. ast_log(LOG_WARNING, "Masquerade failed :(\n");
  4639. ast_hangup(chan2m);
  4640. return -1;
  4641. }
  4642. } else {
  4643. if (chan1m)
  4644. ast_hangup(chan1m);
  4645. if (chan2m)
  4646. ast_hangup(chan2m);
  4647. return -1;
  4648. }
  4649. d = malloc(sizeof(struct iax_dual));
  4650. if (d) {
  4651. memset(d, 0, sizeof(*d));
  4652. d->chan1 = chan1m;
  4653. d->chan2 = chan2m;
  4654. if (!ast_pthread_create(&th, NULL, iax_park_thread, d))
  4655. return 0;
  4656. free(d);
  4657. }
  4658. return -1;
  4659. }
  4660. static int iax2_provision(struct sockaddr_in *end, char *dest, const char *template, int force);
  4661. static int check_provisioning(struct sockaddr_in *sin, char *si, unsigned int ver)
  4662. {
  4663. unsigned int ourver;
  4664. unsigned char rsi[80];
  4665. snprintf(rsi, sizeof(rsi), "si-%s", si);
  4666. if (iax_provision_version(&ourver, rsi, 1))
  4667. return 0;
  4668. if (option_debug)
  4669. ast_log(LOG_DEBUG, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
  4670. if (ourver != ver)
  4671. iax2_provision(sin, NULL, rsi, 1);
  4672. return 0;
  4673. }
  4674. static int socket_read(int *id, int fd, short events, void *cbdata)
  4675. {
  4676. struct sockaddr_in sin;
  4677. int res;
  4678. int updatehistory=1;
  4679. int new = NEW_PREVENT;
  4680. char buf[4096], *ptr;
  4681. int len = sizeof(sin);
  4682. int dcallno = 0;
  4683. struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)buf;
  4684. struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)buf;
  4685. struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)buf;
  4686. struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)buf;
  4687. struct ast_iax2_meta_trunk_hdr *mth;
  4688. struct ast_iax2_meta_trunk_entry *mte;
  4689. char dblbuf[4096]; /* Declaration of dblbuf must immediately *preceed* fr on the stack */
  4690. struct iax_frame fr;
  4691. struct iax_frame *cur;
  4692. char iabuf[INET_ADDRSTRLEN];
  4693. struct ast_frame f;
  4694. struct ast_channel *c;
  4695. struct iax2_dpcache *dp;
  4696. struct iax2_peer *peer;
  4697. struct iax2_trunk_peer *tpeer;
  4698. struct timeval rxtrunktime;
  4699. struct iax_ies ies;
  4700. struct iax_ie_data ied0, ied1;
  4701. int format;
  4702. int exists;
  4703. int minivid = 0;
  4704. unsigned int ts;
  4705. char empty[32]=""; /* Safety measure */
  4706. struct iax_frame *duped_fr;
  4707. dblbuf[0] = 0; /* Keep GCC from whining */
  4708. fr.callno = 0;
  4709. res = recvfrom(netsocket, buf, sizeof(buf), 0,(struct sockaddr *) &sin, &len);
  4710. if (res < 0) {
  4711. if (errno != ECONNREFUSED)
  4712. ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
  4713. handle_error();
  4714. return 1;
  4715. }
  4716. if (res < sizeof(struct ast_iax2_mini_hdr)) {
  4717. ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int)sizeof(struct ast_iax2_mini_hdr));
  4718. return 1;
  4719. }
  4720. if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
  4721. if (res < sizeof(*vh)) {
  4722. ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a mini video frame but is too short\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
  4723. return 1;
  4724. }
  4725. /* This is a video frame, get call number */
  4726. fr.callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, 1);
  4727. minivid = 1;
  4728. } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000)) {
  4729. if (res < sizeof(*meta)) {
  4730. ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a meta frame but is too short\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
  4731. return 1;
  4732. }
  4733. /* This is a meta header */
  4734. switch(meta->metacmd) {
  4735. case IAX_META_TRUNK:
  4736. if (meta->cmddata != 0) {
  4737. ast_log(LOG_WARNING, "meta trunk cmd %d received, I only understand 0 (perhaps the remote side is sending trunk timestamps?)\n", meta->cmddata);
  4738. return 1;
  4739. }
  4740. if (res < sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr)) {
  4741. ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %d min)\n", res, (int)sizeof(struct ast_iax2_mini_hdr));
  4742. return 1;
  4743. }
  4744. mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
  4745. ts = ntohl(mth->ts);
  4746. res -= (sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr));
  4747. ptr = mth->data;
  4748. tpeer = find_tpeer(&sin);
  4749. if (!tpeer) {
  4750. ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s:%d': No matching peer\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
  4751. return 1;
  4752. }
  4753. if (!ts || (!tpeer->rxtrunktime.tv_sec && !tpeer->rxtrunktime.tv_usec)) {
  4754. gettimeofday(&tpeer->rxtrunktime, NULL);
  4755. tpeer->trunkact = tpeer->rxtrunktime;
  4756. } else
  4757. gettimeofday(&tpeer->trunkact, NULL);
  4758. rxtrunktime = tpeer->rxtrunktime;
  4759. ast_mutex_unlock(&tpeer->lock);
  4760. while(res >= sizeof(struct ast_iax2_meta_trunk_entry)) {
  4761. /* Process channels */
  4762. mte = (struct ast_iax2_meta_trunk_entry *)ptr;
  4763. ptr += sizeof(struct ast_iax2_meta_trunk_entry);
  4764. res -= sizeof(struct ast_iax2_meta_trunk_entry);
  4765. len = ntohs(mte->len);
  4766. /* Stop if we don't have enough data */
  4767. if (len > res)
  4768. break;
  4769. fr.callno = find_callno(ntohs(mte->callno) & ~IAX_FLAG_FULL, 0, &sin, NEW_PREVENT, 1);
  4770. if (fr.callno) {
  4771. ast_mutex_lock(&iaxsl[fr.callno]);
  4772. /* If it's a valid call, deliver the contents. If not, we
  4773. drop it, since we don't have a scallno to use for an INVAL */
  4774. /* Process as a mini frame */
  4775. f.frametype = AST_FRAME_VOICE;
  4776. if (iaxs[fr.callno]) {
  4777. if (iaxs[fr.callno]->voiceformat > 0) {
  4778. f.subclass = iaxs[fr.callno]->voiceformat;
  4779. f.datalen = len;
  4780. if (f.datalen >= 0) {
  4781. if (f.datalen)
  4782. f.data = ptr;
  4783. else
  4784. f.data = NULL;
  4785. fr.ts = fix_peerts(&rxtrunktime, fr.callno, ts);
  4786. /* Don't pass any packets until we're started */
  4787. if ((iaxs[fr.callno]->state & IAX_STATE_STARTED)) {
  4788. /* Common things */
  4789. f.src = "IAX2";
  4790. f.mallocd = 0;
  4791. f.offset = 0;
  4792. if (f.datalen && (f.frametype == AST_FRAME_VOICE))
  4793. f.samples = get_samples(&f);
  4794. else
  4795. f.samples = 0;
  4796. fr.outoforder = 0;
  4797. iax_frame_wrap(&fr, &f);
  4798. #ifdef BRIDGE_OPTIMIZATION
  4799. if (iaxs[fr.callno]->bridgecallno) {
  4800. forward_delivery(&fr);
  4801. } else {
  4802. schedule_delivery(iaxfrdup2(&fr), 1, updatehistory, 1);
  4803. }
  4804. #else
  4805. schedule_delivery(iaxfrdup2(&fr), 1, updatehistory, 1);
  4806. #endif
  4807. }
  4808. } else {
  4809. ast_log(LOG_WARNING, "Datalen < 0?\n");
  4810. }
  4811. } else {
  4812. ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n ");
  4813. iax2_vnak(fr.callno);
  4814. }
  4815. }
  4816. ast_mutex_unlock(&iaxsl[fr.callno]);
  4817. }
  4818. ptr += len;
  4819. res -= len;
  4820. }
  4821. }
  4822. return 1;
  4823. }
  4824. #ifdef DEBUG_SUPPORT
  4825. if (iaxdebug)
  4826. iax_showframe(NULL, fh, 1, &sin, res - sizeof(struct ast_iax2_full_hdr));
  4827. #endif
  4828. if ((res >= sizeof(*fh)) && ntohs(mh->callno) & IAX_FLAG_FULL) {
  4829. /* Get the destination call number */
  4830. dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
  4831. /* Retrieve the type and subclass */
  4832. f.frametype = fh->type;
  4833. if (f.frametype == AST_FRAME_VIDEO) {
  4834. f.subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
  4835. } else {
  4836. f.subclass = uncompress_subclass(fh->csub);
  4837. }
  4838. if ((f.frametype == AST_FRAME_IAX) && ((f.subclass == IAX_COMMAND_NEW) || (f.subclass == IAX_COMMAND_REGREQ)
  4839. || (f.subclass == IAX_COMMAND_POKE) || (f.subclass == IAX_COMMAND_FWDOWNL)))
  4840. new = NEW_ALLOW;
  4841. } else {
  4842. /* Don't know anything about it yet */
  4843. f.frametype = AST_FRAME_NULL;
  4844. f.subclass = 0;
  4845. }
  4846. if (!fr.callno)
  4847. fr.callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, new, 1);
  4848. if (fr.callno > 0)
  4849. ast_mutex_lock(&iaxsl[fr.callno]);
  4850. if (!fr.callno || !iaxs[fr.callno]) {
  4851. /* A call arrived for a nonexistent destination. Unless it's an "inval"
  4852. frame, reply with an inval */
  4853. if (ntohs(mh->callno) & IAX_FLAG_FULL) {
  4854. /* We can only raw hangup control frames */
  4855. if (((f.subclass != IAX_COMMAND_INVAL) &&
  4856. (f.subclass != IAX_COMMAND_TXCNT) &&
  4857. (f.subclass != IAX_COMMAND_TXACC) &&
  4858. (f.subclass != IAX_COMMAND_FWDOWNL))||
  4859. (f.frametype != AST_FRAME_IAX))
  4860. raw_hangup(&sin, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL
  4861. );
  4862. }
  4863. if (fr.callno > 0)
  4864. ast_mutex_unlock(&iaxsl[fr.callno]);
  4865. return 1;
  4866. }
  4867. if (!inaddrcmp(&sin, &iaxs[fr.callno]->addr) && !minivid &&
  4868. f.subclass != IAX_COMMAND_TXCNT && /* for attended transfer */
  4869. f.subclass != IAX_COMMAND_TXACC) /* for attended transfer */
  4870. iaxs[fr.callno]->peercallno = (unsigned short)(ntohs(mh->callno) & ~IAX_FLAG_FULL);
  4871. if (ntohs(mh->callno) & IAX_FLAG_FULL) {
  4872. if (option_debug)
  4873. ast_log(LOG_DEBUG, "Received packet %d, (%d, %d)\n", fh->oseqno, f.frametype, f.subclass);
  4874. /* Check if it's out of order (and not an ACK or INVAL) */
  4875. fr.oseqno = fh->oseqno;
  4876. fr.iseqno = fh->iseqno;
  4877. fr.ts = ntohl(fh->ts);
  4878. #if 0
  4879. if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
  4880. ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
  4881. (f.subclass == IAX_COMMAND_NEW ||
  4882. f.subclass == IAX_COMMAND_AUTHREQ ||
  4883. f.subclass == IAX_COMMAND_ACCEPT ||
  4884. f.subclass == IAX_COMMAND_REJECT)) ) )
  4885. #endif
  4886. if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
  4887. updatehistory = 0;
  4888. if ((iaxs[fr.callno]->iseqno != fr.oseqno) &&
  4889. (iaxs[fr.callno]->iseqno ||
  4890. ((f.subclass != IAX_COMMAND_TXCNT) &&
  4891. (f.subclass != IAX_COMMAND_TXREADY) && /* for attended transfer */
  4892. (f.subclass != IAX_COMMAND_TXREL) && /* for attended transfer */
  4893. (f.subclass != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
  4894. (f.subclass != IAX_COMMAND_TXACC)) ||
  4895. (f.frametype != AST_FRAME_IAX))) {
  4896. if (
  4897. ((f.subclass != IAX_COMMAND_ACK) &&
  4898. (f.subclass != IAX_COMMAND_INVAL) &&
  4899. (f.subclass != IAX_COMMAND_TXCNT) &&
  4900. (f.subclass != IAX_COMMAND_TXREADY) && /* for attended transfer */
  4901. (f.subclass != IAX_COMMAND_TXREL) && /* for attended transfer */
  4902. (f.subclass != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
  4903. (f.subclass != IAX_COMMAND_TXACC) &&
  4904. (f.subclass != IAX_COMMAND_VNAK)) ||
  4905. (f.frametype != AST_FRAME_IAX)) {
  4906. /* If it's not an ACK packet, it's out of order. */
  4907. if (option_debug)
  4908. ast_log(LOG_DEBUG, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
  4909. iaxs[fr.callno]->iseqno, fr.oseqno, f.frametype, f.subclass);
  4910. if (iaxs[fr.callno]->iseqno > fr.oseqno) {
  4911. /* If we've already seen it, ack it XXX There's a border condition here XXX */
  4912. if ((f.frametype != AST_FRAME_IAX) ||
  4913. ((f.subclass != IAX_COMMAND_ACK) && (f.subclass != IAX_COMMAND_INVAL))) {
  4914. if (option_debug)
  4915. ast_log(LOG_DEBUG, "Acking anyway\n");
  4916. /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
  4917. we have anything to send, we'll retransmit and get an ACK back anyway XXX */
  4918. send_command_immediate(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.iseqno);
  4919. }
  4920. } else {
  4921. /* Send a VNAK requesting retransmission */
  4922. iax2_vnak(fr.callno);
  4923. }
  4924. ast_mutex_unlock(&iaxsl[fr.callno]);
  4925. return 1;
  4926. }
  4927. } else {
  4928. /* Increment unless it's an ACK or VNAK */
  4929. if (((f.subclass != IAX_COMMAND_ACK) &&
  4930. (f.subclass != IAX_COMMAND_INVAL) &&
  4931. (f.subclass != IAX_COMMAND_TXCNT) &&
  4932. (f.subclass != IAX_COMMAND_TXACC) &&
  4933. (f.subclass != IAX_COMMAND_VNAK)) ||
  4934. (f.frametype != AST_FRAME_IAX))
  4935. iaxs[fr.callno]->iseqno++;
  4936. }
  4937. /* A full frame */
  4938. if (res < sizeof(struct ast_iax2_full_hdr)) {
  4939. ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int)sizeof(struct ast_iax2_full_hdr));
  4940. ast_mutex_unlock(&iaxsl[fr.callno]);
  4941. return 1;
  4942. }
  4943. f.datalen = res - sizeof(struct ast_iax2_full_hdr);
  4944. /* Handle implicit ACKing unless this is an INVAL, and only if this is
  4945. from the real peer, not the transfer peer */
  4946. if (!inaddrcmp(&sin, &iaxs[fr.callno]->addr) &&
  4947. (((f.subclass != IAX_COMMAND_INVAL)) ||
  4948. (f.frametype != AST_FRAME_IAX))) {
  4949. unsigned char x;
  4950. /* XXX This code is not very efficient. Surely there is a better way which still
  4951. properly handles boundary conditions? XXX */
  4952. /* First we have to qualify that the ACKed value is within our window */
  4953. for (x=iaxs[fr.callno]->rseqno; x != iaxs[fr.callno]->oseqno; x++)
  4954. if (fr.iseqno == x)
  4955. break;
  4956. if ((x != iaxs[fr.callno]->oseqno) || (iaxs[fr.callno]->oseqno == fr.iseqno)) {
  4957. /* The acknowledgement is within our window. Time to acknowledge everything
  4958. that it says to */
  4959. for (x=iaxs[fr.callno]->rseqno; x != fr.iseqno; x++) {
  4960. /* Ack the packet with the given timestamp */
  4961. if (option_debug)
  4962. ast_log(LOG_DEBUG, "Cancelling transmission of packet %d\n", x);
  4963. ast_mutex_lock(&iaxq.lock);
  4964. for (cur = iaxq.head; cur ; cur = cur->next) {
  4965. /* If it's our call, and our timestamp, mark -1 retries */
  4966. if ((fr.callno == cur->callno) && (x == cur->oseqno)) {
  4967. cur->retries = -1;
  4968. /* Destroy call if this is the end */
  4969. if (cur->final) {
  4970. if (option_debug)
  4971. ast_log(LOG_DEBUG, "Really destroying %d, having been acked on final message\n", fr.callno);
  4972. iax2_destroy_nolock(fr.callno);
  4973. }
  4974. }
  4975. }
  4976. ast_mutex_unlock(&iaxq.lock);
  4977. }
  4978. /* Note how much we've received acknowledgement for */
  4979. if (iaxs[fr.callno])
  4980. iaxs[fr.callno]->rseqno = fr.iseqno;
  4981. else {
  4982. /* Stop processing now */
  4983. ast_mutex_unlock(&iaxsl[fr.callno]);
  4984. return 1;
  4985. }
  4986. } else
  4987. ast_log(LOG_DEBUG, "Received iseqno %d not within window %d->%d\n", fr.iseqno, iaxs[fr.callno]->rseqno, iaxs[fr.callno]->oseqno);
  4988. }
  4989. if (inaddrcmp(&sin, &iaxs[fr.callno]->addr) &&
  4990. ((f.frametype != AST_FRAME_IAX) ||
  4991. ((f.subclass != IAX_COMMAND_TXACC) &&
  4992. (f.subclass != IAX_COMMAND_TXCNT)))) {
  4993. /* Only messages we accept from a transfer host are TXACC and TXCNT */
  4994. ast_mutex_unlock(&iaxsl[fr.callno]);
  4995. return 1;
  4996. }
  4997. if (f.datalen) {
  4998. if (f.frametype == AST_FRAME_IAX) {
  4999. if (iax_parse_ies(&ies, buf + sizeof(struct ast_iax2_full_hdr), f.datalen)) {
  5000. ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr));
  5001. ast_mutex_unlock(&iaxsl[fr.callno]);
  5002. return 1;
  5003. }
  5004. f.data = NULL;
  5005. } else
  5006. f.data = buf + sizeof(struct ast_iax2_full_hdr);
  5007. } else {
  5008. if (f.frametype == AST_FRAME_IAX)
  5009. f.data = NULL;
  5010. else
  5011. f.data = empty;
  5012. memset(&ies, 0, sizeof(ies));
  5013. }
  5014. if (f.frametype == AST_FRAME_VOICE) {
  5015. if (f.subclass != iaxs[fr.callno]->voiceformat) {
  5016. iaxs[fr.callno]->voiceformat = f.subclass;
  5017. ast_log(LOG_DEBUG, "Ooh, voice format changed to %d\n", f.subclass);
  5018. if (iaxs[fr.callno]->owner) {
  5019. int orignative;
  5020. retryowner:
  5021. if (ast_mutex_trylock(&iaxs[fr.callno]->owner->lock)) {
  5022. ast_mutex_unlock(&iaxsl[fr.callno]);
  5023. usleep(1);
  5024. ast_mutex_lock(&iaxsl[fr.callno]);
  5025. if (iaxs[fr.callno] && iaxs[fr.callno]->owner) goto retryowner;
  5026. }
  5027. if (iaxs[fr.callno]) {
  5028. if (iaxs[fr.callno]->owner) {
  5029. orignative = iaxs[fr.callno]->owner->nativeformats;
  5030. iaxs[fr.callno]->owner->nativeformats = f.subclass;
  5031. if (iaxs[fr.callno]->owner->readformat)
  5032. ast_set_read_format(iaxs[fr.callno]->owner, iaxs[fr.callno]->owner->readformat);
  5033. iaxs[fr.callno]->owner->nativeformats = orignative;
  5034. ast_mutex_unlock(&iaxs[fr.callno]->owner->lock);
  5035. }
  5036. } else {
  5037. ast_log(LOG_DEBUG, "Neat, somebody took away the channel at a magical time but i found it!\n");
  5038. ast_mutex_unlock(&iaxsl[fr.callno]);
  5039. return 1;
  5040. }
  5041. }
  5042. }
  5043. }
  5044. if (f.frametype == AST_FRAME_VIDEO) {
  5045. if (f.subclass != iaxs[fr.callno]->videoformat) {
  5046. ast_log(LOG_DEBUG, "Ooh, video format changed to %d\n", f.subclass & ~0x1);
  5047. iaxs[fr.callno]->videoformat = f.subclass & ~0x1;
  5048. }
  5049. }
  5050. if (f.frametype == AST_FRAME_IAX) {
  5051. if (iaxs[fr.callno]->initid > -1) {
  5052. /* Don't auto congest anymore since we've gotten something usefulb ack */
  5053. ast_sched_del(sched, iaxs[fr.callno]->initid);
  5054. iaxs[fr.callno]->initid = -1;
  5055. }
  5056. /* Handle the IAX pseudo frame itself */
  5057. if (option_debug)
  5058. ast_log(LOG_DEBUG, "IAX subclass %d received\n", f.subclass);
  5059. /* Go through the motions of delivering the packet without actually doing so */
  5060. schedule_delivery(&fr, 0, updatehistory, 0);
  5061. switch(f.subclass) {
  5062. case IAX_COMMAND_ACK:
  5063. /* Do nothing */
  5064. break;
  5065. case IAX_COMMAND_QUELCH:
  5066. if (iaxs[fr.callno]->state & IAX_STATE_STARTED) {
  5067. iaxs[fr.callno]->quelch = 1;
  5068. if (ies.musiconhold) {
  5069. if (iaxs[fr.callno]->owner &&
  5070. iaxs[fr.callno]->owner->bridge)
  5071. ast_moh_start(iaxs[fr.callno]->owner->bridge, NULL);
  5072. }
  5073. }
  5074. break;
  5075. case IAX_COMMAND_UNQUELCH:
  5076. if (iaxs[fr.callno]->state & IAX_STATE_STARTED) {
  5077. iaxs[fr.callno]->quelch = 0;
  5078. if (iaxs[fr.callno]->owner &&
  5079. iaxs[fr.callno]->owner->bridge)
  5080. ast_moh_stop(iaxs[fr.callno]->owner->bridge);
  5081. }
  5082. break;
  5083. case IAX_COMMAND_TXACC:
  5084. if (iaxs[fr.callno]->transferring == TRANSFER_BEGIN) {
  5085. /* Ack the packet with the given timestamp */
  5086. ast_mutex_lock(&iaxq.lock);
  5087. for (cur = iaxq.head; cur ; cur = cur->next) {
  5088. /* Cancel any outstanding txcnt's */
  5089. if ((fr.callno == cur->callno) && (cur->transfer))
  5090. cur->retries = -1;
  5091. }
  5092. ast_mutex_unlock(&iaxq.lock);
  5093. memset(&ied1, 0, sizeof(ied1));
  5094. iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr.callno]->callno);
  5095. send_command(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
  5096. iaxs[fr.callno]->transferring = TRANSFER_READY;
  5097. }
  5098. break;
  5099. case IAX_COMMAND_NEW:
  5100. /* Ignore if it's already up */
  5101. if (iaxs[fr.callno]->state & (IAX_STATE_STARTED | IAX_STATE_TBD))
  5102. break;
  5103. if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr)
  5104. check_provisioning(&sin, ies.serviceident, ies.provver);
  5105. /* For security, always ack immediately */
  5106. if (delayreject)
  5107. send_command_immediate(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.iseqno);
  5108. if (check_access(fr.callno, &sin, &ies)) {
  5109. /* They're not allowed on */
  5110. auth_fail(fr.callno, IAX_COMMAND_REJECT);
  5111. if (authdebug)
  5112. ast_log(LOG_NOTICE, "Rejected connect attempt from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr));
  5113. break;
  5114. }
  5115. /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
  5116. if (iaxs[fr.callno]->trunk) {
  5117. fr.callno = make_trunk(fr.callno, 1);
  5118. }
  5119. /* This might re-enter the IAX code and need the lock */
  5120. if (strcasecmp(iaxs[fr.callno]->exten, "TBD")) {
  5121. ast_mutex_unlock(&iaxsl[fr.callno]);
  5122. exists = ast_exists_extension(NULL, iaxs[fr.callno]->context, iaxs[fr.callno]->exten, 1, iaxs[fr.callno]->callerid);
  5123. ast_mutex_lock(&iaxsl[fr.callno]);
  5124. } else
  5125. exists = 0;
  5126. if (ast_strlen_zero(iaxs[fr.callno]->secret) && ast_strlen_zero(iaxs[fr.callno]->inkeys)) {
  5127. if (strcmp(iaxs[fr.callno]->exten, "TBD") && !exists) {
  5128. memset(&ied0, 0, sizeof(ied0));
  5129. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
  5130. send_command_final(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  5131. if (authdebug)
  5132. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), iaxs[fr.callno]->exten, iaxs[fr.callno]->context);
  5133. } else {
  5134. /* Select an appropriate format */
  5135. format = iaxs[fr.callno]->peerformat & iaxs[fr.callno]->capability;
  5136. if (!format) {
  5137. format = iaxs[fr.callno]->peercapability & iaxs[fr.callno]->capability;
  5138. if (!format) {
  5139. memset(&ied0, 0, sizeof(ied0));
  5140. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
  5141. send_command_final(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  5142. if (authdebug)
  5143. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), iaxs[fr.callno]->peerformat, iaxs[fr.callno]->peercapability, iaxs[fr.callno]->capability);
  5144. } else {
  5145. /* Pick one... */
  5146. format = ast_best_codec(iaxs[fr.callno]->peercapability & iaxs[fr.callno]->capability);
  5147. if (!format) {
  5148. memset(&ied0, 0, sizeof(ied0));
  5149. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
  5150. ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr.callno]->peercapability & iaxs[fr.callno]->capability);
  5151. send_command_final(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  5152. if (authdebug)
  5153. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), iaxs[fr.callno]->peerformat, iaxs[fr.callno]->peercapability, iaxs[fr.callno]->capability);
  5154. iaxs[fr.callno]->alreadygone = 1;
  5155. break;
  5156. }
  5157. }
  5158. }
  5159. if (format) {
  5160. /* No authentication required, let them in */
  5161. memset(&ied1, 0, sizeof(ied1));
  5162. iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
  5163. send_command(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
  5164. if (strcmp(iaxs[fr.callno]->exten, "TBD")) {
  5165. iaxs[fr.callno]->state |= IAX_STATE_STARTED;
  5166. if (option_verbose > 2)
  5167. ast_verbose(VERBOSE_PREFIX_3 "Accepting unauthenticated call from %s, requested format = %d, actual format = %d\n",
  5168. ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), iaxs[fr.callno]->peerformat,format);
  5169. if(!(c = ast_iax2_new(fr.callno, AST_STATE_RING, format)))
  5170. iax2_destroy_nolock(fr.callno);
  5171. } else {
  5172. iaxs[fr.callno]->state |= IAX_STATE_TBD;
  5173. /* If this is a TBD call, we're ready but now what... */
  5174. if (option_verbose > 2)
  5175. ast_verbose(VERBOSE_PREFIX_3 "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr));
  5176. }
  5177. }
  5178. }
  5179. break;
  5180. }
  5181. authenticate_request(iaxs[fr.callno]);
  5182. iaxs[fr.callno]->state |= IAX_STATE_AUTHENTICATED;
  5183. break;
  5184. case IAX_COMMAND_DPREQ:
  5185. /* Request status in the dialplan */
  5186. if ((iaxs[fr.callno]->state & IAX_STATE_TBD) &&
  5187. !(iaxs[fr.callno]->state & IAX_STATE_STARTED) && ies.called_number) {
  5188. if (iaxcompat) {
  5189. /* Spawn a thread for the lookup */
  5190. spawn_dp_lookup(fr.callno, iaxs[fr.callno]->context, ies.called_number, iaxs[fr.callno]->callerid);
  5191. } else {
  5192. /* Just look it up */
  5193. dp_lookup(fr.callno, iaxs[fr.callno]->context, ies.called_number, iaxs[fr.callno]->callerid, 1);
  5194. }
  5195. }
  5196. break;
  5197. case IAX_COMMAND_HANGUP:
  5198. iaxs[fr.callno]->alreadygone = 1;
  5199. ast_log(LOG_DEBUG, "Immediately destroying %d, having received hangup\n", fr.callno);
  5200. /* Send ack immediately, before we destroy */
  5201. send_command_immediate(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.iseqno);
  5202. iax2_destroy_nolock(fr.callno);
  5203. break;
  5204. case IAX_COMMAND_REJECT:
  5205. memset(&f, 0, sizeof(f));
  5206. f.frametype = AST_FRAME_CONTROL;
  5207. f.subclass = AST_CONTROL_CONGESTION;
  5208. iax2_queue_frame(fr.callno, &f);
  5209. if (iaxs[fr.callno]->provision) {
  5210. /* Send ack immediately, before we destroy */
  5211. send_command_immediate(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.iseqno);
  5212. iax2_destroy_nolock(fr.callno);
  5213. break;
  5214. }
  5215. if (iaxs[fr.callno]->owner) {
  5216. if (authdebug)
  5217. ast_log(LOG_WARNING, "Call rejected by %s: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[fr.callno]->addr.sin_addr), ies.cause ? ies.cause : "<Unknown>");
  5218. }
  5219. ast_log(LOG_DEBUG, "Immediately destroying %d, having received reject\n", fr.callno);
  5220. /* Send ack immediately, before we destroy */
  5221. send_command_immediate(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.iseqno);
  5222. iaxs[fr.callno]->error = EPERM;
  5223. iax2_destroy_nolock(fr.callno);
  5224. break;
  5225. case IAX_COMMAND_TRANSFER:
  5226. if (iaxs[fr.callno]->owner && iaxs[fr.callno]->owner->bridge && ies.called_number) {
  5227. if (!strcmp(ies.called_number, ast_parking_ext())) {
  5228. if (iax_park(iaxs[fr.callno]->owner->bridge, iaxs[fr.callno]->owner)) {
  5229. ast_log(LOG_WARNING, "Failed to park call on '%s'\n", iaxs[fr.callno]->owner->bridge->name);
  5230. } else
  5231. ast_log(LOG_DEBUG, "Parked call on '%s'\n", iaxs[fr.callno]->owner->bridge->name);
  5232. } else {
  5233. if (ast_async_goto(iaxs[fr.callno]->owner->bridge, iaxs[fr.callno]->context, ies.called_number, 1))
  5234. ast_log(LOG_WARNING, "Async goto of '%s' to '%s@%s' failed\n", iaxs[fr.callno]->owner->bridge->name,
  5235. ies.called_number, iaxs[fr.callno]->context);
  5236. else
  5237. ast_log(LOG_DEBUG, "Async goto of '%s' to '%s@%s' started\n", iaxs[fr.callno]->owner->bridge->name,
  5238. ies.called_number, iaxs[fr.callno]->context);
  5239. }
  5240. } else
  5241. ast_log(LOG_DEBUG, "Async goto not applicable on call %d\n", fr.callno);
  5242. break;
  5243. case IAX_COMMAND_ACCEPT:
  5244. /* Ignore if call is already up or needs authentication or is a TBD */
  5245. if (iaxs[fr.callno]->state & (IAX_STATE_STARTED | IAX_STATE_TBD | IAX_STATE_AUTHENTICATED))
  5246. break;
  5247. if (iaxs[fr.callno]->provision) {
  5248. /* Send ack immediately, before we destroy */
  5249. send_command_immediate(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.iseqno);
  5250. iax2_destroy_nolock(fr.callno);
  5251. break;
  5252. }
  5253. if (ies.format) {
  5254. iaxs[fr.callno]->peerformat = ies.format;
  5255. } else {
  5256. if (iaxs[fr.callno]->owner)
  5257. iaxs[fr.callno]->peerformat = iaxs[fr.callno]->owner->nativeformats;
  5258. else
  5259. iaxs[fr.callno]->peerformat = iaxs[fr.callno]->capability;
  5260. }
  5261. if (option_verbose > 2)
  5262. ast_verbose(VERBOSE_PREFIX_3 "Call accepted by %s (format %s)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[fr.callno]->addr.sin_addr), ast_getformatname(iaxs[fr.callno]->peerformat));
  5263. if (!(iaxs[fr.callno]->peerformat & iaxs[fr.callno]->capability)) {
  5264. memset(&ied0, 0, sizeof(ied0));
  5265. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
  5266. send_command_final(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  5267. if (authdebug)
  5268. ast_log(LOG_NOTICE, "Rejected call to %s, format 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), iaxs[fr.callno]->peerformat, iaxs[fr.callno]->capability);
  5269. } else {
  5270. iaxs[fr.callno]->state |= IAX_STATE_STARTED;
  5271. if (iaxs[fr.callno]->owner) {
  5272. /* Switch us to use a compatible format */
  5273. iaxs[fr.callno]->owner->nativeformats = iaxs[fr.callno]->peerformat;
  5274. if (option_verbose > 2)
  5275. ast_verbose(VERBOSE_PREFIX_3 "Format for call is %s\n", ast_getformatname(iaxs[fr.callno]->owner->nativeformats));
  5276. retryowner2:
  5277. if (ast_mutex_trylock(&iaxs[fr.callno]->owner->lock)) {
  5278. ast_mutex_unlock(&iaxsl[fr.callno]);
  5279. usleep(1);
  5280. ast_mutex_lock(&iaxsl[fr.callno]);
  5281. if (iaxs[fr.callno] && iaxs[fr.callno]->owner) goto retryowner2;
  5282. }
  5283. if (iaxs[fr.callno] && iaxs[fr.callno]->owner) {
  5284. /* Setup read/write formats properly. */
  5285. if (iaxs[fr.callno]->owner->writeformat)
  5286. ast_set_write_format(iaxs[fr.callno]->owner, iaxs[fr.callno]->owner->writeformat);
  5287. if (iaxs[fr.callno]->owner->readformat)
  5288. ast_set_read_format(iaxs[fr.callno]->owner, iaxs[fr.callno]->owner->readformat);
  5289. ast_mutex_unlock(&iaxs[fr.callno]->owner->lock);
  5290. }
  5291. }
  5292. }
  5293. ast_mutex_lock(&dpcache_lock);
  5294. dp = iaxs[fr.callno]->dpentries;
  5295. while(dp) {
  5296. if (!(dp->flags & CACHE_FLAG_TRANSMITTED)) {
  5297. iax2_dprequest(dp, fr.callno);
  5298. }
  5299. dp = dp->peer;
  5300. }
  5301. ast_mutex_unlock(&dpcache_lock);
  5302. break;
  5303. case IAX_COMMAND_POKE:
  5304. /* Send back a pong packet with the original timestamp */
  5305. send_command_final(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr.ts, NULL, 0, -1);
  5306. break;
  5307. case IAX_COMMAND_PING:
  5308. #ifdef BRIDGE_OPTIMIZATION
  5309. if (iaxs[fr.callno]->bridgecallno) {
  5310. /* If we're in a bridged call, just forward this */
  5311. forward_command(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_PING, fr.ts, NULL, 0, -1);
  5312. } else {
  5313. /* Send back a pong packet with the original timestamp */
  5314. send_command(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr.ts, NULL, 0, -1);
  5315. }
  5316. #else
  5317. /* Send back a pong packet with the original timestamp */
  5318. send_command(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr.ts, NULL, 0, -1);
  5319. #endif
  5320. break;
  5321. case IAX_COMMAND_PONG:
  5322. #ifdef BRIDGE_OPTIMIZATION
  5323. if (iaxs[fr.callno]->bridgecallno) {
  5324. /* Forward to the other side of the bridge */
  5325. forward_command(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr.ts, NULL, 0, -1);
  5326. } else {
  5327. /* Calculate ping time */
  5328. iaxs[fr.callno]->pingtime = calc_timestamp(iaxs[fr.callno], 0, &f) - fr.ts;
  5329. }
  5330. #else
  5331. /* Calculate ping time */
  5332. iaxs[fr.callno]->pingtime = calc_timestamp(iaxs[fr.callno], 0, &f) - fr.ts;
  5333. #endif
  5334. if (iaxs[fr.callno]->peerpoke) {
  5335. peer = iaxs[fr.callno]->peerpoke;
  5336. if ((peer->lastms < 0) || (peer->lastms > peer->maxms)) {
  5337. if (iaxs[fr.callno]->pingtime <= peer->maxms) {
  5338. ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE!\n", peer->name);
  5339. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer->name,iaxs[fr.callno]->pingtime);
  5340. }
  5341. } else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
  5342. if (iaxs[fr.callno]->pingtime > peer->maxms) {
  5343. ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer->name, iaxs[fr.callno]->pingtime);
  5344. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer->name,iaxs[fr.callno]->pingtime);
  5345. }
  5346. }
  5347. peer->lastms = iaxs[fr.callno]->pingtime;
  5348. if (peer->pokeexpire > -1)
  5349. ast_sched_del(sched, peer->pokeexpire);
  5350. send_command_immediate(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.iseqno);
  5351. iax2_destroy_nolock(fr.callno);
  5352. peer->callno = 0;
  5353. /* Try again eventually */
  5354. if ((peer->lastms < 0) || (peer->lastms > peer->maxms))
  5355. peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, iax2_poke_peer_s, peer);
  5356. else
  5357. peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, iax2_poke_peer_s, peer);
  5358. }
  5359. break;
  5360. case IAX_COMMAND_LAGRQ:
  5361. case IAX_COMMAND_LAGRP:
  5362. #ifdef BRIDGE_OPTIMIZATION
  5363. if (iaxs[fr.callno]->bridgecallno) {
  5364. forward_command(iaxs[fr.callno], AST_FRAME_IAX, f.subclass, fr.ts, NULL, 0, -1);
  5365. } else {
  5366. #endif
  5367. f.src = "LAGRQ";
  5368. f.mallocd = 0;
  5369. f.offset = 0;
  5370. f.samples = 0;
  5371. iax_frame_wrap(&fr, &f);
  5372. if(f.subclass == IAX_COMMAND_LAGRQ) {
  5373. /* Received a LAGRQ - echo back a LAGRP */
  5374. fr.af.subclass = IAX_COMMAND_LAGRP;
  5375. iax2_send(iaxs[fr.callno], &fr.af, fr.ts, -1, 0, 0, 0);
  5376. } else {
  5377. /* Received LAGRP in response to our LAGRQ */
  5378. unsigned int ts;
  5379. /* This is a reply we've been given, actually measure the difference */
  5380. ts = calc_timestamp(iaxs[fr.callno], 0, &fr.af);
  5381. iaxs[fr.callno]->lag = ts - fr.ts;
  5382. if (option_debug)
  5383. ast_log(LOG_DEBUG, "Peer %s lag measured as %dms\n",
  5384. ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[fr.callno]->addr.sin_addr), iaxs[fr.callno]->lag);
  5385. }
  5386. #ifdef BRIDGE_OPTIMIZATION
  5387. }
  5388. #endif
  5389. break;
  5390. case IAX_COMMAND_AUTHREQ:
  5391. if (iaxs[fr.callno]->state & (IAX_STATE_STARTED | IAX_STATE_TBD)) {
  5392. ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr.callno]->owner ? iaxs[fr.callno]->owner->name : "<Unknown>");
  5393. break;
  5394. }
  5395. if (authenticate_reply(iaxs[fr.callno], &iaxs[fr.callno]->addr, &ies, iaxs[fr.callno]->secret, iaxs[fr.callno]->outkey)) {
  5396. ast_log(LOG_WARNING,
  5397. "I don't know how to authenticate %s to %s\n",
  5398. ies.username ? ies.username : "<unknown>", ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[fr.callno]->addr.sin_addr));
  5399. }
  5400. break;
  5401. case IAX_COMMAND_AUTHREP:
  5402. /* For security, always ack immediately */
  5403. if (delayreject)
  5404. send_command_immediate(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.iseqno);
  5405. /* Ignore once we've started */
  5406. if (iaxs[fr.callno]->state & (IAX_STATE_STARTED | IAX_STATE_TBD)) {
  5407. ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr.callno]->owner ? iaxs[fr.callno]->owner->name : "<Unknown>");
  5408. break;
  5409. }
  5410. if (authenticate_verify(iaxs[fr.callno], &ies)) {
  5411. if (authdebug)
  5412. ast_log(LOG_NOTICE, "Host %s failed to authenticate as %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[fr.callno]->addr.sin_addr), iaxs[fr.callno]->username);
  5413. memset(&ied0, 0, sizeof(ied0));
  5414. auth_fail(fr.callno, IAX_COMMAND_REJECT);
  5415. break;
  5416. }
  5417. if (strcasecmp(iaxs[fr.callno]->exten, "TBD")) {
  5418. /* This might re-enter the IAX code and need the lock */
  5419. exists = ast_exists_extension(NULL, iaxs[fr.callno]->context, iaxs[fr.callno]->exten, 1, iaxs[fr.callno]->callerid);
  5420. } else
  5421. exists = 0;
  5422. if (strcmp(iaxs[fr.callno]->exten, "TBD") && !exists) {
  5423. if (authdebug)
  5424. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), iaxs[fr.callno]->exten, iaxs[fr.callno]->context);
  5425. memset(&ied0, 0, sizeof(ied0));
  5426. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
  5427. send_command_final(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  5428. } else {
  5429. /* Select an appropriate format */
  5430. format = iaxs[fr.callno]->peerformat & iaxs[fr.callno]->capability;
  5431. if (!format) {
  5432. ast_log(LOG_DEBUG, "We don't do requested format %s, falling back to peer capability %d\n", ast_getformatname(iaxs[fr.callno]->peerformat), iaxs[fr.callno]->peercapability);
  5433. format = iaxs[fr.callno]->peercapability & iaxs[fr.callno]->capability;
  5434. if (!format) {
  5435. if (authdebug)
  5436. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), iaxs[fr.callno]->peerformat, iaxs[fr.callno]->peercapability, iaxs[fr.callno]->capability);
  5437. memset(&ied0, 0, sizeof(ied0));
  5438. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
  5439. send_command_final(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  5440. } else {
  5441. /* Pick one... */
  5442. format = ast_best_codec(iaxs[fr.callno]->peercapability & iaxs[fr.callno]->capability);
  5443. if (!format) {
  5444. ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr.callno]->peercapability & iaxs[fr.callno]->capability);
  5445. if (authdebug)
  5446. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), iaxs[fr.callno]->peerformat, iaxs[fr.callno]->peercapability, iaxs[fr.callno]->capability);
  5447. memset(&ied0, 0, sizeof(ied0));
  5448. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
  5449. send_command_final(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  5450. }
  5451. }
  5452. }
  5453. if (format) {
  5454. /* Authentication received */
  5455. memset(&ied1, 0, sizeof(ied1));
  5456. iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
  5457. send_command(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
  5458. if (strcmp(iaxs[fr.callno]->exten, "TBD")) {
  5459. iaxs[fr.callno]->state |= IAX_STATE_STARTED;
  5460. if (option_verbose > 2)
  5461. ast_verbose(VERBOSE_PREFIX_3 "Accepting AUTHENTICATED call from %s, requested format = %d, actual format = %d\n",
  5462. ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), iaxs[fr.callno]->peerformat,format);
  5463. iaxs[fr.callno]->state |= IAX_STATE_STARTED;
  5464. if(!(c = ast_iax2_new(fr.callno, AST_STATE_RING, format)))
  5465. iax2_destroy_nolock(fr.callno);
  5466. } else {
  5467. iaxs[fr.callno]->state |= IAX_STATE_TBD;
  5468. /* If this is a TBD call, we're ready but now what... */
  5469. if (option_verbose > 2)
  5470. ast_verbose(VERBOSE_PREFIX_3 "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr));
  5471. }
  5472. }
  5473. }
  5474. break;
  5475. case IAX_COMMAND_DIAL:
  5476. if (iaxs[fr.callno]->state & IAX_STATE_TBD) {
  5477. iaxs[fr.callno]->state &= ~IAX_STATE_TBD;
  5478. strncpy(iaxs[fr.callno]->exten, ies.called_number ? ies.called_number : "s", sizeof(iaxs[fr.callno]->exten)-1);
  5479. if (!ast_exists_extension(NULL, iaxs[fr.callno]->context, iaxs[fr.callno]->exten, 1, iaxs[fr.callno]->callerid)) {
  5480. if (authdebug)
  5481. ast_log(LOG_NOTICE, "Rejected dial attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), iaxs[fr.callno]->exten, iaxs[fr.callno]->context);
  5482. memset(&ied0, 0, sizeof(ied0));
  5483. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
  5484. send_command_final(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  5485. } else {
  5486. iaxs[fr.callno]->state |= IAX_STATE_STARTED;
  5487. if (option_verbose > 2)
  5488. ast_verbose(VERBOSE_PREFIX_3 "Accepting DIAL from %s, formats = 0x%x\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), iaxs[fr.callno]->peerformat);
  5489. iaxs[fr.callno]->state |= IAX_STATE_STARTED;
  5490. send_command(iaxs[fr.callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
  5491. if(!(c = ast_iax2_new(fr.callno, AST_STATE_RING, iaxs[fr.callno]->peerformat)))
  5492. iax2_destroy_nolock(fr.callno);
  5493. }
  5494. }
  5495. break;
  5496. case IAX_COMMAND_INVAL:
  5497. iaxs[fr.callno]->error = ENOTCONN;
  5498. ast_log(LOG_DEBUG, "Immediately destroying %d, having received INVAL\n", fr.callno);
  5499. iax2_destroy_nolock(fr.callno);
  5500. if (option_debug)
  5501. ast_log(LOG_DEBUG, "Destroying call %d\n", fr.callno);
  5502. break;
  5503. case IAX_COMMAND_VNAK:
  5504. ast_log(LOG_DEBUG, "Sending VNAK\n");
  5505. /* Force retransmission */
  5506. vnak_retransmit(fr.callno, fr.iseqno);
  5507. break;
  5508. case IAX_COMMAND_REGREQ:
  5509. case IAX_COMMAND_REGREL:
  5510. /* For security, always ack immediately */
  5511. if (delayreject)
  5512. send_command_immediate(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.iseqno);
  5513. if (register_verify(fr.callno, &sin, &ies)) {
  5514. /* Send delayed failure */
  5515. auth_fail(fr.callno, IAX_COMMAND_REGREJ);
  5516. break;
  5517. }
  5518. if ((ast_strlen_zero(iaxs[fr.callno]->secret) && ast_strlen_zero(iaxs[fr.callno]->inkeys)) || (iaxs[fr.callno]->state & IAX_STATE_AUTHENTICATED)) {
  5519. if (f.subclass == IAX_COMMAND_REGREL)
  5520. memset(&sin, 0, sizeof(sin));
  5521. if (update_registry(iaxs[fr.callno]->peer, &sin, fr.callno, ies.devicetype))
  5522. ast_log(LOG_WARNING, "Registry error\n");
  5523. if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr)
  5524. check_provisioning(&sin, ies.serviceident, ies.provver);
  5525. break;
  5526. }
  5527. registry_authrequest(iaxs[fr.callno]->peer, fr.callno);
  5528. break;
  5529. case IAX_COMMAND_REGACK:
  5530. if (iax2_ack_registry(&ies, &sin, fr.callno))
  5531. ast_log(LOG_WARNING, "Registration failure\n");
  5532. /* Send ack immediately, before we destroy */
  5533. send_command_immediate(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.iseqno);
  5534. iax2_destroy_nolock(fr.callno);
  5535. break;
  5536. case IAX_COMMAND_REGREJ:
  5537. if (iaxs[fr.callno]->reg) {
  5538. if (authdebug) {
  5539. ast_log(LOG_NOTICE, "Registration of '%s' rejected: %s\n", iaxs[fr.callno]->reg->username, ies.cause ? ies.cause : "<unknown>");
  5540. manager_event(EVENT_FLAG_SYSTEM, "Registry", "Channel: IAX2\r\nUsername: %s\r\nStatus: Rejected\r\nCause: %s\r\n", iaxs[fr.callno]->reg->username, ies.cause ? ies.cause : "<unknown>");
  5541. }
  5542. iaxs[fr.callno]->reg->regstate = REG_STATE_REJECTED;
  5543. }
  5544. /* Send ack immediately, before we destroy */
  5545. send_command_immediate(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.iseqno);
  5546. iax2_destroy_nolock(fr.callno);
  5547. break;
  5548. case IAX_COMMAND_REGAUTH:
  5549. /* Authentication request */
  5550. if (registry_rerequest(&ies, fr.callno, &sin)) {
  5551. memset(&ied0, 0, sizeof(ied0));
  5552. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
  5553. send_command_final(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  5554. }
  5555. break;
  5556. case IAX_COMMAND_TXREJ:
  5557. iaxs[fr.callno]->transferring = 0;
  5558. if (option_verbose > 2)
  5559. ast_verbose(VERBOSE_PREFIX_3 "Channel '%s' unable to transfer\n", iaxs[fr.callno]->owner ? iaxs[fr.callno]->owner->name : "<Unknown>");
  5560. memset(&iaxs[fr.callno]->transfer, 0, sizeof(iaxs[fr.callno]->transfer));
  5561. if (iaxs[fr.callno]->bridgecallno) {
  5562. if (iaxs[iaxs[fr.callno]->bridgecallno]->transferring) {
  5563. iaxs[iaxs[fr.callno]->bridgecallno]->transferring = 0;
  5564. send_command(iaxs[iaxs[fr.callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
  5565. }
  5566. }
  5567. break;
  5568. case IAX_COMMAND_TXREADY:
  5569. if (iaxs[fr.callno]->transferring == TRANSFER_BEGIN) {
  5570. iaxs[fr.callno]->transferring = TRANSFER_READY;
  5571. if (option_verbose > 2)
  5572. ast_verbose(VERBOSE_PREFIX_3 "Channel '%s' ready to transfer\n", iaxs[fr.callno]->owner ? iaxs[fr.callno]->owner->name : "<Unknown>");
  5573. if (iaxs[fr.callno]->bridgecallno) {
  5574. if (iaxs[iaxs[fr.callno]->bridgecallno]->transferring == TRANSFER_READY) {
  5575. if (option_verbose > 2)
  5576. ast_verbose(VERBOSE_PREFIX_3 "Releasing %s and %s\n", iaxs[fr.callno]->owner ? iaxs[fr.callno]->owner->name : "<Unknown>",
  5577. iaxs[iaxs[fr.callno]->bridgecallno]->owner ? iaxs[iaxs[fr.callno]->bridgecallno]->owner->name : "<Unknown>");
  5578. /* They're both ready, now release them. */
  5579. iaxs[iaxs[fr.callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
  5580. iaxs[fr.callno]->transferring = TRANSFER_RELEASED;
  5581. iaxs[iaxs[fr.callno]->bridgecallno]->alreadygone = 1;
  5582. iaxs[fr.callno]->alreadygone = 1;
  5583. /* Stop doing lag & ping requests */
  5584. stop_stuff(fr.callno);
  5585. stop_stuff(iaxs[fr.callno]->bridgecallno);
  5586. memset(&ied0, 0, sizeof(ied0));
  5587. memset(&ied1, 0, sizeof(ied1));
  5588. iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr.callno]->bridgecallno]->peercallno);
  5589. iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr.callno]->peercallno);
  5590. send_command(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
  5591. send_command(iaxs[iaxs[fr.callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
  5592. }
  5593. }
  5594. }
  5595. break;
  5596. case IAX_COMMAND_TXREQ:
  5597. try_transfer(iaxs[fr.callno], &ies);
  5598. break;
  5599. case IAX_COMMAND_TXCNT:
  5600. if (iaxs[fr.callno]->transferring)
  5601. send_command_transfer(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, NULL, 0);
  5602. break;
  5603. case IAX_COMMAND_TXREL:
  5604. /* Send ack immediately, rather than waiting until we've changed addresses */
  5605. send_command_immediate(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.iseqno);
  5606. complete_transfer(fr.callno, &ies);
  5607. stop_stuff(fr.callno); /* for attended transfer to work with libiax */
  5608. break;
  5609. case IAX_COMMAND_DPREP:
  5610. complete_dpreply(iaxs[fr.callno], &ies);
  5611. break;
  5612. case IAX_COMMAND_UNSUPPORT:
  5613. ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
  5614. break;
  5615. case IAX_COMMAND_FWDOWNL:
  5616. /* Firmware download */
  5617. memset(&ied0, 0, sizeof(ied0));
  5618. res = iax_firmware_append(&ied0, ies.devicetype, ies.fwdesc);
  5619. if (res < 0)
  5620. send_command_final(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  5621. else if (res > 0)
  5622. send_command_final(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
  5623. else
  5624. send_command(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
  5625. break;
  5626. default:
  5627. ast_log(LOG_DEBUG, "Unknown IAX command %d on %d/%d\n", f.subclass, fr.callno, iaxs[fr.callno]->peercallno);
  5628. memset(&ied0, 0, sizeof(ied0));
  5629. iax_ie_append_byte(&ied0, IAX_IE_IAX_UNKNOWN, f.subclass);
  5630. send_command(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
  5631. }
  5632. /* Don't actually pass these frames along */
  5633. if ((f.subclass != IAX_COMMAND_ACK) &&
  5634. (f.subclass != IAX_COMMAND_TXCNT) &&
  5635. (f.subclass != IAX_COMMAND_TXACC) &&
  5636. (f.subclass != IAX_COMMAND_INVAL) &&
  5637. (f.subclass != IAX_COMMAND_VNAK)) {
  5638. if (iaxs[fr.callno] && iaxs[fr.callno]->aseqno != iaxs[fr.callno]->iseqno)
  5639. send_command_immediate(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.iseqno);
  5640. }
  5641. ast_mutex_unlock(&iaxsl[fr.callno]);
  5642. return 1;
  5643. }
  5644. /* Unless this is an ACK or INVAL frame, ack it */
  5645. if (iaxs[fr.callno]->aseqno != iaxs[fr.callno]->iseqno)
  5646. send_command_immediate(iaxs[fr.callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.iseqno);
  5647. } else if (minivid) {
  5648. f.frametype = AST_FRAME_VIDEO;
  5649. if (iaxs[fr.callno]->videoformat > 0)
  5650. f.subclass = iaxs[fr.callno]->videoformat | (ntohs(vh->ts) & 0x8000 ? 1 : 0);
  5651. else {
  5652. ast_log(LOG_WARNING, "Received mini frame before first full video frame\n ");
  5653. iax2_vnak(fr.callno);
  5654. ast_mutex_unlock(&iaxsl[fr.callno]);
  5655. return 1;
  5656. }
  5657. f.datalen = res - sizeof(struct ast_iax2_video_hdr);
  5658. if (f.datalen)
  5659. f.data = buf + sizeof(struct ast_iax2_video_hdr);
  5660. else
  5661. f.data = NULL;
  5662. fr.ts = (iaxs[fr.callno]->last & 0xFFFF8000L) | (ntohs(mh->ts) & 0x7fff);
  5663. } else {
  5664. /* A mini frame */
  5665. f.frametype = AST_FRAME_VOICE;
  5666. if (iaxs[fr.callno]->voiceformat > 0)
  5667. f.subclass = iaxs[fr.callno]->voiceformat;
  5668. else {
  5669. ast_log(LOG_WARNING, "Received mini frame before first full voice frame\n ");
  5670. iax2_vnak(fr.callno);
  5671. ast_mutex_unlock(&iaxsl[fr.callno]);
  5672. return 1;
  5673. }
  5674. f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
  5675. if (f.datalen < 0) {
  5676. ast_log(LOG_WARNING, "Datalen < 0?\n");
  5677. ast_mutex_unlock(&iaxsl[fr.callno]);
  5678. return 1;
  5679. }
  5680. if (f.datalen)
  5681. f.data = buf + sizeof(struct ast_iax2_mini_hdr);
  5682. else
  5683. f.data = NULL;
  5684. fr.ts = (iaxs[fr.callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
  5685. /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
  5686. }
  5687. /* Don't pass any packets until we're started */
  5688. if (!(iaxs[fr.callno]->state & IAX_STATE_STARTED)) {
  5689. ast_mutex_unlock(&iaxsl[fr.callno]);
  5690. return 1;
  5691. }
  5692. /* Common things */
  5693. f.src = "IAX2";
  5694. f.mallocd = 0;
  5695. f.offset = 0;
  5696. if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
  5697. f.samples = get_samples(&f);
  5698. /* We need to byteswap incoming slinear samples from network byte order */
  5699. if (f.subclass == AST_FORMAT_SLINEAR)
  5700. ast_frame_byteswap_be(&f);
  5701. } else
  5702. f.samples = 0;
  5703. iax_frame_wrap(&fr, &f);
  5704. /* If this is our most recent packet, use it as our basis for timestamping */
  5705. if (iaxs[fr.callno]->last < fr.ts) {
  5706. /*iaxs[fr.callno]->last = fr.ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
  5707. fr.outoforder = 0;
  5708. } else {
  5709. if (option_debug)
  5710. ast_log(LOG_DEBUG, "Received out of order packet... (type=%d, subclass %d, ts = %d, last = %d)\n", f.frametype, f.subclass, fr.ts, iaxs[fr.callno]->last);
  5711. fr.outoforder = -1;
  5712. }
  5713. #ifdef BRIDGE_OPTIMIZATION
  5714. if (iaxs[fr.callno]->bridgecallno) {
  5715. forward_delivery(&fr);
  5716. } else {
  5717. duped_fr = iaxfrdup2(&fr);
  5718. schedule_delivery(duped_fr, 1, updatehistory, 0);
  5719. fr.ts = duped_fr->ts;
  5720. }
  5721. #else
  5722. duped_fr = iaxfrdup2(&fr);
  5723. schedule_delivery(duped_fr, 1, updatehistory, 0);
  5724. fr.ts = duped_fr->ts;
  5725. #endif
  5726. if (iaxs[fr.callno]->last < fr.ts) {
  5727. iaxs[fr.callno]->last = fr.ts;
  5728. #if 1
  5729. if (option_debug)
  5730. ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr.callno, fr.ts);
  5731. #endif
  5732. }
  5733. /* Always run again */
  5734. ast_mutex_unlock(&iaxsl[fr.callno]);
  5735. return 1;
  5736. }
  5737. static int iax2_do_register(struct iax2_registry *reg)
  5738. {
  5739. struct iax_ie_data ied;
  5740. if (option_debug)
  5741. ast_log(LOG_DEBUG, "Sending registration request for '%s'\n", reg->username);
  5742. if (!reg->callno) {
  5743. if (option_debug)
  5744. ast_log(LOG_DEBUG, "Allocate call number\n");
  5745. reg->callno = find_callno(0, 0, &reg->addr, NEW_FORCE, 1);
  5746. if (reg->callno < 1) {
  5747. ast_log(LOG_WARNING, "Unable to create call for registration\n");
  5748. return -1;
  5749. } else if (option_debug)
  5750. ast_log(LOG_DEBUG, "Registration created on call %d\n", reg->callno);
  5751. iaxs[reg->callno]->reg = reg;
  5752. }
  5753. /* Schedule the next registration attempt */
  5754. if (reg->expire > -1)
  5755. ast_sched_del(sched, reg->expire);
  5756. /* Setup the registration a little early */
  5757. reg->expire = ast_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
  5758. /* Send the request */
  5759. memset(&ied, 0, sizeof(ied));
  5760. iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
  5761. iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
  5762. send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
  5763. reg->regstate = REG_STATE_REGSENT;
  5764. return 0;
  5765. }
  5766. static char *iax2_prov_complete_template_3rd(char *line, char *word, int pos, int state)
  5767. {
  5768. if (pos != 3)
  5769. return NULL;
  5770. return iax_prov_complete_template(line, word, pos, state);
  5771. }
  5772. static int iax2_provision(struct sockaddr_in *end, char *dest, const char *template, int force)
  5773. {
  5774. /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
  5775. is found for template */
  5776. struct iax_ie_data provdata;
  5777. struct iax_ie_data ied;
  5778. unsigned int sig;
  5779. struct sockaddr_in sin;
  5780. int callno;
  5781. if (option_debug)
  5782. ast_log(LOG_DEBUG, "Provisioning '%s' from template '%s'\n", dest, template);
  5783. if (iax_provision_build(&provdata, &sig, template, force)) {
  5784. ast_log(LOG_DEBUG, "No provisioning found for template '%s'\n", template);
  5785. return 0;
  5786. }
  5787. if (end)
  5788. memcpy(&sin, end, sizeof(sin));
  5789. else {
  5790. if (create_addr(&sin, NULL, NULL, NULL, dest, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, NULL, NULL))
  5791. return -1;
  5792. }
  5793. /* Build the rest of the message */
  5794. memset(&ied, 0, sizeof(ied));
  5795. iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
  5796. callno = find_callno(0, 0, &sin, NEW_FORCE, 1);
  5797. if (!callno)
  5798. return -1;
  5799. ast_mutex_lock(&iaxsl[callno]);
  5800. if (iaxs[callno]) {
  5801. /* Schedule autodestruct in case they don't ever give us anything back */
  5802. if (iaxs[callno]->autoid > -1)
  5803. ast_sched_del(sched, iaxs[callno]->autoid);
  5804. iaxs[callno]->autoid = ast_sched_add(sched, 15000, auto_hangup, (void *)(long)callno);
  5805. iaxs[callno]->provision = 1;
  5806. /* Got a call number now, so go ahead and send the provisioning information */
  5807. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
  5808. }
  5809. ast_mutex_unlock(&iaxsl[callno]);
  5810. return 1;
  5811. }
  5812. static int iax2_prov_cmd(int fd, int argc, char *argv[])
  5813. {
  5814. int force = 0;
  5815. int res;
  5816. if (argc < 4)
  5817. return RESULT_SHOWUSAGE;
  5818. if ((argc > 4)) {
  5819. if (!strcasecmp(argv[4], "forced"))
  5820. force = 1;
  5821. else
  5822. return RESULT_SHOWUSAGE;
  5823. }
  5824. res = iax2_provision(NULL, argv[2], argv[3], force);
  5825. if (res < 0)
  5826. ast_cli(fd, "Unable to find peer/address '%s'\n", argv[2]);
  5827. else if (res < 1)
  5828. ast_cli(fd, "No template (including wildcard) matching '%s'\n", argv[3]);
  5829. else
  5830. ast_cli(fd, "Provisioning '%s' with template '%s'%s\n", argv[2], argv[3], force ? ", forced" : "");
  5831. return RESULT_SUCCESS;
  5832. }
  5833. static char show_prov_usage[] =
  5834. "Usage: iax2 provision <host> <template> [forced]\n"
  5835. " Provisions the given peer or IP address using a template\n"
  5836. " matching either 'template' or '*' if the template is not\n"
  5837. " found. If 'forced' is specified, even empty provisioning\n"
  5838. " fields will be provisioned as empty fields.\n";
  5839. static struct ast_cli_entry cli_provision =
  5840. { { "iax2", "provision", NULL }, iax2_prov_cmd, "Provision an IAX device", show_prov_usage, iax2_prov_complete_template_3rd };
  5841. static int iax2_poke_noanswer(void *data)
  5842. {
  5843. struct iax2_peer *peer = data;
  5844. peer->pokeexpire = -1;
  5845. if (peer->lastms > -1) {
  5846. ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!\n", peer->name);
  5847. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name,peer->lastms);
  5848. }
  5849. if (peer->callno > 0)
  5850. iax2_destroy(peer->callno);
  5851. peer->callno = 0;
  5852. peer->lastms = -1;
  5853. /* Try again quickly */
  5854. peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, iax2_poke_peer_s, peer);
  5855. return 0;
  5856. }
  5857. static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
  5858. {
  5859. if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
  5860. /* IF we have no IP, or this isn't to be monitored, return
  5861. imeediately after clearing things out */
  5862. peer->lastms = 0;
  5863. peer->pokeexpire = -1;
  5864. peer->callno = 0;
  5865. return 0;
  5866. }
  5867. if (peer->callno > 0) {
  5868. ast_log(LOG_NOTICE, "Still have a callno...\n");
  5869. iax2_destroy(peer->callno);
  5870. }
  5871. if (heldcall)
  5872. ast_mutex_unlock(&iaxsl[heldcall]);
  5873. peer->callno = find_callno(0, 0, &peer->addr, NEW_FORCE, 0);
  5874. if (heldcall)
  5875. ast_mutex_lock(&iaxsl[heldcall]);
  5876. if (peer->callno < 1) {
  5877. ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
  5878. return -1;
  5879. }
  5880. if (peer->pokeexpire > -1)
  5881. ast_sched_del(sched, peer->pokeexpire);
  5882. /* Speed up retransmission times */
  5883. iaxs[peer->callno]->pingtime = peer->maxms / 4 + 1;
  5884. iaxs[peer->callno]->peerpoke = peer;
  5885. send_command(iaxs[peer->callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, NULL, 0, -1);
  5886. peer->pokeexpire = ast_sched_add(sched, DEFAULT_MAXMS * 2, iax2_poke_noanswer, peer);
  5887. return 0;
  5888. }
  5889. static void free_context(struct iax2_context *con)
  5890. {
  5891. struct iax2_context *conl;
  5892. while(con) {
  5893. conl = con;
  5894. con = con->next;
  5895. free(conl);
  5896. }
  5897. }
  5898. static struct ast_channel *iax2_request(char *type, int format, void *data)
  5899. {
  5900. int callno;
  5901. int res;
  5902. int sendani;
  5903. int maxtime;
  5904. int found = 0;
  5905. int fmt, native;
  5906. struct sockaddr_in sin;
  5907. char s[256];
  5908. char *st, *hostname;
  5909. struct ast_channel *c;
  5910. char *stringp=NULL;
  5911. char *portno=NULL;
  5912. int capability = iax2_capability;
  5913. int trunk;
  5914. int notransfer = globalnotransfer;
  5915. int usejitterbuf = globalusejitterbuf;
  5916. strncpy(s, (char *)data, sizeof(s)-1);
  5917. /* FIXME The next two lines seem useless */
  5918. stringp=s;
  5919. strsep(&stringp, "/");
  5920. stringp=s;
  5921. strsep(&stringp, "@");
  5922. st = strsep(&stringp, "@");
  5923. if (!st)
  5924. {
  5925. st = s;
  5926. }
  5927. hostname = strsep(&st, ":");
  5928. if (st) {
  5929. portno = strsep(&st, ":");
  5930. }
  5931. /* Populate our address from the given */
  5932. if (create_addr(&sin, &capability, &sendani, &maxtime, hostname, NULL, &trunk, &notransfer, &usejitterbuf, NULL, 0, NULL, 0, &found, NULL)) {
  5933. return NULL;
  5934. }
  5935. if (portno) {
  5936. sin.sin_port = htons(atoi(portno));
  5937. }
  5938. callno = find_callno(0, 0, &sin, NEW_FORCE, 1);
  5939. if (callno < 1) {
  5940. ast_log(LOG_WARNING, "Unable to create call\n");
  5941. return NULL;
  5942. }
  5943. ast_mutex_lock(&iaxsl[callno]);
  5944. /* If this is a trunk, update it now */
  5945. iaxs[callno]->trunk = trunk;
  5946. if (trunk)
  5947. callno = make_trunk(callno, 1);
  5948. /* Keep track of sendani flag */
  5949. iaxs[callno]->sendani = sendani;
  5950. iaxs[callno]->maxtime = maxtime;
  5951. iaxs[callno]->notransfer = notransfer;
  5952. iaxs[callno]->usejitterbuf = usejitterbuf;
  5953. if (found)
  5954. strncpy(iaxs[callno]->host, hostname, sizeof(iaxs[callno]->host) - 1);
  5955. c = ast_iax2_new(callno, AST_STATE_DOWN, capability);
  5956. ast_mutex_unlock(&iaxsl[callno]);
  5957. if (c) {
  5958. /* Choose a format we can live with */
  5959. if (c->nativeformats & format)
  5960. c->nativeformats &= format;
  5961. else {
  5962. native = c->nativeformats;
  5963. fmt = format;
  5964. res = ast_translator_best_choice(&fmt, &native);
  5965. if (res < 0) {
  5966. ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n", ast_getformatname(c->nativeformats), ast_getformatname(fmt), c->name);
  5967. ast_hangup(c);
  5968. return NULL;
  5969. }
  5970. c->nativeformats = native;
  5971. }
  5972. c->readformat = ast_best_codec(c->nativeformats);
  5973. c->writeformat = c->readformat;
  5974. }
  5975. return c;
  5976. }
  5977. static void *network_thread(void *ignore)
  5978. {
  5979. /* Our job is simple: Send queued messages, retrying if necessary. Read frames
  5980. from the network, and queue them for delivery to the channels */
  5981. int res;
  5982. struct iax_frame *f, *freeme;
  5983. /* Establish I/O callback for socket read */
  5984. ast_io_add(io, netsocket, socket_read, AST_IO_IN, NULL);
  5985. if (timingfd > -1)
  5986. ast_io_add(io, timingfd, timing_read, AST_IO_IN | AST_IO_PRI, NULL);
  5987. for(;;) {
  5988. /* Go through the queue, sending messages which have not yet been
  5989. sent, and scheduling retransmissions if appropriate */
  5990. ast_mutex_lock(&iaxq.lock);
  5991. f = iaxq.head;
  5992. while(f) {
  5993. freeme = NULL;
  5994. if (!f->sentyet) {
  5995. f->sentyet++;
  5996. /* Send a copy immediately -- errors here are ok, so don't bother locking */
  5997. if (iaxs[f->callno]) {
  5998. send_packet(f);
  5999. }
  6000. if (f->retries < 0) {
  6001. /* This is not supposed to be retransmitted */
  6002. if (f->prev)
  6003. f->prev->next = f->next;
  6004. else
  6005. iaxq.head = f->next;
  6006. if (f->next)
  6007. f->next->prev = f->prev;
  6008. else
  6009. iaxq.tail = f->prev;
  6010. iaxq.count--;
  6011. /* Free the iax frame */
  6012. freeme = f;
  6013. } else {
  6014. /* We need reliable delivery. Schedule a retransmission */
  6015. f->retries++;
  6016. f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
  6017. }
  6018. }
  6019. f = f->next;
  6020. if (freeme)
  6021. iax_frame_free(freeme);
  6022. }
  6023. ast_mutex_unlock(&iaxq.lock);
  6024. res = ast_sched_wait(sched);
  6025. if ((res > 1000) || (res < 0))
  6026. res = 1000;
  6027. res = ast_io_wait(io, res);
  6028. if (res >= 0) {
  6029. ast_sched_runq(sched);
  6030. }
  6031. }
  6032. return NULL;
  6033. }
  6034. static int start_network_thread(void)
  6035. {
  6036. return ast_pthread_create(&netthreadid, NULL, network_thread, NULL);
  6037. }
  6038. static struct iax2_context *build_context(char *context)
  6039. {
  6040. struct iax2_context *con = malloc(sizeof(struct iax2_context));
  6041. if (con) {
  6042. strncpy(con->context, context, sizeof(con->context)-1);
  6043. con->next = NULL;
  6044. }
  6045. return con;
  6046. }
  6047. static int get_auth_methods(char *value)
  6048. {
  6049. int methods = 0;
  6050. if (strstr(value, "rsa"))
  6051. methods |= IAX_AUTH_RSA;
  6052. if (strstr(value, "md5"))
  6053. methods |= IAX_AUTH_MD5;
  6054. if (strstr(value, "plaintext"))
  6055. methods |= IAX_AUTH_PLAINTEXT;
  6056. return methods;
  6057. }
  6058. static struct iax2_peer *build_peer(char *name, struct ast_variable *v)
  6059. {
  6060. struct iax2_peer *peer;
  6061. struct iax2_peer *prev;
  6062. struct ast_ha *oldha = NULL;
  6063. int maskfound=0;
  6064. int format;
  6065. int found=0;
  6066. prev = NULL;
  6067. ast_mutex_lock(&peerl.lock);
  6068. peer = peerl.peers;
  6069. while(peer) {
  6070. if (!strcasecmp(peer->name, name)) {
  6071. break;
  6072. }
  6073. prev = peer;
  6074. peer = peer->next;
  6075. }
  6076. if (peer) {
  6077. found++;
  6078. oldha = peer->ha;
  6079. peer->ha = NULL;
  6080. /* Already in the list, remove it and it will be added back (or FREE'd) */
  6081. if (prev) {
  6082. prev->next = peer->next;
  6083. } else {
  6084. peerl.peers = peer->next;
  6085. }
  6086. ast_mutex_unlock(&peerl.lock);
  6087. } else {
  6088. ast_mutex_unlock(&peerl.lock);
  6089. peer = malloc(sizeof(struct iax2_peer));
  6090. if (peer) {
  6091. memset(peer, 0, sizeof(struct iax2_peer));
  6092. peer->expire = -1;
  6093. peer->pokeexpire = -1;
  6094. }
  6095. }
  6096. if (peer) {
  6097. peer->messagedetail = globalmessagedetail;
  6098. peer->usejitterbuf = globalusejitterbuf;
  6099. if (!found) {
  6100. strncpy(peer->name, name, sizeof(peer->name)-1);
  6101. peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
  6102. peer->expirey = expirey;
  6103. }
  6104. peer->capability = iax2_capability;
  6105. while(v) {
  6106. if (!strcasecmp(v->name, "secret"))
  6107. strncpy(peer->secret, v->value, sizeof(peer->secret)-1);
  6108. else if (!strcasecmp(v->name, "mailbox"))
  6109. strncpy(peer->mailbox, v->value, sizeof(peer->mailbox) - 1);
  6110. else if (!strcasecmp(v->name, "mailboxdetail"))
  6111. peer->messagedetail = ast_true(v->value);
  6112. else if (!strcasecmp(v->name, "trunk")) {
  6113. peer->trunk = ast_true(v->value);
  6114. if (peer->trunk && (timingfd < 0)) {
  6115. ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without zaptel timing\n", peer->name);
  6116. peer->trunk = 0;
  6117. }
  6118. } else if (!strcasecmp(v->name, "auth")) {
  6119. peer->authmethods = get_auth_methods(v->value);
  6120. } else if (!strcasecmp(v->name, "notransfer")) {
  6121. peer->notransfer = ast_true(v->value);
  6122. } else if (!strcasecmp(v->name, "jitterbuffer")) {
  6123. peer->usejitterbuf = ast_true(v->value);
  6124. } else if (!strcasecmp(v->name, "host")) {
  6125. if (!strcasecmp(v->value, "dynamic")) {
  6126. /* They'll register with us */
  6127. peer->dynamic = 1;
  6128. if (!found) {
  6129. /* Initialize stuff iff we're not found, otherwise
  6130. we keep going with what we had */
  6131. memset(&peer->addr.sin_addr, 0, 4);
  6132. if (peer->addr.sin_port) {
  6133. /* If we've already got a port, make it the default rather than absolute */
  6134. peer->defaddr.sin_port = peer->addr.sin_port;
  6135. peer->addr.sin_port = 0;
  6136. }
  6137. }
  6138. } else {
  6139. /* Non-dynamic. Make sure we become that way if we're not */
  6140. if (peer->expire > -1)
  6141. ast_sched_del(sched, peer->expire);
  6142. peer->expire = -1;
  6143. peer->dynamic = 0;
  6144. if (ast_get_ip(&peer->addr, v->value)) {
  6145. free(peer);
  6146. return NULL;
  6147. }
  6148. }
  6149. if (!maskfound)
  6150. inet_aton("255.255.255.255", &peer->mask);
  6151. } else if (!strcasecmp(v->name, "defaultip")) {
  6152. if (ast_get_ip(&peer->defaddr, v->value)) {
  6153. free(peer);
  6154. return NULL;
  6155. }
  6156. } else if (!strcasecmp(v->name, "permit") ||
  6157. !strcasecmp(v->name, "deny")) {
  6158. peer->ha = ast_append_ha(v->name, v->value, peer->ha);
  6159. } else if (!strcasecmp(v->name, "mask")) {
  6160. maskfound++;
  6161. inet_aton(v->value, &peer->mask);
  6162. } else if (!strcasecmp(v->name, "context")) {
  6163. if (ast_strlen_zero(peer->context))
  6164. strncpy(peer->context, v->value, sizeof(peer->context) - 1);
  6165. } else if (!strcasecmp(v->name, "regexten")) {
  6166. strncpy(peer->regexten, v->value, sizeof(peer->regexten) - 1);
  6167. } else if (!strcasecmp(v->name, "peercontext")) {
  6168. if (ast_strlen_zero(peer->peercontext))
  6169. strncpy(peer->peercontext, v->value, sizeof(peer->peercontext) - 1);
  6170. } else if (!strcasecmp(v->name, "port")) {
  6171. if (peer->dynamic)
  6172. peer->defaddr.sin_port = htons(atoi(v->value));
  6173. else
  6174. peer->addr.sin_port = htons(atoi(v->value));
  6175. } else if (!strcasecmp(v->name, "username")) {
  6176. strncpy(peer->username, v->value, sizeof(peer->username)-1);
  6177. } else if (!strcasecmp(v->name, "allow")) {
  6178. format = ast_getformatbyname(v->value);
  6179. if (format < 1)
  6180. ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
  6181. else
  6182. peer->capability |= format;
  6183. } else if (!strcasecmp(v->name, "disallow")) {
  6184. format = ast_getformatbyname(v->value);
  6185. if (format < 1)
  6186. ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
  6187. else
  6188. peer->capability &= ~format;
  6189. } else if (!strcasecmp(v->name, "callerid")) {
  6190. strncpy(peer->callerid, v->value, sizeof(peer->callerid)-1);
  6191. peer->hascallerid=1;
  6192. } else if (!strcasecmp(v->name, "sendani")) {
  6193. peer->sendani = ast_true(v->value);
  6194. } else if (!strcasecmp(v->name, "inkeys")) {
  6195. strncpy(peer->inkeys, v->value, sizeof(peer->inkeys) - 1);
  6196. } else if (!strcasecmp(v->name, "outkey")) {
  6197. strncpy(peer->outkey, v->value, sizeof(peer->outkey) - 1);
  6198. } else if (!strcasecmp(v->name, "qualify")) {
  6199. if (!strcasecmp(v->value, "no")) {
  6200. peer->maxms = 0;
  6201. } else if (!strcasecmp(v->value, "yes")) {
  6202. peer->maxms = DEFAULT_MAXMS;
  6203. } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
  6204. ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
  6205. peer->maxms = 0;
  6206. }
  6207. }// else if (strcasecmp(v->name,"type"))
  6208. // ast_log(LOG_WARNING, "Ignoring %s\n", v->name);
  6209. v=v->next;
  6210. }
  6211. if (!peer->authmethods)
  6212. peer->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
  6213. peer->delme = 0;
  6214. /* Make sure these are IPv4 addresses */
  6215. peer->addr.sin_family = AF_INET;
  6216. if (!found && peer->dynamic)
  6217. reg_source_db(peer);
  6218. }
  6219. if (oldha)
  6220. ast_free_ha(oldha);
  6221. return peer;
  6222. }
  6223. static struct iax2_user *build_user(char *name, struct ast_variable *v)
  6224. {
  6225. struct iax2_user *prev, *user;
  6226. struct iax2_context *con, *conl = NULL;
  6227. struct ast_ha *oldha = NULL;
  6228. struct iax2_context *oldcon = NULL;
  6229. int format;
  6230. prev = NULL;
  6231. ast_mutex_lock(&userl.lock);
  6232. user = userl.users;
  6233. while(user) {
  6234. if (!strcasecmp(user->name, name)) {
  6235. break;
  6236. }
  6237. prev = user;
  6238. user = user->next;
  6239. }
  6240. if (user) {
  6241. oldha = user->ha;
  6242. oldcon = user->contexts;
  6243. user->ha = NULL;
  6244. user->contexts = NULL;
  6245. /* Already in the list, remove it and it will be added back (or FREE'd) */
  6246. if (prev) {
  6247. prev->next = user->next;
  6248. } else {
  6249. userl.users = user->next;
  6250. }
  6251. ast_mutex_unlock(&userl.lock);
  6252. } else {
  6253. ast_mutex_unlock(&userl.lock);
  6254. user = malloc(sizeof(struct iax2_user));
  6255. if (user)
  6256. memset(user, 0, sizeof(struct iax2_user));
  6257. }
  6258. if (user) {
  6259. memset(user, 0, sizeof(struct iax2_user));
  6260. user->capability = iax2_capability;
  6261. strncpy(user->name, name, sizeof(user->name)-1);
  6262. strncpy(user->language, language, sizeof(user->language) - 1);
  6263. user->usejitterbuf = globalusejitterbuf;
  6264. while(v) {
  6265. if (!strcasecmp(v->name, "context")) {
  6266. con = build_context(v->value);
  6267. if (con) {
  6268. if (conl)
  6269. conl->next = con;
  6270. else
  6271. user->contexts = con;
  6272. conl = con;
  6273. }
  6274. } else if (!strcasecmp(v->name, "permit") ||
  6275. !strcasecmp(v->name, "deny")) {
  6276. user->ha = ast_append_ha(v->name, v->value, user->ha);
  6277. } else if (!strcasecmp(v->name, "allow")) {
  6278. format = ast_getformatbyname(v->value);
  6279. if (format < 1)
  6280. ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
  6281. else
  6282. user->capability |= format;
  6283. } else if (!strcasecmp(v->name, "disallow")) {
  6284. format = ast_getformatbyname(v->value);
  6285. if (format < 1)
  6286. ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
  6287. else
  6288. user->capability &= ~format;
  6289. } else if (!strcasecmp(v->name, "trunk")) {
  6290. user->trunk = ast_true(v->value);
  6291. if (user->trunk && (timingfd < 0)) {
  6292. ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without zaptel timing\n", user->name);
  6293. user->trunk = 0;
  6294. }
  6295. } else if (!strcasecmp(v->name, "auth")) {
  6296. user->authmethods = get_auth_methods(v->value);
  6297. } else if (!strcasecmp(v->name, "notransfer")) {
  6298. user->notransfer = ast_true(v->value);
  6299. } else if (!strcasecmp(v->name, "jitterbuffer")) {
  6300. user->usejitterbuf = ast_true(v->value);
  6301. } else if (!strcasecmp(v->name, "secret")) {
  6302. strncpy(user->secret, v->value, sizeof(user->secret)-1);
  6303. } else if (!strcasecmp(v->name, "callerid")) {
  6304. strncpy(user->callerid, v->value, sizeof(user->callerid)-1);
  6305. user->hascallerid=1;
  6306. } else if (!strcasecmp(v->name, "accountcode")) {
  6307. strncpy(user->accountcode, v->value, sizeof(user->accountcode)-1);
  6308. } else if (!strcasecmp(v->name, "language")) {
  6309. strncpy(user->language, v->value, sizeof(user->language)-1);
  6310. } else if (!strcasecmp(v->name, "amaflags")) {
  6311. format = ast_cdr_amaflags2int(v->value);
  6312. if (format < 0) {
  6313. ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
  6314. } else {
  6315. user->amaflags = format;
  6316. }
  6317. } else if (!strcasecmp(v->name, "inkeys")) {
  6318. strncpy(user->inkeys, v->value, sizeof(user->inkeys) - 1);
  6319. }// else if (strcasecmp(v->name,"type"))
  6320. // ast_log(LOG_WARNING, "Ignoring %s\n", v->name);
  6321. v = v->next;
  6322. }
  6323. if (!user->authmethods) {
  6324. if (!ast_strlen_zero(user->secret)) {
  6325. user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
  6326. if (!ast_strlen_zero(user->inkeys))
  6327. user->authmethods |= IAX_AUTH_RSA;
  6328. } else if (!ast_strlen_zero(user->inkeys)) {
  6329. user->authmethods = IAX_AUTH_RSA;
  6330. } else {
  6331. user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
  6332. }
  6333. }
  6334. user->delme = 0;
  6335. }
  6336. if (oldha)
  6337. ast_free_ha(oldha);
  6338. if (oldcon)
  6339. free_context(oldcon);
  6340. return user;
  6341. }
  6342. static void delete_users(void)
  6343. {
  6344. struct iax2_user *user;
  6345. struct iax2_peer *peer;
  6346. struct iax2_registry *reg, *regl;
  6347. ast_mutex_lock(&userl.lock);
  6348. for (user=userl.users;user;) {
  6349. user->delme = 1;
  6350. user = user->next;
  6351. }
  6352. ast_mutex_unlock(&userl.lock);
  6353. for (reg = registrations;reg;) {
  6354. regl = reg;
  6355. reg = reg->next;
  6356. if (regl->expire > -1) {
  6357. ast_sched_del(sched, regl->expire);
  6358. }
  6359. if (regl->callno) {
  6360. /* XXX Is this a potential lock? I don't think so, but you never know */
  6361. ast_mutex_lock(&iaxsl[regl->callno]);
  6362. if (iaxs[regl->callno]) {
  6363. iaxs[regl->callno]->reg = NULL;
  6364. iax2_destroy_nolock(regl->callno);
  6365. }
  6366. ast_mutex_unlock(&iaxsl[regl->callno]);
  6367. }
  6368. free(regl);
  6369. }
  6370. registrations = NULL;
  6371. ast_mutex_lock(&peerl.lock);
  6372. for (peer=peerl.peers;peer;) {
  6373. /* Assume all will be deleted, and we'll find out for sure later */
  6374. peer->delme = 1;
  6375. peer = peer->next;
  6376. }
  6377. ast_mutex_unlock(&peerl.lock);
  6378. }
  6379. static void prune_users(void)
  6380. {
  6381. struct iax2_user *user, *usernext, *userlast = NULL;
  6382. ast_mutex_lock(&userl.lock);
  6383. for (user=userl.users;user;) {
  6384. usernext = user->next;
  6385. if (user->delme) {
  6386. ast_free_ha(user->ha);
  6387. free_context(user->contexts);
  6388. free(user);
  6389. if (userlast)
  6390. userlast->next = usernext;
  6391. else
  6392. userl.users = usernext;
  6393. } else
  6394. userlast = user;
  6395. user = usernext;
  6396. }
  6397. ast_mutex_unlock(&userl.lock);
  6398. }
  6399. static void prune_peers(void){
  6400. /* Prune peers who still are supposed to be deleted */
  6401. struct iax2_peer *peer, *peerlast, *peernext;
  6402. int x;
  6403. ast_mutex_lock(&peerl.lock);
  6404. peerlast = NULL;
  6405. for (peer=peerl.peers;peer;) {
  6406. peernext = peer->next;
  6407. if (peer->delme) {
  6408. ast_free_ha(peer->ha);
  6409. for (x=0;x<IAX_MAX_CALLS;x++) {
  6410. ast_mutex_lock(&iaxsl[x]);
  6411. if (iaxs[x] && (iaxs[x]->peerpoke == peer)) {
  6412. iax2_destroy(x);
  6413. }
  6414. ast_mutex_unlock(&iaxsl[x]);
  6415. }
  6416. /* Delete it, it needs to disappear */
  6417. if (peer->expire > -1)
  6418. ast_sched_del(sched, peer->expire);
  6419. if (peer->pokeexpire > -1)
  6420. ast_sched_del(sched, peer->pokeexpire);
  6421. if (peer->callno > 0)
  6422. iax2_destroy(peer->callno);
  6423. register_peer_exten(peer, 0);
  6424. free(peer);
  6425. if (peerlast)
  6426. peerlast->next = peernext;
  6427. else
  6428. peerl.peers = peernext;
  6429. } else
  6430. peerlast = peer;
  6431. peer=peernext;
  6432. }
  6433. ast_mutex_unlock(&peerl.lock);
  6434. }
  6435. static void set_timing(void)
  6436. {
  6437. #ifdef IAX_TRUNKING
  6438. int bs = trunkfreq * 8;
  6439. if (timingfd > -1) {
  6440. if (
  6441. #ifdef ZT_TIMERACK
  6442. ioctl(timingfd, ZT_TIMERCONFIG, &bs) &&
  6443. #endif
  6444. ioctl(timingfd, ZT_SET_BLOCKSIZE, &bs))
  6445. ast_log(LOG_WARNING, "Unable to set blocksize on timing source\n");
  6446. }
  6447. #endif
  6448. }
  6449. static int set_config(char *config_file, struct sockaddr_in* sin){
  6450. struct ast_config *cfg;
  6451. int capability=iax2_capability;
  6452. struct ast_variable *v;
  6453. char *cat;
  6454. char *utype;
  6455. int format;
  6456. struct iax2_user *user;
  6457. struct iax2_peer *peer;
  6458. #if 0
  6459. static unsigned short int last_port=0;
  6460. #endif
  6461. cfg = ast_load(config_file);
  6462. if (!cfg) {
  6463. ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
  6464. return -1;
  6465. }
  6466. v = ast_variable_browse(cfg, "general");
  6467. while(v) {
  6468. if (!strcasecmp(v->name, "bindport")){
  6469. sin->sin_port = ntohs(atoi(v->value));
  6470. #if 0
  6471. if(last_port==0){
  6472. last_port=sin->sin_port;
  6473. #if 0
  6474. ast_verbose("setting last port\n");
  6475. #endif
  6476. }
  6477. else if(sin->sin_port != last_port)
  6478. ast_log(LOG_WARNING, "change to port ignored until next asterisk re-start\n");
  6479. #endif
  6480. }
  6481. else if (!strcasecmp(v->name, "pingtime"))
  6482. ping_time = atoi(v->value);
  6483. else if (!strcasecmp(v->name, "maxjitterbuffer"))
  6484. maxjitterbuffer = atoi(v->value);
  6485. else if (!strcasecmp(v->name, "jittershrinkrate"))
  6486. jittershrinkrate = atoi(v->value);
  6487. else if (!strcasecmp(v->name, "maxexcessbuffer"))
  6488. max_jitter_buffer = atoi(v->value);
  6489. else if (!strcasecmp(v->name, "minexcessbuffer"))
  6490. min_jitter_buffer = atoi(v->value);
  6491. else if (!strcasecmp(v->name, "lagrqtime"))
  6492. lagrq_time = atoi(v->value);
  6493. else if (!strcasecmp(v->name, "dropcount"))
  6494. iax2_dropcount = atoi(v->value);
  6495. else if (!strcasecmp(v->name, "bindaddr"))
  6496. inet_aton(v->value, &sin->sin_addr);
  6497. else if (!strcasecmp(v->name, "authdebug"))
  6498. authdebug = ast_true(v->value);
  6499. else if (!strcasecmp(v->name, "notransfer"))
  6500. globalnotransfer = ast_true(v->value);
  6501. else if (!strcasecmp(v->name, "jitterbuffer"))
  6502. globalusejitterbuf = ast_true(v->value);
  6503. else if (!strcasecmp(v->name, "delayreject"))
  6504. delayreject = ast_true(v->value);
  6505. else if (!strcasecmp(v->name, "mailboxdetail"))
  6506. globalmessagedetail = ast_true(v->value);
  6507. else if (!strcasecmp(v->name, "trunkfreq")) {
  6508. trunkfreq = atoi(v->value);
  6509. if (trunkfreq < 10)
  6510. trunkfreq = 10;
  6511. } else if (!strcasecmp(v->name, "bandwidth")) {
  6512. if (!strcasecmp(v->value, "low")) {
  6513. capability = IAX_CAPABILITY_LOWBANDWIDTH;
  6514. } else if (!strcasecmp(v->value, "medium")) {
  6515. capability = IAX_CAPABILITY_MEDBANDWIDTH;
  6516. } else if (!strcasecmp(v->value, "high")) {
  6517. capability = IAX_CAPABILITY_FULLBANDWIDTH;
  6518. } else
  6519. ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
  6520. } else if (!strcasecmp(v->name, "allow")) {
  6521. format = ast_getformatbyname(v->value);
  6522. if (format < 1)
  6523. ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
  6524. else
  6525. capability |= format;
  6526. } else if (!strcasecmp(v->name, "disallow")) {
  6527. format = ast_getformatbyname(v->value);
  6528. if (format < 1)
  6529. ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
  6530. else
  6531. capability &= ~format;
  6532. } else if (!strcasecmp(v->name, "register")) {
  6533. iax2_register(v->value, v->lineno);
  6534. } else if (!strcasecmp(v->name, "iaxcompat")) {
  6535. iaxcompat = ast_true(v->value);
  6536. } else if (!strcasecmp(v->name, "regcontext")) {
  6537. strncpy(regcontext, v->value, sizeof(regcontext) - 1);
  6538. /* Create context if it doesn't exist already */
  6539. if (!ast_context_find(regcontext))
  6540. ast_context_create(NULL, regcontext, type);
  6541. } else if (!strcasecmp(v->name, "tos")) {
  6542. if (sscanf(v->value, "%i", &format) == 1)
  6543. tos = format & 0xff;
  6544. else if (!strcasecmp(v->value, "lowdelay"))
  6545. tos = IPTOS_LOWDELAY;
  6546. else if (!strcasecmp(v->value, "throughput"))
  6547. tos = IPTOS_THROUGHPUT;
  6548. else if (!strcasecmp(v->value, "reliability"))
  6549. tos = IPTOS_RELIABILITY;
  6550. else if (!strcasecmp(v->value, "mincost"))
  6551. tos = IPTOS_MINCOST;
  6552. else if (!strcasecmp(v->value, "none"))
  6553. tos = 0;
  6554. else
  6555. ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
  6556. } else if (!strcasecmp(v->name, "accountcode")) {
  6557. strncpy(accountcode, v->value, sizeof(accountcode)-1);
  6558. } else if (!strcasecmp(v->name, "amaflags")) {
  6559. format = ast_cdr_amaflags2int(v->value);
  6560. if (format < 0) {
  6561. ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
  6562. } else {
  6563. amaflags = format;
  6564. }
  6565. #ifdef MYSQL_FRIENDS
  6566. } else if (!strcasecmp(v->name, "dbuser")) {
  6567. strncpy(mydbuser, v->value, sizeof(mydbuser) - 1);
  6568. } else if (!strcasecmp(v->name, "dbpass")) {
  6569. strncpy(mydbpass, v->value, sizeof(mydbpass) - 1);
  6570. } else if (!strcasecmp(v->name, "dbhost")) {
  6571. strncpy(mydbhost, v->value, sizeof(mydbhost) - 1);
  6572. } else if (!strcasecmp(v->name, "dbname")) {
  6573. strncpy(mydbname, v->value, sizeof(mydbname) - 1);
  6574. #endif
  6575. } else if (!strcasecmp(v->name, "language")) {
  6576. strncpy(language, v->value, sizeof(language) - 1);
  6577. } //else if (strcasecmp(v->name,"type"))
  6578. // ast_log(LOG_WARNING, "Ignoring %s\n", v->name);
  6579. v = v->next;
  6580. }
  6581. iax2_capability = capability;
  6582. cat = ast_category_browse(cfg, NULL);
  6583. while(cat) {
  6584. if (strcasecmp(cat, "general")) {
  6585. utype = ast_variable_retrieve(cfg, cat, "type");
  6586. if (utype) {
  6587. if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
  6588. user = build_user(cat, ast_variable_browse(cfg, cat));
  6589. if (user) {
  6590. ast_mutex_lock(&userl.lock);
  6591. user->next = userl.users;
  6592. userl.users = user;
  6593. ast_mutex_unlock(&userl.lock);
  6594. }
  6595. }
  6596. if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
  6597. peer = build_peer(cat, ast_variable_browse(cfg, cat));
  6598. if (peer) {
  6599. ast_mutex_lock(&peerl.lock);
  6600. peer->next = peerl.peers;
  6601. peerl.peers = peer;
  6602. ast_mutex_unlock(&peerl.lock);
  6603. }
  6604. } else if (strcasecmp(utype, "user")) {
  6605. ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
  6606. }
  6607. } else
  6608. ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
  6609. }
  6610. cat = ast_category_browse(cfg, cat);
  6611. }
  6612. ast_destroy(cfg);
  6613. set_timing();
  6614. #ifdef MYSQL_FRIENDS
  6615. /* Connect to db if appropriate */
  6616. if (!mysql && !ast_strlen_zero(mydbname)) {
  6617. mysql = mysql_init(NULL);
  6618. if (!mysql_real_connect(mysql, mydbhost[0] ? mydbhost : NULL, mydbuser, mydbpass, mydbname, 0, NULL, 0)) {
  6619. memset(mydbpass, '*', strlen(mydbpass));
  6620. ast_log(LOG_WARNING, "Database connection failed (db=%s, host=%s, user=%s, pass=%s)!\n",
  6621. mydbname, mydbhost, mydbuser, mydbpass);
  6622. free(mysql);
  6623. mysql = NULL;
  6624. } else
  6625. ast_verbose(VERBOSE_PREFIX_1 "Connected to database '%s' on '%s' as '%s'\n",
  6626. mydbname, mydbhost, mydbuser);
  6627. }
  6628. #endif
  6629. return capability;
  6630. }
  6631. static int reload_config(void)
  6632. {
  6633. char *config = "iax.conf";
  6634. struct iax2_registry *reg;
  6635. struct sockaddr_in dead_sin;
  6636. struct iax2_peer *peer;
  6637. strncpy(accountcode, "", sizeof(accountcode)-1);
  6638. strncpy(language, "", sizeof(language)-1);
  6639. amaflags = 0;
  6640. delayreject = 0;
  6641. globalnotransfer = 0;
  6642. globalusejitterbuf = 0;
  6643. delete_users();
  6644. set_config(config,&dead_sin);
  6645. prune_peers();
  6646. prune_users();
  6647. for (reg = registrations; reg; reg = reg->next)
  6648. iax2_do_register(reg);
  6649. /* Qualify hosts, too */
  6650. ast_mutex_lock(&peerl.lock);
  6651. for (peer = peerl.peers; peer; peer = peer->next)
  6652. iax2_poke_peer(peer, 0);
  6653. ast_mutex_unlock(&peerl.lock);
  6654. reload_firmware();
  6655. iax_provision_reload();
  6656. return 0;
  6657. }
  6658. int reload(void)
  6659. {
  6660. return reload_config();
  6661. }
  6662. static int cache_get_callno_locked(char *data)
  6663. {
  6664. struct sockaddr_in sin;
  6665. int x;
  6666. char st[256], *s;
  6667. char *host;
  6668. char *username=NULL;
  6669. char *password=NULL;
  6670. char *context=NULL;
  6671. int callno;
  6672. struct iax_ie_data ied;
  6673. for (x=0;x<IAX_MAX_CALLS; x++) {
  6674. /* Look for an *exact match* call. Once a call is negotiated, it can only
  6675. look up entries for a single context */
  6676. if (!ast_mutex_trylock(&iaxsl[x])) {
  6677. if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot)) {
  6678. return x;
  6679. }
  6680. ast_mutex_unlock(&iaxsl[x]);
  6681. }
  6682. }
  6683. memset(&ied, 0, sizeof(ied));
  6684. /* No match found, we need to create a new one */
  6685. strncpy(st, data, sizeof(st)-1);
  6686. /* Grab the host */
  6687. s = strchr(st, '/');
  6688. if (s) {
  6689. *s = '\0';
  6690. s++;
  6691. context = s;
  6692. }
  6693. s = strchr(st, '@');
  6694. if (s) {
  6695. /* Get username/password if there is one */
  6696. *s='\0';
  6697. username=st;
  6698. password = strchr(username, ':');
  6699. if (password) {
  6700. *password = '\0';
  6701. password++;
  6702. }
  6703. s++;
  6704. host = s;
  6705. } else {
  6706. /* Just a hostname */
  6707. host = st;
  6708. }
  6709. /* Populate our address from the given */
  6710. if (create_addr(&sin, NULL, NULL, NULL, host, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, NULL, NULL)) {
  6711. return -1;
  6712. }
  6713. ast_log(LOG_DEBUG, "host: %s, user: %s, password: %s, context: %s\n", host, username, password, context);
  6714. callno = find_callno(0, 0, &sin, NEW_FORCE, 1);
  6715. if (callno < 1) {
  6716. ast_log(LOG_WARNING, "Unable to create call\n");
  6717. return -1;
  6718. }
  6719. ast_mutex_lock(&iaxsl[callno]);
  6720. strncpy(iaxs[callno]->dproot, data, sizeof(iaxs[callno]->dproot)-1);
  6721. iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
  6722. iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
  6723. iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, "TBD");
  6724. if (context)
  6725. iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
  6726. if (username)
  6727. iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
  6728. iax_ie_append_int(&ied, IAX_IE_FORMAT, IAX_CAPABILITY_FULLBANDWIDTH);
  6729. iax_ie_append_int(&ied, IAX_IE_CAPABILITY, IAX_CAPABILITY_FULLBANDWIDTH);
  6730. /* Keep password handy */
  6731. if (password)
  6732. strncpy(iaxs[callno]->secret, password, sizeof(iaxs[callno]->secret)-1);
  6733. #if 0
  6734. /* XXX Need equivalent XXX */
  6735. if (option_verbose > 2)
  6736. ast_verbose(VERBOSE_PREFIX_3 "Calling TBD using options '%s'\n", requeststr);
  6737. #endif
  6738. /* Start the call going */
  6739. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
  6740. return callno;
  6741. }
  6742. static struct iax2_dpcache *find_cache(struct ast_channel *chan, char *data, char *context, char *exten, int priority)
  6743. {
  6744. struct iax2_dpcache *dp, *prev = NULL, *next;
  6745. struct timeval tv;
  6746. int x;
  6747. int com[2];
  6748. int timeout;
  6749. int old=0;
  6750. int outfd;
  6751. int abort;
  6752. int callno;
  6753. struct ast_channel *c;
  6754. struct ast_frame *f;
  6755. gettimeofday(&tv, NULL);
  6756. dp = dpcache;
  6757. while(dp) {
  6758. next = dp->next;
  6759. /* Expire old caches */
  6760. if ((tv.tv_sec > dp->expirey.tv_sec) ||
  6761. ((tv.tv_sec == dp->expirey.tv_sec) && (tv.tv_usec > dp->expirey.tv_usec))) {
  6762. /* It's expired, let it disappear */
  6763. if (prev)
  6764. prev->next = dp->next;
  6765. else
  6766. dpcache = dp->next;
  6767. if (!dp->peer && !(dp->flags & CACHE_FLAG_PENDING) && !dp->callno) {
  6768. /* Free memory and go again */
  6769. free(dp);
  6770. } else {
  6771. ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = %p callno = %d)\n", dp->flags, dp->peer, dp->callno);
  6772. }
  6773. dp = next;
  6774. continue;
  6775. }
  6776. /* We found an entry that matches us! */
  6777. if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
  6778. break;
  6779. prev = dp;
  6780. dp = next;
  6781. }
  6782. if (!dp) {
  6783. /* No matching entry. Create a new one. */
  6784. /* First, can we make a callno? */
  6785. callno = cache_get_callno_locked(data);
  6786. if (callno < 0) {
  6787. ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
  6788. return NULL;
  6789. }
  6790. dp = malloc(sizeof(struct iax2_dpcache));
  6791. if (!dp) {
  6792. ast_mutex_unlock(&iaxsl[callno]);
  6793. return NULL;
  6794. }
  6795. memset(dp, 0, sizeof(struct iax2_dpcache));
  6796. strncpy(dp->peercontext, data, sizeof(dp->peercontext)-1);
  6797. strncpy(dp->exten, exten, sizeof(dp->exten)-1);
  6798. gettimeofday(&dp->expirey, NULL);
  6799. dp->orig = dp->expirey;
  6800. /* Expires in 30 mins by default */
  6801. dp->expirey.tv_sec += iaxdefaultdpcache;
  6802. dp->next = dpcache;
  6803. dp->flags = CACHE_FLAG_PENDING;
  6804. for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
  6805. dp->waiters[x] = -1;
  6806. dpcache = dp;
  6807. dp->peer = iaxs[callno]->dpentries;
  6808. iaxs[callno]->dpentries = dp;
  6809. /* Send the request if we're already up */
  6810. if (iaxs[callno]->state & IAX_STATE_STARTED)
  6811. iax2_dprequest(dp, callno);
  6812. ast_mutex_unlock(&iaxsl[callno]);
  6813. }
  6814. /* By here we must have a dp */
  6815. if (dp->flags & CACHE_FLAG_PENDING) {
  6816. /* Okay, here it starts to get nasty. We need a pipe now to wait
  6817. for a reply to come back so long as it's pending */
  6818. for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++) {
  6819. /* Find an empty slot */
  6820. if (dp->waiters[x] < 0)
  6821. break;
  6822. }
  6823. if (x >= sizeof(dp->waiters) / sizeof(dp->waiters[0])) {
  6824. ast_log(LOG_WARNING, "No more waiter positions available\n");
  6825. return NULL;
  6826. }
  6827. if (pipe(com)) {
  6828. ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
  6829. return NULL;
  6830. }
  6831. dp->waiters[x] = com[1];
  6832. /* Okay, now we wait */
  6833. timeout = iaxdefaulttimeout * 1000;
  6834. /* Temporarily unlock */
  6835. ast_mutex_unlock(&dpcache_lock);
  6836. /* Defer any dtmf */
  6837. if (chan)
  6838. old = ast_channel_defer_dtmf(chan);
  6839. abort = 0;
  6840. while(timeout) {
  6841. c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &timeout);
  6842. if (outfd > -1) {
  6843. break;
  6844. }
  6845. if (c) {
  6846. f = ast_read(c);
  6847. if (f)
  6848. ast_frfree(f);
  6849. else {
  6850. /* Got hung up on, abort! */
  6851. break;
  6852. abort = 1;
  6853. }
  6854. }
  6855. }
  6856. if (!timeout) {
  6857. ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
  6858. }
  6859. ast_mutex_lock(&dpcache_lock);
  6860. dp->waiters[x] = -1;
  6861. close(com[1]);
  6862. close(com[0]);
  6863. if (abort) {
  6864. /* Don't interpret anything, just abort. Not sure what th epoint
  6865. of undeferring dtmf on a hung up channel is but hey whatever */
  6866. if (!old && chan)
  6867. ast_channel_undefer_dtmf(chan);
  6868. return NULL;
  6869. }
  6870. if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
  6871. /* Now to do non-independent analysis the results of our wait */
  6872. if (dp->flags & CACHE_FLAG_PENDING) {
  6873. /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
  6874. pending. Don't let it take as long to timeout. */
  6875. dp->flags &= ~CACHE_FLAG_PENDING;
  6876. dp->flags |= CACHE_FLAG_TIMEOUT;
  6877. /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
  6878. systems without leaving it unavailable once the server comes back online */
  6879. dp->expirey.tv_sec = dp->orig.tv_sec + 60;
  6880. for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
  6881. if (dp->waiters[x] > -1)
  6882. write(dp->waiters[x], "asdf", 4);
  6883. }
  6884. }
  6885. /* Our caller will obtain the rest */
  6886. if (!old && chan)
  6887. ast_channel_undefer_dtmf(chan);
  6888. }
  6889. return dp;
  6890. }
  6891. static int iax2_exists(struct ast_channel *chan, char *context, char *exten, int priority, char *callerid, char *data)
  6892. {
  6893. struct iax2_dpcache *dp;
  6894. int res = 0;
  6895. #if 0
  6896. ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
  6897. #endif
  6898. if ((priority != 1) && (priority != 2))
  6899. return 0;
  6900. ast_mutex_lock(&dpcache_lock);
  6901. dp = find_cache(chan, data, context, exten, priority);
  6902. if (dp) {
  6903. if (dp->flags & CACHE_FLAG_EXISTS)
  6904. res= 1;
  6905. }
  6906. ast_mutex_unlock(&dpcache_lock);
  6907. if (!dp) {
  6908. ast_log(LOG_WARNING, "Unable to make DP cache\n");
  6909. }
  6910. return res;
  6911. }
  6912. static int iax2_canmatch(struct ast_channel *chan, char *context, char *exten, int priority, char *callerid, char *data)
  6913. {
  6914. int res = 0;
  6915. struct iax2_dpcache *dp;
  6916. #if 0
  6917. ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
  6918. #endif
  6919. if ((priority != 1) && (priority != 2))
  6920. return 0;
  6921. ast_mutex_lock(&dpcache_lock);
  6922. dp = find_cache(chan, data, context, exten, priority);
  6923. if (dp) {
  6924. if (dp->flags & CACHE_FLAG_CANEXIST)
  6925. res= 1;
  6926. }
  6927. ast_mutex_unlock(&dpcache_lock);
  6928. if (!dp) {
  6929. ast_log(LOG_WARNING, "Unable to make DP cache\n");
  6930. }
  6931. return res;
  6932. }
  6933. static int iax2_matchmore(struct ast_channel *chan, char *context, char *exten, int priority, char *callerid, char *data)
  6934. {
  6935. int res = 0;
  6936. struct iax2_dpcache *dp;
  6937. #if 0
  6938. ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
  6939. #endif
  6940. if ((priority != 1) && (priority != 2))
  6941. return 0;
  6942. ast_mutex_lock(&dpcache_lock);
  6943. dp = find_cache(chan, data, context, exten, priority);
  6944. if (dp) {
  6945. if (dp->flags & CACHE_FLAG_MATCHMORE)
  6946. res= 1;
  6947. }
  6948. ast_mutex_unlock(&dpcache_lock);
  6949. if (!dp) {
  6950. ast_log(LOG_WARNING, "Unable to make DP cache\n");
  6951. }
  6952. return res;
  6953. }
  6954. static int iax2_exec(struct ast_channel *chan, char *context, char *exten, int priority, char *callerid, int newstack, char *data)
  6955. {
  6956. char odata[256];
  6957. char req[256];
  6958. char *ncontext;
  6959. char *dialstatus;
  6960. struct iax2_dpcache *dp;
  6961. struct ast_app *dial;
  6962. #if 0
  6963. ast_log(LOG_NOTICE, "iax2_exec: con: %s, exten: %s, pri: %d, cid: %s, data: %s, newstack: %d\n", context, exten, priority, callerid ? callerid : "<unknown>", data, newstack);
  6964. #endif
  6965. if (priority == 2) {
  6966. /* Indicate status, can be overridden in dialplan */
  6967. dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
  6968. if (dialstatus) {
  6969. dial = pbx_findapp(dialstatus);
  6970. if (dial)
  6971. pbx_exec(chan, dial, "", newstack);
  6972. }
  6973. return -1;
  6974. } else if (priority != 1)
  6975. return -1;
  6976. ast_mutex_lock(&dpcache_lock);
  6977. dp = find_cache(chan, data, context, exten, priority);
  6978. if (dp) {
  6979. if (dp->flags & CACHE_FLAG_EXISTS) {
  6980. strncpy(odata, data, sizeof(odata)-1);
  6981. ncontext = strchr(odata, '/');
  6982. if (ncontext) {
  6983. *ncontext = '\0';
  6984. ncontext++;
  6985. snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
  6986. } else {
  6987. snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
  6988. }
  6989. if (option_verbose > 2)
  6990. ast_verbose(VERBOSE_PREFIX_3 "Executing Dial('%s')\n", req);
  6991. } else {
  6992. ast_mutex_unlock(&dpcache_lock);
  6993. ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
  6994. return -1;
  6995. }
  6996. }
  6997. ast_mutex_unlock(&dpcache_lock);
  6998. dial = pbx_findapp("Dial");
  6999. if (dial) {
  7000. return pbx_exec(chan, dial, req, newstack);
  7001. } else {
  7002. ast_log(LOG_WARNING, "No dial application registered\n");
  7003. }
  7004. return -1;
  7005. }
  7006. static struct ast_switch iax2_switch =
  7007. {
  7008. name: "IAX2",
  7009. description: "IAX Remote Dialplan Switch",
  7010. exists: iax2_exists,
  7011. canmatch: iax2_canmatch,
  7012. exec: iax2_exec,
  7013. matchmore: iax2_matchmore,
  7014. };
  7015. static int __unload_module(void)
  7016. {
  7017. int x;
  7018. /* Cancel the network thread, close the net socket */
  7019. if (netthreadid != AST_PTHREADT_NULL) {
  7020. pthread_cancel(netthreadid);
  7021. pthread_join(netthreadid, NULL);
  7022. }
  7023. close(netsocket);
  7024. for (x=0;x<IAX_MAX_CALLS;x++)
  7025. if (iaxs[x])
  7026. iax2_destroy(x);
  7027. ast_manager_unregister( "IAXpeers" );
  7028. ast_cli_unregister(&cli_show_users);
  7029. ast_cli_unregister(&cli_show_channels);
  7030. ast_cli_unregister(&cli_show_peers);
  7031. ast_cli_unregister(&cli_show_peers_include);
  7032. ast_cli_unregister(&cli_show_peers_exclude);
  7033. ast_cli_unregister(&cli_show_peers_begin);
  7034. ast_cli_unregister(&cli_show_firmware);
  7035. ast_cli_unregister(&cli_show_registry);
  7036. ast_cli_unregister(&cli_provision);
  7037. ast_cli_unregister(&cli_debug);
  7038. ast_cli_unregister(&cli_trunk_debug);
  7039. ast_cli_unregister(&cli_no_debug);
  7040. ast_cli_unregister(&cli_set_jitter);
  7041. ast_cli_unregister(&cli_show_stats);
  7042. ast_cli_unregister(&cli_show_cache);
  7043. ast_unregister_switch(&iax2_switch);
  7044. ast_channel_unregister(type);
  7045. delete_users();
  7046. iax_provision_unload();
  7047. return 0;
  7048. }
  7049. int unload_module()
  7050. {
  7051. ast_mutex_destroy(&iaxq.lock);
  7052. ast_mutex_destroy(&userl.lock);
  7053. ast_mutex_destroy(&peerl.lock);
  7054. ast_mutex_destroy(&waresl.lock);
  7055. return __unload_module();
  7056. }
  7057. int load_module(void)
  7058. {
  7059. char *config = "iax.conf";
  7060. int res = 0;
  7061. int x;
  7062. char iabuf[INET_ADDRSTRLEN];
  7063. struct iax2_registry *reg;
  7064. struct iax2_peer *peer;
  7065. struct sockaddr_in sin;
  7066. iax_set_output(iax_debug_output);
  7067. iax_set_error(iax_error_output);
  7068. /* Seed random number generator */
  7069. srand(time(NULL));
  7070. sin.sin_family = AF_INET;
  7071. sin.sin_port = htons(IAX_DEFAULT_PORTNO);
  7072. sin.sin_addr.s_addr = INADDR_ANY;
  7073. #ifdef IAX_TRUNKING
  7074. #ifdef ZT_TIMERACK
  7075. timingfd = open("/dev/zap/timer", O_RDWR);
  7076. if (timingfd < 0)
  7077. #endif
  7078. timingfd = open("/dev/zap/pseudo", O_RDWR);
  7079. if (timingfd < 0)
  7080. ast_log(LOG_WARNING, "Unable to open IAX timing interface: %s\n", strerror(errno));
  7081. #endif
  7082. memset(iaxs, 0, sizeof(iaxs));
  7083. for (x=0;x<IAX_MAX_CALLS;x++)
  7084. ast_mutex_init(&iaxsl[x]);
  7085. io = io_context_create();
  7086. sched = sched_context_create();
  7087. if (!io || !sched) {
  7088. ast_log(LOG_ERROR, "Out of memory\n");
  7089. return -1;
  7090. }
  7091. ast_mutex_init(&iaxq.lock);
  7092. ast_mutex_init(&userl.lock);
  7093. ast_mutex_init(&peerl.lock);
  7094. ast_mutex_init(&waresl.lock);
  7095. ast_cli_register(&cli_show_users);
  7096. ast_cli_register(&cli_show_channels);
  7097. ast_cli_register(&cli_show_peers);
  7098. ast_cli_register(&cli_show_peers_include);
  7099. ast_cli_register(&cli_show_peers_exclude);
  7100. ast_cli_register(&cli_show_peers_begin);
  7101. ast_cli_register(&cli_show_firmware);
  7102. ast_cli_register(&cli_show_registry);
  7103. ast_cli_register(&cli_provision);
  7104. ast_cli_register(&cli_debug);
  7105. ast_cli_register(&cli_trunk_debug);
  7106. ast_cli_register(&cli_no_debug);
  7107. ast_cli_register(&cli_set_jitter);
  7108. ast_cli_register(&cli_show_stats);
  7109. ast_cli_register(&cli_show_cache);
  7110. ast_manager_register( "IAXpeers", 0, manager_iax2_show_peers, "List IAX Peers" );
  7111. set_config(config,&sin);
  7112. if (ast_channel_register(type, tdesc, iax2_capability, iax2_request)) {
  7113. ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
  7114. __unload_module();
  7115. return -1;
  7116. }
  7117. if (ast_register_switch(&iax2_switch))
  7118. ast_log(LOG_ERROR, "Unable to register IAX switch\n");
  7119. /* Make a UDP socket */
  7120. netsocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
  7121. if (netsocket < 0) {
  7122. ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
  7123. return -1;
  7124. }
  7125. if (bind(netsocket,(struct sockaddr *)&sin, sizeof(sin))) {
  7126. ast_log(LOG_ERROR, "Unable to bind to %s port %d: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), strerror(errno));
  7127. return -1;
  7128. }
  7129. if (option_verbose > 1)
  7130. ast_verbose(VERBOSE_PREFIX_2 "Using TOS bits %d\n", tos);
  7131. if (setsockopt(netsocket, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)))
  7132. ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
  7133. res = start_network_thread();
  7134. if (!res) {
  7135. if (option_verbose > 1)
  7136. ast_verbose(VERBOSE_PREFIX_2 "IAX Ready and Listening on %s port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
  7137. } else {
  7138. ast_log(LOG_ERROR, "Unable to start network thread\n");
  7139. close(netsocket);
  7140. }
  7141. for (reg = registrations; reg; reg = reg->next)
  7142. iax2_do_register(reg);
  7143. ast_mutex_lock(&peerl.lock);
  7144. for (peer = peerl.peers; peer; peer = peer->next)
  7145. iax2_poke_peer(peer, 0);
  7146. ast_mutex_unlock(&peerl.lock);
  7147. reload_firmware();
  7148. iax_provision_reload();
  7149. return res;
  7150. }
  7151. char *description()
  7152. {
  7153. return desc;
  7154. }
  7155. int usecount()
  7156. {
  7157. int res;
  7158. ast_mutex_lock(&usecnt_lock);
  7159. res = usecnt;
  7160. ast_mutex_unlock(&usecnt_lock);
  7161. return res;
  7162. }
  7163. char *key()
  7164. {
  7165. return ASTERISK_GPL_KEY;
  7166. }