chan_iax2.c 490 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2006, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*! \file
  19. *
  20. * \brief Implementation of Inter-Asterisk eXchange Version 2
  21. * as specified in RFC 5456
  22. *
  23. * \author Mark Spencer <markster@digium.com>
  24. *
  25. * \par See also
  26. * \arg \ref Config_iax
  27. *
  28. * \ingroup channel_drivers
  29. *
  30. * \todo Implement musicclass settings for IAX2 devices
  31. */
  32. /*** MODULEINFO
  33. <use type="external">crypto</use>
  34. <support_level>core</support_level>
  35. ***/
  36. #include "asterisk.h"
  37. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  38. #include <sys/mman.h>
  39. #include <dirent.h>
  40. #include <sys/socket.h>
  41. #include <netinet/in.h>
  42. #include <arpa/inet.h>
  43. #include <netinet/in_systm.h>
  44. #include <netinet/ip.h>
  45. #include <sys/time.h>
  46. #include <sys/signal.h>
  47. #include <signal.h>
  48. #include <strings.h>
  49. #include <netdb.h>
  50. #include <fcntl.h>
  51. #include <sys/stat.h>
  52. #include <regex.h>
  53. #include "asterisk/paths.h" /* need ast_config_AST_DATA_DIR for firmware */
  54. #include "asterisk/lock.h"
  55. #include "asterisk/frame.h"
  56. #include "asterisk/channel.h"
  57. #include "asterisk/module.h"
  58. #include "asterisk/pbx.h"
  59. #include "asterisk/sched.h"
  60. #include "asterisk/io.h"
  61. #include "asterisk/config.h"
  62. #include "asterisk/cli.h"
  63. #include "asterisk/translate.h"
  64. #include "asterisk/md5.h"
  65. #include "asterisk/cdr.h"
  66. #include "asterisk/crypto.h"
  67. #include "asterisk/acl.h"
  68. #include "asterisk/manager.h"
  69. #include "asterisk/callerid.h"
  70. #include "asterisk/app.h"
  71. #include "asterisk/astdb.h"
  72. #include "asterisk/musiconhold.h"
  73. #include "asterisk/features.h"
  74. #include "asterisk/utils.h"
  75. #include "asterisk/causes.h"
  76. #include "asterisk/localtime.h"
  77. #include "asterisk/dnsmgr.h"
  78. #include "asterisk/devicestate.h"
  79. #include "asterisk/netsock.h"
  80. #include "asterisk/stringfields.h"
  81. #include "asterisk/linkedlists.h"
  82. #include "asterisk/event.h"
  83. #include "asterisk/astobj2.h"
  84. #include "asterisk/timing.h"
  85. #include "asterisk/taskprocessor.h"
  86. #include "asterisk/test.h"
  87. #include "asterisk/data.h"
  88. #include "asterisk/netsock2.h"
  89. #include "iax2.h"
  90. #include "iax2-parser.h"
  91. #include "iax2-provision.h"
  92. #include "jitterbuf.h"
  93. /*** DOCUMENTATION
  94. <application name="IAX2Provision" language="en_US">
  95. <synopsis>
  96. Provision a calling IAXy with a given template.
  97. </synopsis>
  98. <syntax>
  99. <parameter name="template">
  100. <para>If not specified, defaults to <literal>default</literal>.</para>
  101. </parameter>
  102. </syntax>
  103. <description>
  104. <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
  105. given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
  106. or <literal>0</literal> on success.</para>
  107. </description>
  108. </application>
  109. <function name="IAXPEER" language="en_US">
  110. <synopsis>
  111. Gets IAX peer information.
  112. </synopsis>
  113. <syntax>
  114. <parameter name="peername" required="true">
  115. <enumlist>
  116. <enum name="CURRENTCHANNEL">
  117. <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
  118. endpoint of the current channel</para>
  119. </enum>
  120. </enumlist>
  121. </parameter>
  122. <parameter name="item">
  123. <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
  124. <enumlist>
  125. <enum name="ip">
  126. <para>(default) The IP address.</para>
  127. </enum>
  128. <enum name="status">
  129. <para>The peer's status (if <literal>qualify=yes</literal>)</para>
  130. </enum>
  131. <enum name="mailbox">
  132. <para>The configured mailbox.</para>
  133. </enum>
  134. <enum name="context">
  135. <para>The configured context.</para>
  136. </enum>
  137. <enum name="expire">
  138. <para>The epoch time of the next expire.</para>
  139. </enum>
  140. <enum name="dynamic">
  141. <para>Is it dynamic? (yes/no).</para>
  142. </enum>
  143. <enum name="callerid_name">
  144. <para>The configured Caller ID name.</para>
  145. </enum>
  146. <enum name="callerid_num">
  147. <para>The configured Caller ID number.</para>
  148. </enum>
  149. <enum name="codecs">
  150. <para>The configured codecs.</para>
  151. </enum>
  152. <enum name="codec[x]">
  153. <para>Preferred codec index number <replaceable>x</replaceable> (beginning
  154. with <literal>0</literal>)</para>
  155. </enum>
  156. </enumlist>
  157. </parameter>
  158. </syntax>
  159. <description>
  160. <para>Gets information associated with the specified IAX2 peer.</para>
  161. </description>
  162. <see-also>
  163. <ref type="function">SIPPEER</ref>
  164. </see-also>
  165. </function>
  166. <function name="IAXVAR" language="en_US">
  167. <synopsis>
  168. Sets or retrieves a remote variable.
  169. </synopsis>
  170. <syntax>
  171. <parameter name="varname" required="true" />
  172. </syntax>
  173. <description>
  174. <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
  175. </description>
  176. </function>
  177. <manager name="IAXpeers" language="en_US">
  178. <synopsis>
  179. List IAX peers.
  180. </synopsis>
  181. <syntax>
  182. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  183. </syntax>
  184. <description>
  185. </description>
  186. </manager>
  187. <manager name="IAXpeerlist" language="en_US">
  188. <synopsis>
  189. List IAX Peers.
  190. </synopsis>
  191. <syntax>
  192. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  193. </syntax>
  194. <description>
  195. <para>List all the IAX peers.</para>
  196. </description>
  197. </manager>
  198. <manager name="IAXnetstats" language="en_US">
  199. <synopsis>
  200. Show IAX Netstats.
  201. </synopsis>
  202. <syntax />
  203. <description>
  204. <para>Show IAX channels network statistics.</para>
  205. </description>
  206. </manager>
  207. <manager name="IAXregistry" language="en_US">
  208. <synopsis>
  209. Show IAX registrations.
  210. </synopsis>
  211. <syntax>
  212. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  213. </syntax>
  214. <description>
  215. <para>Show IAX registrations.</para>
  216. </description>
  217. </manager>
  218. ***/
  219. /* Define SCHED_MULTITHREADED to run the scheduler in a special
  220. multithreaded mode. */
  221. #define SCHED_MULTITHREADED
  222. /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
  223. thread is actually doing. */
  224. #define DEBUG_SCHED_MULTITHREAD
  225. #ifdef SO_NO_CHECK
  226. static int nochecksums = 0;
  227. #endif
  228. #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
  229. #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
  230. #define DEFAULT_THREAD_COUNT 10
  231. #define DEFAULT_MAX_THREAD_COUNT 100
  232. #define DEFAULT_RETRY_TIME 1000
  233. #define MEMORY_SIZE 100
  234. #define DEFAULT_DROP 3
  235. #define DEBUG_SUPPORT
  236. #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
  237. /* Sample over last 100 units to determine historic jitter */
  238. #define GAMMA (0.01)
  239. static struct ast_codec_pref prefs;
  240. static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
  241. /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
  242. fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
  243. #define MAX_TRUNK_MTU 1240
  244. static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
  245. static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
  246. #define DEFAULT_CONTEXT "default"
  247. static char default_parkinglot[AST_MAX_CONTEXT];
  248. static char language[MAX_LANGUAGE] = "";
  249. static char regcontext[AST_MAX_CONTEXT] = "";
  250. static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
  251. static struct ast_event_sub *acl_change_event_subscription; /*!< subscription id for ACL change events */
  252. static int network_change_event_sched_id = -1;
  253. static int maxauthreq = 3;
  254. static int max_retries = 4;
  255. static int ping_time = 21;
  256. static int lagrq_time = 10;
  257. static int maxjitterbuffer=1000;
  258. static int resyncthreshold=1000;
  259. static int maxjitterinterps=10;
  260. static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
  261. #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
  262. static int trunkfreq = 20;
  263. static int trunkmaxsize = MAX_TRUNKDATA;
  264. static int authdebug = 0;
  265. static int autokill = 0;
  266. static int iaxcompat = 0;
  267. static int last_authmethod = 0;
  268. static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
  269. static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
  270. static struct {
  271. unsigned int tos;
  272. unsigned int cos;
  273. } qos = { 0, 0 };
  274. static int min_reg_expire;
  275. static int max_reg_expire;
  276. static int srvlookup = 0;
  277. static struct ast_timer *timer; /* Timer for trunking */
  278. static struct ast_netsock_list *netsock;
  279. static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
  280. static int defaultsockfd = -1;
  281. static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
  282. /* Ethernet, etc */
  283. #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
  284. /* T1, maybe ISDN */
  285. #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
  286. ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR) & \
  287. ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR16) & \
  288. ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN7) & \
  289. ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN14) & \
  290. ~ast_format_id_to_old_bitfield(AST_FORMAT_G719) & \
  291. ~ast_format_id_to_old_bitfield(AST_FORMAT_ULAW) & \
  292. ~ast_format_id_to_old_bitfield(AST_FORMAT_ALAW) & \
  293. ~ast_format_id_to_old_bitfield(AST_FORMAT_G722))
  294. /* A modem */
  295. #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
  296. ~ast_format_id_to_old_bitfield(AST_FORMAT_G726) & \
  297. ~ast_format_id_to_old_bitfield(AST_FORMAT_G726_AAL2) & \
  298. ~ast_format_id_to_old_bitfield(AST_FORMAT_ADPCM))
  299. #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
  300. ~ast_format_id_to_old_bitfield(AST_FORMAT_G723_1))
  301. #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
  302. #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
  303. #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
  304. /* if a pvt has encryption setup done and is running on the call */
  305. #define IAX_CALLENCRYPTED(pvt) \
  306. (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
  307. #define IAX_DEBUGDIGEST(msg, key) do { \
  308. int idx; \
  309. char digest[33] = ""; \
  310. \
  311. if (!iaxdebug) \
  312. break; \
  313. \
  314. for (idx = 0; idx < 16; idx++) \
  315. sprintf(digest + (idx << 1), "%02hhx", (unsigned char) key[idx]); \
  316. \
  317. ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
  318. } while(0)
  319. static struct io_context *io;
  320. static struct ast_sched_context *sched;
  321. #define DONT_RESCHEDULE -2
  322. static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
  323. static int iaxdebug = 0;
  324. static int iaxtrunkdebug = 0;
  325. static int test_losspct = 0;
  326. #ifdef IAXTESTS
  327. static int test_late = 0;
  328. static int test_resync = 0;
  329. static int test_jit = 0;
  330. static int test_jitpct = 0;
  331. #endif /* IAXTESTS */
  332. static char accountcode[AST_MAX_ACCOUNT_CODE];
  333. static char mohinterpret[MAX_MUSICCLASS];
  334. static char mohsuggest[MAX_MUSICCLASS];
  335. static int amaflags = 0;
  336. static int adsi = 0;
  337. static int delayreject = 0;
  338. static int iax2_encryption = 0;
  339. static struct ast_flags64 globalflags = { 0 };
  340. static pthread_t netthreadid = AST_PTHREADT_NULL;
  341. enum iax2_state {
  342. IAX_STATE_STARTED = (1 << 0),
  343. IAX_STATE_AUTHENTICATED = (1 << 1),
  344. IAX_STATE_TBD = (1 << 2),
  345. };
  346. struct iax2_context {
  347. char context[AST_MAX_CONTEXT];
  348. struct iax2_context *next;
  349. };
  350. #define IAX_HASCALLERID (uint64_t)(1 << 0) /*!< CallerID has been specified */
  351. #define IAX_DELME (uint64_t)(1 << 1) /*!< Needs to be deleted */
  352. #define IAX_TEMPONLY (uint64_t)(1 << 2) /*!< Temporary (realtime) */
  353. #define IAX_TRUNK (uint64_t)(1 << 3) /*!< Treat as a trunk */
  354. #define IAX_NOTRANSFER (uint64_t)(1 << 4) /*!< Don't native bridge */
  355. #define IAX_USEJITTERBUF (uint64_t)(1 << 5) /*!< Use jitter buffer */
  356. #define IAX_DYNAMIC (uint64_t)(1 << 6) /*!< dynamic peer */
  357. #define IAX_SENDANI (uint64_t)(1 << 7) /*!< Send ANI along with CallerID */
  358. #define IAX_RTSAVE_SYSNAME (uint64_t)(1 << 8) /*!< Save Systname on Realtime Updates */
  359. #define IAX_ALREADYGONE (uint64_t)(1 << 9) /*!< Already disconnected */
  360. #define IAX_PROVISION (uint64_t)(1 << 10) /*!< This is a provisioning request */
  361. #define IAX_QUELCH (uint64_t)(1 << 11) /*!< Whether or not we quelch audio */
  362. #define IAX_ENCRYPTED (uint64_t)(1 << 12) /*!< Whether we should assume encrypted tx/rx */
  363. #define IAX_KEYPOPULATED (uint64_t)(1 << 13) /*!< Whether we have a key populated */
  364. #define IAX_CODEC_USER_FIRST (uint64_t)(1 << 14) /*!< are we willing to let the other guy choose the codec? */
  365. #define IAX_CODEC_NOPREFS (uint64_t)(1 << 15) /*!< Force old behaviour by turning off prefs */
  366. #define IAX_CODEC_NOCAP (uint64_t)(1 << 16) /*!< only consider requested format and ignore capabilities*/
  367. #define IAX_RTCACHEFRIENDS (uint64_t)(1 << 17) /*!< let realtime stay till your reload */
  368. #define IAX_RTUPDATE (uint64_t)(1 << 18) /*!< Send a realtime update */
  369. #define IAX_RTAUTOCLEAR (uint64_t)(1 << 19) /*!< erase me on expire */
  370. #define IAX_FORCEJITTERBUF (uint64_t)(1 << 20) /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
  371. #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1 << 21) /*!< When using realtime, ignore registration expiration */
  372. #define IAX_TRUNKTIMESTAMPS (uint64_t)(1 << 22) /*!< Send trunk timestamps */
  373. #define IAX_TRANSFERMEDIA (uint64_t)(1 << 23) /*!< When doing IAX2 transfers, transfer media only */
  374. #define IAX_MAXAUTHREQ (uint64_t)(1 << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
  375. #define IAX_DELAYPBXSTART (uint64_t)(1 << 25) /*!< Don't start a PBX on the channel until the peer sends us a response, so that we've achieved a three-way handshake with them before sending voice or anything else */
  376. #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1 << 26) /*!< Allow the FWDOWNL command? */
  377. #define IAX_IMMEDIATE (uint64_t)(1 << 27) /*!< Allow immediate off-hook to extension s */
  378. #define IAX_SENDCONNECTEDLINE (uint64_t)(1 << 28) /*!< Allow sending of connected line updates */
  379. #define IAX_RECVCONNECTEDLINE (uint64_t)(1 << 29) /*!< Allow receiving of connected line updates */
  380. #define IAX_FORCE_ENCRYPT (uint64_t)(1 << 30) /*!< Forces call encryption, if encryption not possible hangup */
  381. #define IAX_SHRINKCALLERID (uint64_t)(1 << 31) /*!< Turn on and off caller id shrinking */
  382. static int global_rtautoclear = 120;
  383. static int reload_config(int forced_reload);
  384. /*!
  385. * \brief Call token validation settings.
  386. */
  387. enum calltoken_peer_enum {
  388. /*! \brief Default calltoken required unless the ip is in the ignorelist */
  389. CALLTOKEN_DEFAULT = 0,
  390. /*! \brief Require call token validation. */
  391. CALLTOKEN_YES = 1,
  392. /*! \brief Require call token validation after a successful registration
  393. * using call token validation occurs. */
  394. CALLTOKEN_AUTO = 2,
  395. /*! \brief Do not require call token validation. */
  396. CALLTOKEN_NO = 3,
  397. };
  398. struct iax2_user {
  399. AST_DECLARE_STRING_FIELDS(
  400. AST_STRING_FIELD(name);
  401. AST_STRING_FIELD(secret);
  402. AST_STRING_FIELD(dbsecret);
  403. AST_STRING_FIELD(accountcode);
  404. AST_STRING_FIELD(mohinterpret);
  405. AST_STRING_FIELD(mohsuggest);
  406. AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
  407. AST_STRING_FIELD(language);
  408. AST_STRING_FIELD(cid_num);
  409. AST_STRING_FIELD(cid_name);
  410. AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
  411. );
  412. int authmethods;
  413. int encmethods;
  414. int amaflags;
  415. int adsi;
  416. uint64_t flags;
  417. iax2_format capability;
  418. int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
  419. int curauthreq; /*!< Current number of outstanding AUTHREQs */
  420. struct ast_codec_pref prefs;
  421. struct ast_acl_list *acl;
  422. struct iax2_context *contexts;
  423. struct ast_variable *vars;
  424. enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
  425. };
  426. struct iax2_peer {
  427. AST_DECLARE_STRING_FIELDS(
  428. AST_STRING_FIELD(name);
  429. AST_STRING_FIELD(username);
  430. AST_STRING_FIELD(description); /*!< Description of the peer */
  431. AST_STRING_FIELD(secret);
  432. AST_STRING_FIELD(dbsecret);
  433. AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
  434. AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
  435. AST_STRING_FIELD(context); /*!< For transfers only */
  436. AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
  437. AST_STRING_FIELD(mailbox); /*!< Mailbox */
  438. AST_STRING_FIELD(mohinterpret);
  439. AST_STRING_FIELD(mohsuggest);
  440. AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
  441. /* Suggested caller id if registering */
  442. AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
  443. AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
  444. AST_STRING_FIELD(zonetag); /*!< Time Zone */
  445. AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
  446. );
  447. struct ast_codec_pref prefs;
  448. struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
  449. struct ast_sockaddr addr;
  450. int formats;
  451. int sockfd; /*!< Socket to use for transmission */
  452. struct in_addr mask;
  453. int adsi;
  454. uint64_t flags;
  455. /* Dynamic Registration fields */
  456. struct sockaddr_in defaddr; /*!< Default address if there is one */
  457. int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
  458. int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
  459. int expire; /*!< Schedule entry for expiry */
  460. int expiry; /*!< How soon to expire */
  461. iax2_format capability; /*!< Capability */
  462. /* Qualification */
  463. int callno; /*!< Call number of POKE request */
  464. int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
  465. int lastms; /*!< How long last response took (in ms), or -1 for no response */
  466. int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
  467. int pokefreqok; /*!< How often to check if the host is up */
  468. int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
  469. int historicms; /*!< How long recent average responses took */
  470. int smoothing; /*!< Sample over how many units to determine historic ms */
  471. uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
  472. struct ast_event_sub *mwi_event_sub;
  473. struct ast_acl_list *acl;
  474. enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
  475. };
  476. #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
  477. struct iax2_trunk_peer {
  478. ast_mutex_t lock;
  479. int sockfd;
  480. struct sockaddr_in addr;
  481. struct timeval txtrunktime; /*!< Transmit trunktime */
  482. struct timeval rxtrunktime; /*!< Receive trunktime */
  483. struct timeval lasttxtime; /*!< Last transmitted trunktime */
  484. struct timeval trunkact; /*!< Last trunk activity */
  485. unsigned int lastsent; /*!< Last sent time */
  486. /* Trunk data and length */
  487. unsigned char *trunkdata;
  488. unsigned int trunkdatalen;
  489. unsigned int trunkdataalloc;
  490. int trunkmaxmtu;
  491. int trunkerror;
  492. int calls;
  493. AST_LIST_ENTRY(iax2_trunk_peer) list;
  494. };
  495. static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
  496. struct iax_firmware {
  497. AST_LIST_ENTRY(iax_firmware) list;
  498. int fd;
  499. int mmaplen;
  500. int dead;
  501. struct ast_iax2_firmware_header *fwh;
  502. unsigned char *buf;
  503. };
  504. enum iax_reg_state {
  505. REG_STATE_UNREGISTERED = 0,
  506. REG_STATE_REGSENT,
  507. REG_STATE_AUTHSENT,
  508. REG_STATE_REGISTERED,
  509. REG_STATE_REJECTED,
  510. REG_STATE_TIMEOUT,
  511. REG_STATE_NOAUTH
  512. };
  513. enum iax_transfer_state {
  514. TRANSFER_NONE = 0,
  515. TRANSFER_BEGIN,
  516. TRANSFER_READY,
  517. TRANSFER_RELEASED,
  518. TRANSFER_PASSTHROUGH,
  519. TRANSFER_MBEGIN,
  520. TRANSFER_MREADY,
  521. TRANSFER_MRELEASED,
  522. TRANSFER_MPASSTHROUGH,
  523. TRANSFER_MEDIA,
  524. TRANSFER_MEDIAPASS
  525. };
  526. struct iax2_registry {
  527. struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
  528. char username[80];
  529. char secret[80]; /*!< Password or key name in []'s */
  530. int expire; /*!< Sched ID of expiration */
  531. int refresh; /*!< How often to refresh */
  532. enum iax_reg_state regstate;
  533. int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
  534. int callno; /*!< Associated call number if applicable */
  535. struct sockaddr_in us; /*!< Who the server thinks we are */
  536. struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
  537. AST_LIST_ENTRY(iax2_registry) entry;
  538. int port;
  539. char hostname[];
  540. };
  541. static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
  542. /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
  543. #define MIN_RETRY_TIME 100
  544. #define MAX_RETRY_TIME 10000
  545. #define MAX_JITTER_BUFFER 50
  546. #define MIN_JITTER_BUFFER 10
  547. #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
  548. #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
  549. /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
  550. #define TS_GAP_FOR_JB_RESYNC 5000
  551. /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
  552. #define MARK_IAX_SUBCLASS_TX 0x8000
  553. static int iaxthreadcount = DEFAULT_THREAD_COUNT;
  554. static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
  555. static int iaxdynamicthreadcount = 0;
  556. static int iaxdynamicthreadnum = 0;
  557. static int iaxactivethreadcount = 0;
  558. struct iax_rr {
  559. int jitter;
  560. int losspct;
  561. int losscnt;
  562. int packets;
  563. int delay;
  564. int dropped;
  565. int ooo;
  566. };
  567. struct iax2_pvt_ref;
  568. struct chan_iax2_pvt {
  569. /*! Socket to send/receive on for this call */
  570. int sockfd;
  571. /*! ast_callid bound to dialog */
  572. struct ast_callid *callid;
  573. /*! Last received voice format */
  574. iax2_format voiceformat;
  575. /*! Last received video format */
  576. iax2_format videoformat;
  577. /*! Last sent voice format */
  578. iax2_format svoiceformat;
  579. /*! Last sent video format */
  580. iax2_format svideoformat;
  581. /*! What we are capable of sending */
  582. iax2_format capability;
  583. /*! Last received timestamp */
  584. unsigned int last;
  585. /*! Last sent timestamp - never send the same timestamp twice in a single call */
  586. unsigned int lastsent;
  587. /*! Timestamp of the last video frame sent */
  588. unsigned int lastvsent;
  589. /*! Next outgoing timestamp if everything is good */
  590. unsigned int nextpred;
  591. /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
  592. int first_iax_message;
  593. /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
  594. int last_iax_message;
  595. /*! True if the last voice we transmitted was not silence/CNG */
  596. unsigned int notsilenttx:1;
  597. /*! Ping time */
  598. unsigned int pingtime;
  599. /*! Max time for initial response */
  600. int maxtime;
  601. /*! Peer Address */
  602. struct sockaddr_in addr;
  603. /*! Actual used codec preferences */
  604. struct ast_codec_pref prefs;
  605. /*! Requested codec preferences */
  606. struct ast_codec_pref rprefs;
  607. /*! Our call number */
  608. unsigned short callno;
  609. /*! Our callno_entry entry */
  610. struct callno_entry *callno_entry;
  611. /*! Peer callno */
  612. unsigned short peercallno;
  613. /*! Negotiated format, this is only used to remember what format was
  614. chosen for an unauthenticated call so that the channel can get
  615. created later using the right format */
  616. iax2_format chosenformat;
  617. /*! Peer selected format */
  618. iax2_format peerformat;
  619. /*! Peer capability */
  620. iax2_format peercapability;
  621. /*! timeval that we base our transmission on */
  622. struct timeval offset;
  623. /*! timeval that we base our delivery on */
  624. struct timeval rxcore;
  625. /*! The jitterbuffer */
  626. jitterbuf *jb;
  627. /*! active jb read scheduler id */
  628. int jbid;
  629. /*! LAG */
  630. int lag;
  631. /*! Error, as discovered by the manager */
  632. int error;
  633. /*! Owner if we have one */
  634. struct ast_channel *owner;
  635. /*! What's our state? */
  636. struct ast_flags state;
  637. /*! Expiry (optional) */
  638. int expiry;
  639. /*! Next outgoing sequence number */
  640. unsigned char oseqno;
  641. /*! Next sequence number they have not yet acknowledged */
  642. unsigned char rseqno;
  643. /*! Next incoming sequence number */
  644. unsigned char iseqno;
  645. /*! Last incoming sequence number we have acknowledged */
  646. unsigned char aseqno;
  647. AST_DECLARE_STRING_FIELDS(
  648. /*! Peer name */
  649. AST_STRING_FIELD(peer);
  650. /*! Default Context */
  651. AST_STRING_FIELD(context);
  652. /*! Caller ID if available */
  653. AST_STRING_FIELD(cid_num);
  654. AST_STRING_FIELD(cid_name);
  655. /*! Hidden Caller ID (i.e. ANI) if appropriate */
  656. AST_STRING_FIELD(ani);
  657. /*! DNID */
  658. AST_STRING_FIELD(dnid);
  659. /*! RDNIS */
  660. AST_STRING_FIELD(rdnis);
  661. /*! Requested Extension */
  662. AST_STRING_FIELD(exten);
  663. /*! Expected Username */
  664. AST_STRING_FIELD(username);
  665. /*! Expected Secret */
  666. AST_STRING_FIELD(secret);
  667. /*! MD5 challenge */
  668. AST_STRING_FIELD(challenge);
  669. /*! Public keys permitted keys for incoming authentication */
  670. AST_STRING_FIELD(inkeys);
  671. /*! Private key for outgoing authentication */
  672. AST_STRING_FIELD(outkey);
  673. /*! Preferred language */
  674. AST_STRING_FIELD(language);
  675. /*! Hostname/peername for naming purposes */
  676. AST_STRING_FIELD(host);
  677. AST_STRING_FIELD(dproot);
  678. AST_STRING_FIELD(accountcode);
  679. AST_STRING_FIELD(mohinterpret);
  680. AST_STRING_FIELD(mohsuggest);
  681. /*! received OSP token */
  682. AST_STRING_FIELD(osptoken);
  683. /*! Default parkinglot */
  684. AST_STRING_FIELD(parkinglot);
  685. );
  686. /*! AUTHREJ all AUTHREP frames */
  687. int authrej;
  688. /*! permitted authentication methods */
  689. int authmethods;
  690. /*! permitted encryption methods */
  691. int encmethods;
  692. /*! Encryption AES-128 Key */
  693. ast_aes_encrypt_key ecx;
  694. /*! Decryption AES-128 Key corresponding to ecx */
  695. ast_aes_decrypt_key mydcx;
  696. /*! Decryption AES-128 Key used to decrypt peer frames */
  697. ast_aes_decrypt_key dcx;
  698. /*! scheduler id associated with iax_key_rotate
  699. * for encrypted calls*/
  700. int keyrotateid;
  701. /*! 32 bytes of semi-random data */
  702. unsigned char semirand[32];
  703. /*! Associated registry */
  704. struct iax2_registry *reg;
  705. /*! Associated peer for poking */
  706. struct iax2_peer *peerpoke;
  707. /*! IAX_ flags */
  708. uint64_t flags;
  709. int adsi;
  710. /*! Transferring status */
  711. enum iax_transfer_state transferring;
  712. /*! Transfer identifier */
  713. int transferid;
  714. /*! Who we are IAX transferring to */
  715. struct sockaddr_in transfer;
  716. /*! What's the new call number for the transfer */
  717. unsigned short transfercallno;
  718. /*! Transfer encrypt AES-128 Key */
  719. ast_aes_encrypt_key tdcx;
  720. /*! Status of knowledge of peer ADSI capability */
  721. int peeradsicpe;
  722. /*! Callno of native bridge peer. (Valid if nonzero) */
  723. unsigned short bridgecallno;
  724. int pingid; /*!< Transmit PING request */
  725. int lagid; /*!< Retransmit lag request */
  726. int autoid; /*!< Auto hangup for Dialplan requestor */
  727. int authid; /*!< Authentication rejection ID */
  728. int authfail; /*!< Reason to report failure */
  729. int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
  730. int calling_ton;
  731. int calling_tns;
  732. int calling_pres;
  733. int amaflags;
  734. AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
  735. /*! variables inherited from the user definition */
  736. struct ast_variable *vars;
  737. /*! variables transmitted in a NEW packet */
  738. struct ast_variable *iaxvars;
  739. /*! last received remote rr */
  740. struct iax_rr remote_rr;
  741. /*! Current base time: (just for stats) */
  742. int min;
  743. /*! Dropped frame count: (just for stats) */
  744. int frames_dropped;
  745. /*! received frame count: (just for stats) */
  746. int frames_received;
  747. /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
  748. unsigned char calltoken_ie_len;
  749. /*! hold all signaling frames from the pbx thread until we have a destination callno */
  750. char hold_signaling;
  751. /*! frame queue for signaling frames from pbx thread waiting for destination callno */
  752. AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
  753. };
  754. struct signaling_queue_entry {
  755. struct ast_frame f;
  756. AST_LIST_ENTRY(signaling_queue_entry) next;
  757. };
  758. /*! table of available call numbers */
  759. static struct ao2_container *callno_pool;
  760. /*! table of available trunk call numbers */
  761. static struct ao2_container *callno_pool_trunk;
  762. static const unsigned int CALLNO_POOL_BUCKETS = 2699;
  763. /*!
  764. * \brief a list of frames that may need to be retransmitted
  765. *
  766. * \note The contents of this list do not need to be explicitly destroyed
  767. * on module unload. This is because all active calls are destroyed, and
  768. * all frames in this queue will get destroyed as a part of that process.
  769. *
  770. * \note Contents protected by the iaxsl[] locks
  771. */
  772. static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
  773. static struct ast_taskprocessor *transmit_processor;
  774. static int randomcalltokendata;
  775. static const time_t MAX_CALLTOKEN_DELAY = 10;
  776. /*!
  777. * This module will get much higher performance when doing a lot of
  778. * user and peer lookups if the number of buckets is increased from 1.
  779. * However, to maintain old behavior for Asterisk 1.4, these are set to
  780. * 1 by default. When using multiple buckets, search order through these
  781. * containers is considered random, so you will not be able to depend on
  782. * the order the entires are specified in iax.conf for matching order. */
  783. #ifdef LOW_MEMORY
  784. #define MAX_PEER_BUCKETS 17
  785. #else
  786. #define MAX_PEER_BUCKETS 563
  787. #endif
  788. static struct ao2_container *peers;
  789. #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
  790. static struct ao2_container *users;
  791. /*! Table containing peercnt objects for every ip address consuming a callno */
  792. static struct ao2_container *peercnts;
  793. /*! Table containing custom callno limit rules for a range of ip addresses. */
  794. static struct ao2_container *callno_limits;
  795. /*! Table containing ip addresses not requiring calltoken validation */
  796. static struct ao2_container *calltoken_ignores;
  797. static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
  798. static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
  799. static uint16_t global_maxcallno;
  800. /*! Total num of call numbers allowed to be allocated without calltoken validation */
  801. static uint16_t global_maxcallno_nonval;
  802. static uint16_t total_nonval_callno_used = 0;
  803. /*! peer connection private, keeps track of all the call numbers
  804. * consumed by a single ip address */
  805. struct peercnt {
  806. /*! ip address consuming call numbers */
  807. unsigned long addr;
  808. /*! Number of call numbers currently used by this ip address */
  809. uint16_t cur;
  810. /*! Max call numbers allowed for this ip address */
  811. uint16_t limit;
  812. /*! Specifies whether limit is set by a registration or not, if so normal
  813. * limit setting rules do not apply to this address. */
  814. unsigned char reg;
  815. };
  816. /*! used by both callno_limits and calltoken_ignores containers */
  817. struct addr_range {
  818. /*! ip address range for custom callno limit rule */
  819. struct ast_ha ha;
  820. /*! callno limit for this ip address range, only used in callno_limits container */
  821. uint16_t limit;
  822. /*! delete me marker for reloads */
  823. unsigned char delme;
  824. };
  825. struct callno_entry {
  826. /*! callno used for this entry */
  827. uint16_t callno;
  828. /*! was this callno calltoken validated or not */
  829. unsigned char validated;
  830. };
  831. static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
  832. enum {
  833. /*! Extension exists */
  834. CACHE_FLAG_EXISTS = (1 << 0),
  835. /*! Extension is nonexistent */
  836. CACHE_FLAG_NONEXISTENT = (1 << 1),
  837. /*! Extension can exist */
  838. CACHE_FLAG_CANEXIST = (1 << 2),
  839. /*! Waiting to hear back response */
  840. CACHE_FLAG_PENDING = (1 << 3),
  841. /*! Timed out */
  842. CACHE_FLAG_TIMEOUT = (1 << 4),
  843. /*! Request transmitted */
  844. CACHE_FLAG_TRANSMITTED = (1 << 5),
  845. /*! Timeout */
  846. CACHE_FLAG_UNKNOWN = (1 << 6),
  847. /*! Matchmore */
  848. CACHE_FLAG_MATCHMORE = (1 << 7),
  849. };
  850. struct iax2_dpcache {
  851. char peercontext[AST_MAX_CONTEXT];
  852. char exten[AST_MAX_EXTENSION];
  853. struct timeval orig;
  854. struct timeval expiry;
  855. int flags;
  856. unsigned short callno;
  857. int waiters[256];
  858. AST_LIST_ENTRY(iax2_dpcache) cache_list;
  859. AST_LIST_ENTRY(iax2_dpcache) peer_list;
  860. };
  861. static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
  862. static void reg_source_db(struct iax2_peer *p);
  863. static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
  864. static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
  865. static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
  866. static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
  867. static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
  868. enum iax2_thread_iostate {
  869. IAX_IOSTATE_IDLE,
  870. IAX_IOSTATE_READY,
  871. IAX_IOSTATE_PROCESSING,
  872. IAX_IOSTATE_SCHEDREADY,
  873. };
  874. enum iax2_thread_type {
  875. IAX_THREAD_TYPE_POOL,
  876. IAX_THREAD_TYPE_DYNAMIC,
  877. };
  878. struct iax2_pkt_buf {
  879. AST_LIST_ENTRY(iax2_pkt_buf) entry;
  880. size_t len;
  881. unsigned char buf[1];
  882. };
  883. struct iax2_thread {
  884. AST_LIST_ENTRY(iax2_thread) list;
  885. enum iax2_thread_type type;
  886. enum iax2_thread_iostate iostate;
  887. #ifdef SCHED_MULTITHREADED
  888. void (*schedfunc)(const void *);
  889. const void *scheddata;
  890. #endif
  891. #ifdef DEBUG_SCHED_MULTITHREAD
  892. char curfunc[80];
  893. #endif
  894. int actions;
  895. pthread_t threadid;
  896. int threadnum;
  897. struct sockaddr_in iosin;
  898. unsigned char readbuf[4096];
  899. unsigned char *buf;
  900. ssize_t buf_len;
  901. size_t buf_size;
  902. int iofd;
  903. time_t checktime;
  904. ast_mutex_t lock;
  905. ast_cond_t cond;
  906. ast_mutex_t init_lock;
  907. ast_cond_t init_cond;
  908. /*! if this thread is processing a full frame,
  909. some information about that frame will be stored
  910. here, so we can avoid dispatching any more full
  911. frames for that callno to other threads */
  912. struct {
  913. unsigned short callno;
  914. struct sockaddr_in sin;
  915. unsigned char type;
  916. unsigned char csub;
  917. } ffinfo;
  918. /*! Queued up full frames for processing. If more full frames arrive for
  919. * a call which this thread is already processing a full frame for, they
  920. * are queued up here. */
  921. AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
  922. unsigned char stop;
  923. };
  924. /* Thread lists */
  925. static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
  926. static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
  927. static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
  928. static void *iax2_process_thread(void *data);
  929. static void iax2_destroy(int callno);
  930. static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
  931. {
  932. ast_mutex_lock(lock);
  933. ast_cond_signal(cond);
  934. ast_mutex_unlock(lock);
  935. }
  936. /*!
  937. * \brief an array of iax2 pvt structures
  938. *
  939. * The container for active chan_iax2_pvt structures is implemented as an
  940. * array for extremely quick direct access to the correct pvt structure
  941. * based on the local call number. The local call number is used as the
  942. * index into the array where the associated pvt structure is stored.
  943. */
  944. static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
  945. static struct ast_callid *iax_pvt_callid_get(int callno)
  946. {
  947. if (iaxs[callno]->callid) {
  948. return ast_callid_ref(iaxs[callno]->callid);
  949. }
  950. return NULL;
  951. }
  952. static void iax_pvt_callid_set(int callno, struct ast_callid *callid)
  953. {
  954. if (iaxs[callno]->callid) {
  955. ast_callid_unref(iaxs[callno]->callid);
  956. }
  957. ast_callid_ref(callid);
  958. iaxs[callno]->callid = callid;
  959. }
  960. static void iax_pvt_callid_new(int callno)
  961. {
  962. struct ast_callid *callid = ast_create_callid();
  963. char buffer[AST_CALLID_BUFFER_LENGTH];
  964. ast_callid_strnprint(buffer, sizeof(buffer), callid);
  965. iax_pvt_callid_set(callno, callid);
  966. ast_callid_unref(callid);
  967. }
  968. /*!
  969. * \brief Another container of iax2_pvt structures
  970. *
  971. * Active IAX2 pvt structs are also stored in this container, if they are a part
  972. * of an active call where we know the remote side's call number. The reason
  973. * for this is that incoming media frames do not contain our call number. So,
  974. * instead of having to iterate the entire iaxs array, we use this container to
  975. * look up calls where the remote side is using a given call number.
  976. */
  977. static struct ao2_container *iax_peercallno_pvts;
  978. /*!
  979. * \brief chan_iax2_pvt structure locks
  980. *
  981. * These locks are used when accessing a pvt structure in the iaxs array.
  982. * The index used here is the same as used in the iaxs array. It is the
  983. * local call number for the associated pvt struct.
  984. */
  985. static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
  986. /*!
  987. * * \brief Another container of iax2_pvt structures
  988. *
  989. * Active IAX2 pvt stucts used during transfering a call are stored here.
  990. */
  991. static struct ao2_container *iax_transfercallno_pvts;
  992. /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
  993. but keeps the division between trunked and non-trunked better. */
  994. #define TRUNK_CALL_START (IAX_MAX_CALLS / 2)
  995. /* Debug routines... */
  996. static struct sockaddr_in debugaddr;
  997. static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
  998. {
  999. if (iaxdebug ||
  1000. (sin && debugaddr.sin_addr.s_addr &&
  1001. (!ntohs(debugaddr.sin_port) ||
  1002. debugaddr.sin_port == sin->sin_port) &&
  1003. debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
  1004. if (iaxdebug) {
  1005. iax_showframe(f, fhi, rx, sin, datalen);
  1006. } else {
  1007. iaxdebug = 1;
  1008. iax_showframe(f, fhi, rx, sin, datalen);
  1009. iaxdebug = 0;
  1010. }
  1011. }
  1012. }
  1013. static void iax_debug_output(const char *data)
  1014. {
  1015. if (iaxdebug)
  1016. ast_verbose("%s", data);
  1017. }
  1018. static void iax_error_output(const char *data)
  1019. {
  1020. ast_log(LOG_WARNING, "%s", data);
  1021. }
  1022. static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
  1023. {
  1024. va_list args;
  1025. char buf[1024];
  1026. va_start(args, fmt);
  1027. vsnprintf(buf, sizeof(buf), fmt, args);
  1028. va_end(args);
  1029. ast_log(LOG_ERROR, "%s", buf);
  1030. }
  1031. static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
  1032. {
  1033. va_list args;
  1034. char buf[1024];
  1035. va_start(args, fmt);
  1036. vsnprintf(buf, sizeof(buf), fmt, args);
  1037. va_end(args);
  1038. ast_log(LOG_WARNING, "%s", buf);
  1039. }
  1040. static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
  1041. {
  1042. va_list args;
  1043. char buf[1024];
  1044. va_start(args, fmt);
  1045. vsnprintf(buf, sizeof(buf), fmt, args);
  1046. va_end(args);
  1047. ast_verbose("%s", buf);
  1048. }
  1049. static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
  1050. static int expire_registry(const void *data);
  1051. static int iax2_answer(struct ast_channel *c);
  1052. static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
  1053. static int iax2_devicestate(const char *data);
  1054. static int iax2_digit_begin(struct ast_channel *c, char digit);
  1055. static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
  1056. static int iax2_do_register(struct iax2_registry *reg);
  1057. static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
  1058. static int iax2_hangup(struct ast_channel *c);
  1059. static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
  1060. static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
  1061. static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
  1062. static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
  1063. static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
  1064. static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
  1065. static int iax2_sendtext(struct ast_channel *c, const char *text);
  1066. static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
  1067. static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
  1068. static int iax2_transfer(struct ast_channel *c, const char *dest);
  1069. static int iax2_write(struct ast_channel *c, struct ast_frame *f);
  1070. static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
  1071. static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
  1072. static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
  1073. static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
  1074. static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
  1075. static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
  1076. static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
  1077. static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
  1078. static struct ast_frame *iax2_read(struct ast_channel *c);
  1079. static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
  1080. static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
  1081. static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
  1082. static void *iax2_dup_variable_datastore(void *);
  1083. static void prune_peers(void);
  1084. static void prune_users(void);
  1085. static void iax2_free_variable_datastore(void *);
  1086. static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
  1087. static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
  1088. static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
  1089. static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
  1090. static void build_rand_pad(unsigned char *buf, ssize_t len);
  1091. static struct callno_entry *get_unused_callno(int trunk, int validated);
  1092. static int replace_callno(const void *obj);
  1093. static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
  1094. static void network_change_event_cb(const struct ast_event *, void *);
  1095. static void acl_change_event_cb(const struct ast_event *, void *);
  1096. static struct ast_channel_tech iax2_tech = {
  1097. .type = "IAX2",
  1098. .description = tdesc,
  1099. .properties = AST_CHAN_TP_WANTSJITTER,
  1100. .requester = iax2_request,
  1101. .devicestate = iax2_devicestate,
  1102. .send_digit_begin = iax2_digit_begin,
  1103. .send_digit_end = iax2_digit_end,
  1104. .send_text = iax2_sendtext,
  1105. .send_image = iax2_sendimage,
  1106. .send_html = iax2_sendhtml,
  1107. .call = iax2_call,
  1108. .hangup = iax2_hangup,
  1109. .answer = iax2_answer,
  1110. .read = iax2_read,
  1111. .write = iax2_write,
  1112. .write_video = iax2_write,
  1113. .indicate = iax2_indicate,
  1114. .setoption = iax2_setoption,
  1115. .queryoption = iax2_queryoption,
  1116. .bridge = iax2_bridge,
  1117. .transfer = iax2_transfer,
  1118. .fixup = iax2_fixup,
  1119. .func_channel_read = acf_channel_read,
  1120. };
  1121. /*!
  1122. * \internal
  1123. * \brief Obtain the owner channel lock if the owner exists.
  1124. *
  1125. * \param callno IAX2 call id.
  1126. *
  1127. * \note Assumes the iaxsl[callno] lock is already obtained.
  1128. *
  1129. * \note
  1130. * IMPORTANT NOTE!!! Any time this function is used, even if
  1131. * iaxs[callno] was valid before calling it, it may no longer be
  1132. * valid after calling it. This function may unlock and lock
  1133. * the mutex associated with this callno, meaning that another
  1134. * thread may grab it and destroy the call.
  1135. *
  1136. * \return Nothing
  1137. */
  1138. static void iax2_lock_owner(int callno)
  1139. {
  1140. for (;;) {
  1141. if (!iaxs[callno] || !iaxs[callno]->owner) {
  1142. /* There is no owner lock to get. */
  1143. break;
  1144. }
  1145. if (!ast_channel_trylock(iaxs[callno]->owner)) {
  1146. /* We got the lock */
  1147. break;
  1148. }
  1149. /* Avoid deadlock by pausing and trying again */
  1150. DEADLOCK_AVOIDANCE(&iaxsl[callno]);
  1151. }
  1152. }
  1153. /*!
  1154. * \internal
  1155. * \brief Check if a control subtype is allowed on the wire.
  1156. *
  1157. * \param subtype Control frame subtype to check if allowed to/from the wire.
  1158. *
  1159. * \retval non-zero if allowed.
  1160. */
  1161. static int iax2_is_control_frame_allowed(int subtype)
  1162. {
  1163. enum ast_control_frame_type control = subtype;
  1164. int is_allowed;
  1165. /*
  1166. * Note: If we compare the enumeration type, which does not have any
  1167. * negative constants, the compiler may optimize this code away.
  1168. * Therefore, we must perform an integer comparison here.
  1169. */
  1170. if (subtype == -1) {
  1171. return -1;
  1172. }
  1173. /* Default to not allowing control frames to pass. */
  1174. is_allowed = 0;
  1175. /*
  1176. * The switch default is not present in order to take advantage
  1177. * of the compiler complaining of a missing enum case.
  1178. */
  1179. switch (control) {
  1180. /*
  1181. * These control frames make sense to send/receive across the link.
  1182. */
  1183. case AST_CONTROL_HANGUP:
  1184. case AST_CONTROL_RING:
  1185. case AST_CONTROL_RINGING:
  1186. case AST_CONTROL_ANSWER:
  1187. case AST_CONTROL_BUSY:
  1188. case AST_CONTROL_TAKEOFFHOOK:
  1189. case AST_CONTROL_OFFHOOK:
  1190. case AST_CONTROL_CONGESTION:
  1191. case AST_CONTROL_FLASH:
  1192. case AST_CONTROL_WINK:
  1193. case AST_CONTROL_OPTION:
  1194. case AST_CONTROL_RADIO_KEY:
  1195. case AST_CONTROL_RADIO_UNKEY:
  1196. case AST_CONTROL_PROGRESS:
  1197. case AST_CONTROL_PROCEEDING:
  1198. case AST_CONTROL_HOLD:
  1199. case AST_CONTROL_UNHOLD:
  1200. case AST_CONTROL_VIDUPDATE:
  1201. case AST_CONTROL_CONNECTED_LINE:
  1202. case AST_CONTROL_REDIRECTING:
  1203. case AST_CONTROL_T38_PARAMETERS:
  1204. case AST_CONTROL_AOC:
  1205. case AST_CONTROL_INCOMPLETE:
  1206. case AST_CONTROL_MCID:
  1207. is_allowed = -1;
  1208. break;
  1209. /*
  1210. * These control frames do not make sense to send/receive across the link.
  1211. */
  1212. case _XXX_AST_CONTROL_T38:
  1213. /* The control value is deprecated in favor of AST_CONTROL_T38_PARAMETERS. */
  1214. case AST_CONTROL_SRCUPDATE:
  1215. /* Across an IAX link the source is still the same. */
  1216. case AST_CONTROL_TRANSFER:
  1217. /* A success/fail status report from calling ast_transfer() on this machine. */
  1218. case AST_CONTROL_CC:
  1219. /* The payload contains pointers that are valid for the sending machine only. */
  1220. case AST_CONTROL_SRCCHANGE:
  1221. /* Across an IAX link the source is still the same. */
  1222. case AST_CONTROL_READ_ACTION:
  1223. /* The action can only be done by the sending machine. */
  1224. case AST_CONTROL_END_OF_Q:
  1225. /* This frame would cause the call to unexpectedly hangup. */
  1226. case AST_CONTROL_UPDATE_RTP_PEER:
  1227. /* Only meaningful across a bridge on this machine for direct-media exchange. */
  1228. case AST_CONTROL_PVT_CAUSE_CODE:
  1229. /* Intended only for the sending machine's local channel structure. */
  1230. break;
  1231. }
  1232. return is_allowed;
  1233. }
  1234. static void mwi_event_cb(const struct ast_event *event, void *userdata)
  1235. {
  1236. /* The MWI subscriptions exist just so the core knows we care about those
  1237. * mailboxes. However, we just grab the events out of the cache when it
  1238. * is time to send MWI, since it is only sent with a REGACK. */
  1239. }
  1240. static void network_change_event_subscribe(void)
  1241. {
  1242. if (!network_change_event_subscription) {
  1243. network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
  1244. network_change_event_cb, "IAX2 Network Change", NULL, AST_EVENT_IE_END);
  1245. }
  1246. }
  1247. static void network_change_event_unsubscribe(void)
  1248. {
  1249. if (network_change_event_subscription) {
  1250. network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
  1251. }
  1252. }
  1253. static void acl_change_event_subscribe(void)
  1254. {
  1255. if (!acl_change_event_subscription) {
  1256. acl_change_event_subscription = ast_event_subscribe(AST_EVENT_ACL_CHANGE,
  1257. acl_change_event_cb, "IAX2 ACL Change", NULL, AST_EVENT_IE_END);
  1258. }
  1259. }
  1260. static void acl_change_event_unsubscribe(void)
  1261. {
  1262. if (acl_change_event_subscription) {
  1263. acl_change_event_subscription = ast_event_unsubscribe(acl_change_event_subscription);
  1264. }
  1265. }
  1266. static int network_change_event_sched_cb(const void *data)
  1267. {
  1268. struct iax2_registry *reg;
  1269. network_change_event_sched_id = -1;
  1270. AST_LIST_LOCK(&registrations);
  1271. AST_LIST_TRAVERSE(&registrations, reg, entry) {
  1272. iax2_do_register(reg);
  1273. }
  1274. AST_LIST_UNLOCK(&registrations);
  1275. return 0;
  1276. }
  1277. static void network_change_event_cb(const struct ast_event *event, void *userdata)
  1278. {
  1279. ast_debug(1, "IAX, got a network change event, renewing all IAX registrations.\n");
  1280. if (network_change_event_sched_id == -1) {
  1281. network_change_event_sched_id = iax2_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
  1282. }
  1283. }
  1284. static void acl_change_event_cb(const struct ast_event *event, void *userdata)
  1285. {
  1286. ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
  1287. reload_config(1);
  1288. }
  1289. /*! \brief Send manager event at call setup to link between Asterisk channel name
  1290. and IAX2 call identifiers */
  1291. static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
  1292. {
  1293. manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
  1294. "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
  1295. pvt->owner ? ast_channel_name(pvt->owner) : "",
  1296. pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
  1297. }
  1298. static const struct ast_datastore_info iax2_variable_datastore_info = {
  1299. .type = "IAX2_VARIABLE",
  1300. .duplicate = iax2_dup_variable_datastore,
  1301. .destroy = iax2_free_variable_datastore,
  1302. };
  1303. static void *iax2_dup_variable_datastore(void *old)
  1304. {
  1305. AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
  1306. struct ast_var_t *oldvar, *newvar;
  1307. newlist = ast_calloc(sizeof(*newlist), 1);
  1308. if (!newlist) {
  1309. ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
  1310. return NULL;
  1311. }
  1312. AST_LIST_HEAD_INIT(newlist);
  1313. AST_LIST_LOCK(oldlist);
  1314. AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
  1315. newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
  1316. if (newvar)
  1317. AST_LIST_INSERT_TAIL(newlist, newvar, entries);
  1318. else
  1319. ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
  1320. }
  1321. AST_LIST_UNLOCK(oldlist);
  1322. return newlist;
  1323. }
  1324. static void iax2_free_variable_datastore(void *old)
  1325. {
  1326. AST_LIST_HEAD(, ast_var_t) *oldlist = old;
  1327. struct ast_var_t *oldvar;
  1328. AST_LIST_LOCK(oldlist);
  1329. while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
  1330. ast_free(oldvar);
  1331. }
  1332. AST_LIST_UNLOCK(oldlist);
  1333. AST_LIST_HEAD_DESTROY(oldlist);
  1334. ast_free(oldlist);
  1335. }
  1336. /* WARNING: insert_idle_thread should only ever be called within the
  1337. * context of an iax2_process_thread() thread.
  1338. */
  1339. static void insert_idle_thread(struct iax2_thread *thread)
  1340. {
  1341. if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
  1342. AST_LIST_LOCK(&dynamic_list);
  1343. AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
  1344. AST_LIST_UNLOCK(&dynamic_list);
  1345. } else {
  1346. AST_LIST_LOCK(&idle_list);
  1347. AST_LIST_INSERT_TAIL(&idle_list, thread, list);
  1348. AST_LIST_UNLOCK(&idle_list);
  1349. }
  1350. return;
  1351. }
  1352. static struct iax2_thread *find_idle_thread(void)
  1353. {
  1354. struct iax2_thread *thread = NULL;
  1355. /* Pop the head of the idle list off */
  1356. AST_LIST_LOCK(&idle_list);
  1357. thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
  1358. AST_LIST_UNLOCK(&idle_list);
  1359. /* If we popped a thread off the idle list, just return it */
  1360. if (thread) {
  1361. memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
  1362. return thread;
  1363. }
  1364. /* Pop the head of the dynamic list off */
  1365. AST_LIST_LOCK(&dynamic_list);
  1366. thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
  1367. AST_LIST_UNLOCK(&dynamic_list);
  1368. /* If we popped a thread off the dynamic list, just return it */
  1369. if (thread) {
  1370. memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
  1371. return thread;
  1372. }
  1373. /* If we can't create a new dynamic thread for any reason, return no thread at all */
  1374. if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
  1375. return NULL;
  1376. /* Set default values */
  1377. ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
  1378. thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
  1379. thread->type = IAX_THREAD_TYPE_DYNAMIC;
  1380. /* Initialize lock and condition */
  1381. ast_mutex_init(&thread->lock);
  1382. ast_cond_init(&thread->cond, NULL);
  1383. ast_mutex_init(&thread->init_lock);
  1384. ast_cond_init(&thread->init_cond, NULL);
  1385. ast_mutex_lock(&thread->init_lock);
  1386. /* Create thread and send it on it's way */
  1387. if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
  1388. ast_cond_destroy(&thread->cond);
  1389. ast_mutex_destroy(&thread->lock);
  1390. ast_mutex_unlock(&thread->init_lock);
  1391. ast_cond_destroy(&thread->init_cond);
  1392. ast_mutex_destroy(&thread->init_lock);
  1393. ast_free(thread);
  1394. return NULL;
  1395. }
  1396. /* this thread is not processing a full frame (since it is idle),
  1397. so ensure that the field for the full frame call number is empty */
  1398. memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
  1399. /* Wait for the thread to be ready before returning it to the caller */
  1400. ast_cond_wait(&thread->init_cond, &thread->init_lock);
  1401. /* Done with init_lock */
  1402. ast_mutex_unlock(&thread->init_lock);
  1403. return thread;
  1404. }
  1405. #ifdef SCHED_MULTITHREADED
  1406. static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
  1407. {
  1408. struct iax2_thread *thread;
  1409. static time_t lasterror;
  1410. time_t t;
  1411. thread = find_idle_thread();
  1412. if (thread != NULL) {
  1413. thread->schedfunc = func;
  1414. thread->scheddata = data;
  1415. thread->iostate = IAX_IOSTATE_SCHEDREADY;
  1416. #ifdef DEBUG_SCHED_MULTITHREAD
  1417. ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
  1418. #endif
  1419. signal_condition(&thread->lock, &thread->cond);
  1420. return 0;
  1421. }
  1422. time(&t);
  1423. if (t != lasterror) {
  1424. lasterror = t;
  1425. ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
  1426. }
  1427. return -1;
  1428. }
  1429. #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
  1430. #endif
  1431. static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
  1432. ast_sched_cb callback, const void *data)
  1433. {
  1434. return ast_sched_replace(id, con, when, callback, data);
  1435. }
  1436. static int iax2_sched_add(struct ast_sched_context *con, int when,
  1437. ast_sched_cb callback, const void *data)
  1438. {
  1439. return ast_sched_add(con, when, callback, data);
  1440. }
  1441. static int send_ping(const void *data);
  1442. static void __send_ping(const void *data)
  1443. {
  1444. int callno = (long) data;
  1445. ast_mutex_lock(&iaxsl[callno]);
  1446. if (iaxs[callno]) {
  1447. if (iaxs[callno]->peercallno) {
  1448. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
  1449. if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
  1450. iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
  1451. }
  1452. }
  1453. } else {
  1454. ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
  1455. }
  1456. ast_mutex_unlock(&iaxsl[callno]);
  1457. }
  1458. static int send_ping(const void *data)
  1459. {
  1460. int callno = (long) data;
  1461. ast_mutex_lock(&iaxsl[callno]);
  1462. if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
  1463. iaxs[callno]->pingid = -1;
  1464. }
  1465. ast_mutex_unlock(&iaxsl[callno]);
  1466. #ifdef SCHED_MULTITHREADED
  1467. if (schedule_action(__send_ping, data))
  1468. #endif
  1469. __send_ping(data);
  1470. return 0;
  1471. }
  1472. static void encmethods_to_str(int e, struct ast_str **buf)
  1473. {
  1474. ast_str_set(buf, 0, "(");
  1475. if (e & IAX_ENCRYPT_AES128) {
  1476. ast_str_append(buf, 0, "aes128");
  1477. }
  1478. if (e & IAX_ENCRYPT_KEYROTATE) {
  1479. ast_str_append(buf, 0, ",keyrotate");
  1480. }
  1481. if (ast_str_strlen(*buf) > 1) {
  1482. ast_str_append(buf, 0, ")");
  1483. } else {
  1484. ast_str_set(buf, 0, "No");
  1485. }
  1486. }
  1487. static int get_encrypt_methods(const char *s)
  1488. {
  1489. int e;
  1490. if (!strcasecmp(s, "aes128"))
  1491. e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
  1492. else if (ast_true(s))
  1493. e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
  1494. else
  1495. e = 0;
  1496. return e;
  1497. }
  1498. static int send_lagrq(const void *data);
  1499. static void __send_lagrq(const void *data)
  1500. {
  1501. int callno = (long) data;
  1502. ast_mutex_lock(&iaxsl[callno]);
  1503. if (iaxs[callno]) {
  1504. if (iaxs[callno]->peercallno) {
  1505. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
  1506. if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
  1507. iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
  1508. }
  1509. }
  1510. } else {
  1511. ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
  1512. }
  1513. ast_mutex_unlock(&iaxsl[callno]);
  1514. }
  1515. static int send_lagrq(const void *data)
  1516. {
  1517. int callno = (long) data;
  1518. ast_mutex_lock(&iaxsl[callno]);
  1519. if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
  1520. iaxs[callno]->lagid = -1;
  1521. }
  1522. ast_mutex_unlock(&iaxsl[callno]);
  1523. #ifdef SCHED_MULTITHREADED
  1524. if (schedule_action(__send_lagrq, data))
  1525. #endif
  1526. __send_lagrq(data);
  1527. return 0;
  1528. }
  1529. static unsigned char compress_subclass(iax2_format subclass)
  1530. {
  1531. int x;
  1532. int power=-1;
  1533. /* If it's 64 or smaller, just return it */
  1534. if (subclass < IAX_FLAG_SC_LOG)
  1535. return subclass;
  1536. /* Otherwise find its power */
  1537. for (x = 0; x < IAX_MAX_SHIFT; x++) {
  1538. if (subclass & (1LL << x)) {
  1539. if (power > -1) {
  1540. ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
  1541. return 0;
  1542. } else
  1543. power = x;
  1544. }
  1545. }
  1546. return power | IAX_FLAG_SC_LOG;
  1547. }
  1548. static iax2_format uncompress_subclass(unsigned char csub)
  1549. {
  1550. /* If the SC_LOG flag is set, return 2^csub otherwise csub */
  1551. if (csub & IAX_FLAG_SC_LOG) {
  1552. /* special case for 'compressed' -1 */
  1553. if (csub == 0xff)
  1554. return -1;
  1555. else
  1556. return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
  1557. }
  1558. else
  1559. return csub;
  1560. }
  1561. static iax2_format iax2_codec_choose(struct ast_codec_pref *pref, iax2_format formats, int find_best)
  1562. {
  1563. struct ast_format_cap *cap;
  1564. struct ast_format tmpfmt;
  1565. iax2_format format = 0;
  1566. if ((cap = ast_format_cap_alloc_nolock())) {
  1567. ast_format_clear(&tmpfmt);
  1568. ast_format_cap_from_old_bitfield(cap, formats);
  1569. ast_codec_choose(pref, cap, find_best, &tmpfmt);
  1570. format = ast_format_to_old_bitfield(&tmpfmt);
  1571. cap = ast_format_cap_destroy(cap);
  1572. }
  1573. return format;
  1574. }
  1575. static iax2_format iax2_best_codec(iax2_format formats)
  1576. {
  1577. struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
  1578. struct ast_format tmpfmt;
  1579. if (!cap) {
  1580. return 0;
  1581. }
  1582. ast_format_clear(&tmpfmt);
  1583. ast_format_cap_from_old_bitfield(cap, formats);
  1584. ast_best_codec(cap, &tmpfmt);
  1585. cap = ast_format_cap_destroy(cap);
  1586. return ast_format_to_old_bitfield(&tmpfmt);
  1587. }
  1588. const char *iax2_getformatname(iax2_format format)
  1589. {
  1590. struct ast_format tmpfmt;
  1591. if (!(ast_format_from_old_bitfield(&tmpfmt, format))) {
  1592. return "Unknown";
  1593. }
  1594. return ast_getformatname(&tmpfmt);
  1595. }
  1596. static char *iax2_getformatname_multiple(char *codec_buf, size_t len, iax2_format format)
  1597. {
  1598. struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
  1599. if (!cap) {
  1600. return "(Nothing)";
  1601. }
  1602. ast_format_cap_from_old_bitfield(cap, format);
  1603. ast_getformatname_multiple(codec_buf, len, cap);
  1604. cap = ast_format_cap_destroy(cap);
  1605. return codec_buf;
  1606. }
  1607. static int iax2_parse_allow_disallow(struct ast_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
  1608. {
  1609. int res;
  1610. struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
  1611. if (!cap) {
  1612. return 1;
  1613. }
  1614. ast_format_cap_from_old_bitfield(cap, *formats);
  1615. res = ast_parse_allow_disallow(pref, cap, list, allowing);
  1616. *formats = ast_format_cap_to_old_bitfield(cap);
  1617. cap = ast_format_cap_destroy(cap);
  1618. return res;
  1619. }
  1620. static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
  1621. {
  1622. int res;
  1623. struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
  1624. if (!cap) {
  1625. return -1;
  1626. }
  1627. ast_format_cap_from_old_bitfield(cap, formats);
  1628. res = ast_data_add_codecs(root, node_name, cap);
  1629. cap = ast_format_cap_destroy(cap);
  1630. return res;
  1631. }
  1632. /*!
  1633. * \note The only member of the peer passed here guaranteed to be set is the name field
  1634. */
  1635. static int peer_hash_cb(const void *obj, const int flags)
  1636. {
  1637. const struct iax2_peer *peer = obj;
  1638. const char *name = obj;
  1639. return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
  1640. }
  1641. /*!
  1642. * \note The only member of the peer passed here guaranteed to be set is the name field
  1643. */
  1644. static int peer_cmp_cb(void *obj, void *arg, int flags)
  1645. {
  1646. struct iax2_peer *peer = obj, *peer2 = arg;
  1647. const char *name = arg;
  1648. return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
  1649. CMP_MATCH | CMP_STOP : 0;
  1650. }
  1651. /*!
  1652. * \note The only member of the user passed here guaranteed to be set is the name field
  1653. */
  1654. static int user_hash_cb(const void *obj, const int flags)
  1655. {
  1656. const struct iax2_user *user = obj;
  1657. const char *name = obj;
  1658. return ast_str_hash(flags & OBJ_KEY ? name : user->name);
  1659. }
  1660. /*!
  1661. * \note The only member of the user passed here guaranteed to be set is the name field
  1662. */
  1663. static int user_cmp_cb(void *obj, void *arg, int flags)
  1664. {
  1665. struct iax2_user *user = obj, *user2 = arg;
  1666. const char *name = arg;
  1667. return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
  1668. CMP_MATCH | CMP_STOP : 0;
  1669. }
  1670. /*!
  1671. * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
  1672. * so do not call it with a pvt lock held.
  1673. */
  1674. static struct iax2_peer *find_peer(const char *name, int realtime)
  1675. {
  1676. struct iax2_peer *peer = NULL;
  1677. peer = ao2_find(peers, name, OBJ_KEY);
  1678. /* Now go for realtime if applicable */
  1679. if(!peer && realtime)
  1680. peer = realtime_peer(name, NULL);
  1681. return peer;
  1682. }
  1683. static struct iax2_peer *peer_ref(struct iax2_peer *peer)
  1684. {
  1685. ao2_ref(peer, +1);
  1686. return peer;
  1687. }
  1688. static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
  1689. {
  1690. ao2_ref(peer, -1);
  1691. return NULL;
  1692. }
  1693. static struct iax2_user *find_user(const char *name)
  1694. {
  1695. return ao2_find(users, name, OBJ_KEY);
  1696. }
  1697. static inline struct iax2_user *user_unref(struct iax2_user *user)
  1698. {
  1699. ao2_ref(user, -1);
  1700. return NULL;
  1701. }
  1702. static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
  1703. {
  1704. struct iax2_peer *peer = NULL;
  1705. int res = 0;
  1706. struct ao2_iterator i;
  1707. i = ao2_iterator_init(peers, 0);
  1708. while ((peer = ao2_iterator_next(&i))) {
  1709. struct sockaddr_in peer_addr;
  1710. ast_sockaddr_to_sin(&peer->addr, &peer_addr);
  1711. if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
  1712. (peer_addr.sin_port == sin.sin_port)) {
  1713. ast_copy_string(host, peer->name, len);
  1714. peer_unref(peer);
  1715. res = 1;
  1716. break;
  1717. }
  1718. peer_unref(peer);
  1719. }
  1720. ao2_iterator_destroy(&i);
  1721. if (!peer) {
  1722. peer = realtime_peer(NULL, &sin);
  1723. if (peer) {
  1724. ast_copy_string(host, peer->name, len);
  1725. peer_unref(peer);
  1726. res = 1;
  1727. }
  1728. }
  1729. return res;
  1730. }
  1731. /*!\note Assumes the lock on the pvt is already held, when
  1732. * iax2_destroy_helper() is called. */
  1733. static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
  1734. {
  1735. /* Decrement AUTHREQ count if needed */
  1736. if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
  1737. struct iax2_user *user;
  1738. user = ao2_find(users, pvt->username, OBJ_KEY);
  1739. if (user) {
  1740. ast_atomic_fetchadd_int(&user->curauthreq, -1);
  1741. user_unref(user);
  1742. }
  1743. ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
  1744. }
  1745. /* No more pings or lagrq's */
  1746. AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
  1747. pvt->pingid = DONT_RESCHEDULE;
  1748. AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
  1749. pvt->lagid = DONT_RESCHEDULE;
  1750. AST_SCHED_DEL(sched, pvt->autoid);
  1751. AST_SCHED_DEL(sched, pvt->authid);
  1752. AST_SCHED_DEL(sched, pvt->initid);
  1753. AST_SCHED_DEL(sched, pvt->jbid);
  1754. AST_SCHED_DEL(sched, pvt->keyrotateid);
  1755. }
  1756. static void iax2_frame_free(struct iax_frame *fr)
  1757. {
  1758. AST_SCHED_DEL(sched, fr->retrans);
  1759. iax_frame_free(fr);
  1760. }
  1761. static int scheduled_destroy(const void *vid)
  1762. {
  1763. unsigned short callno = PTR_TO_CALLNO(vid);
  1764. ast_mutex_lock(&iaxsl[callno]);
  1765. if (iaxs[callno]) {
  1766. ast_debug(1, "Really destroying %d now...\n", callno);
  1767. iax2_destroy(callno);
  1768. }
  1769. ast_mutex_unlock(&iaxsl[callno]);
  1770. return 0;
  1771. }
  1772. static void free_signaling_queue_entry(struct signaling_queue_entry *s)
  1773. {
  1774. if (s->f.datalen) {
  1775. ast_free(s->f.data.ptr);
  1776. }
  1777. ast_free(s);
  1778. }
  1779. /*! \brief This function must be called once we are sure the other side has
  1780. * given us a call number. All signaling is held here until that point. */
  1781. static void send_signaling(struct chan_iax2_pvt *pvt)
  1782. {
  1783. struct signaling_queue_entry *s = NULL;
  1784. while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
  1785. iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
  1786. free_signaling_queue_entry(s);
  1787. }
  1788. pvt->hold_signaling = 0;
  1789. }
  1790. /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
  1791. * we have received a destination call number. */
  1792. static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
  1793. {
  1794. struct signaling_queue_entry *qe;
  1795. if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
  1796. return 1; /* do not queue this frame */
  1797. } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
  1798. return -1; /* out of memory */
  1799. }
  1800. /* copy ast_frame into our queue entry */
  1801. qe->f = *f;
  1802. if (qe->f.datalen) {
  1803. /* if there is data in this frame copy it over as well */
  1804. if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
  1805. free_signaling_queue_entry(qe);
  1806. return -1;
  1807. }
  1808. memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
  1809. }
  1810. AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
  1811. return 0;
  1812. }
  1813. static void pvt_destructor(void *obj)
  1814. {
  1815. struct chan_iax2_pvt *pvt = obj;
  1816. struct iax_frame *cur = NULL;
  1817. struct signaling_queue_entry *s = NULL;
  1818. ast_mutex_lock(&iaxsl[pvt->callno]);
  1819. iax2_destroy_helper(pvt);
  1820. sched_delay_remove(&pvt->addr, pvt->callno_entry);
  1821. pvt->callno_entry = NULL;
  1822. /* Already gone */
  1823. ast_set_flag64(pvt, IAX_ALREADYGONE);
  1824. AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
  1825. /* Cancel any pending transmissions */
  1826. cur->retries = -1;
  1827. }
  1828. ast_mutex_unlock(&iaxsl[pvt->callno]);
  1829. while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
  1830. free_signaling_queue_entry(s);
  1831. }
  1832. if (pvt->reg) {
  1833. pvt->reg->callno = 0;
  1834. }
  1835. if (!pvt->owner) {
  1836. jb_frame frame;
  1837. if (pvt->vars) {
  1838. ast_variables_destroy(pvt->vars);
  1839. pvt->vars = NULL;
  1840. }
  1841. while (jb_getall(pvt->jb, &frame) == JB_OK) {
  1842. iax2_frame_free(frame.data);
  1843. }
  1844. jb_destroy(pvt->jb);
  1845. ast_string_field_free_memory(pvt);
  1846. }
  1847. if (pvt->callid) {
  1848. ast_callid_unref(pvt->callid);
  1849. }
  1850. }
  1851. static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
  1852. {
  1853. struct chan_iax2_pvt *tmp;
  1854. jb_conf jbconf;
  1855. if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
  1856. return NULL;
  1857. }
  1858. if (ast_string_field_init(tmp, 32)) {
  1859. ao2_ref(tmp, -1);
  1860. tmp = NULL;
  1861. return NULL;
  1862. }
  1863. tmp->prefs = prefs;
  1864. tmp->pingid = -1;
  1865. tmp->lagid = -1;
  1866. tmp->autoid = -1;
  1867. tmp->authid = -1;
  1868. tmp->initid = -1;
  1869. tmp->keyrotateid = -1;
  1870. ast_string_field_set(tmp,exten, "s");
  1871. ast_string_field_set(tmp,host, host);
  1872. tmp->jb = jb_new();
  1873. tmp->jbid = -1;
  1874. jbconf.max_jitterbuf = maxjitterbuffer;
  1875. jbconf.resync_threshold = resyncthreshold;
  1876. jbconf.max_contig_interp = maxjitterinterps;
  1877. jbconf.target_extra = jittertargetextra;
  1878. jb_setconf(tmp->jb,&jbconf);
  1879. AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
  1880. tmp->hold_signaling = 1;
  1881. AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
  1882. return tmp;
  1883. }
  1884. static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
  1885. {
  1886. struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
  1887. if (new) {
  1888. size_t afdatalen = new->afdatalen;
  1889. memcpy(new, fr, sizeof(*new));
  1890. iax_frame_wrap(new, &fr->af);
  1891. new->afdatalen = afdatalen;
  1892. new->data = NULL;
  1893. new->datalen = 0;
  1894. new->direction = DIRECTION_INGRESS;
  1895. new->retrans = -1;
  1896. }
  1897. return new;
  1898. }
  1899. /* keep these defined in this order. They are used in find_callno to
  1900. * determine whether or not a new call number should be allowed. */
  1901. enum {
  1902. /* do not allow a new call number, only search ones in use for match */
  1903. NEW_PREVENT = 0,
  1904. /* search for match first, then allow a new one to be allocated */
  1905. NEW_ALLOW = 1,
  1906. /* do not search for match, force a new call number */
  1907. NEW_FORCE = 2,
  1908. /* do not search for match, force a new call number. Signifies call number
  1909. * has been calltoken validated */
  1910. NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
  1911. };
  1912. static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
  1913. {
  1914. if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
  1915. (cur->addr.sin_port == sin->sin_port)) {
  1916. /* This is the main host */
  1917. if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
  1918. (check_dcallno ? dcallno == cur->callno : 1) ) {
  1919. /* That's us. Be sure we keep track of the peer call number */
  1920. return 1;
  1921. }
  1922. }
  1923. if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
  1924. (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
  1925. /* We're transferring */
  1926. if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
  1927. return 1;
  1928. }
  1929. return 0;
  1930. }
  1931. static int make_trunk(unsigned short callno, int locked)
  1932. {
  1933. int x;
  1934. int res= 0;
  1935. struct callno_entry *callno_entry;
  1936. if (iaxs[callno]->oseqno) {
  1937. ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
  1938. return -1;
  1939. }
  1940. if (callno >= TRUNK_CALL_START) {
  1941. ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
  1942. return -1;
  1943. }
  1944. if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
  1945. ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
  1946. return -1;
  1947. }
  1948. x = callno_entry->callno;
  1949. ast_mutex_lock(&iaxsl[x]);
  1950. /*!
  1951. * \note We delete these before switching the slot, because if
  1952. * they fire in the meantime, they will generate a warning.
  1953. */
  1954. AST_SCHED_DEL(sched, iaxs[callno]->pingid);
  1955. AST_SCHED_DEL(sched, iaxs[callno]->lagid);
  1956. iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
  1957. iaxs[x] = iaxs[callno];
  1958. iaxs[x]->callno = x;
  1959. /* since we copied over the pvt from a different callno, make sure the old entry is replaced
  1960. * before assigning the new one */
  1961. if (iaxs[x]->callno_entry) {
  1962. iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
  1963. }
  1964. iaxs[x]->callno_entry = callno_entry;
  1965. iaxs[callno] = NULL;
  1966. /* Update the two timers that should have been started */
  1967. iaxs[x]->pingid = iax2_sched_add(sched,
  1968. ping_time * 1000, send_ping, (void *)(long)x);
  1969. iaxs[x]->lagid = iax2_sched_add(sched,
  1970. lagrq_time * 1000, send_lagrq, (void *)(long)x);
  1971. if (locked)
  1972. ast_mutex_unlock(&iaxsl[callno]);
  1973. res = x;
  1974. if (!locked)
  1975. ast_mutex_unlock(&iaxsl[x]);
  1976. /* We moved this call from a non-trunked to a trunked call */
  1977. ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
  1978. return res;
  1979. }
  1980. static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
  1981. {
  1982. if (!pvt->transfercallno) {
  1983. ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
  1984. return;
  1985. }
  1986. ao2_link(iax_transfercallno_pvts, pvt);
  1987. }
  1988. static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
  1989. {
  1990. if (!pvt->transfercallno) {
  1991. ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
  1992. return;
  1993. }
  1994. ao2_unlink(iax_transfercallno_pvts, pvt);
  1995. }
  1996. static void store_by_peercallno(struct chan_iax2_pvt *pvt)
  1997. {
  1998. if (!pvt->peercallno) {
  1999. ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
  2000. return;
  2001. }
  2002. ao2_link(iax_peercallno_pvts, pvt);
  2003. }
  2004. static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
  2005. {
  2006. if (!pvt->peercallno) {
  2007. ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
  2008. return;
  2009. }
  2010. ao2_unlink(iax_peercallno_pvts, pvt);
  2011. }
  2012. static int addr_range_delme_cb(void *obj, void *arg, int flags)
  2013. {
  2014. struct addr_range *lim = obj;
  2015. lim->delme = 1;
  2016. return 0;
  2017. }
  2018. static int addr_range_hash_cb(const void *obj, const int flags)
  2019. {
  2020. const struct addr_range *lim = obj;
  2021. struct sockaddr_in sin;
  2022. ast_sockaddr_to_sin(&lim->ha.addr, &sin);
  2023. return abs((int) sin.sin_addr.s_addr);
  2024. }
  2025. static int addr_range_cmp_cb(void *obj, void *arg, int flags)
  2026. {
  2027. struct addr_range *lim1 = obj, *lim2 = arg;
  2028. return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
  2029. !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
  2030. CMP_MATCH | CMP_STOP : 0;
  2031. }
  2032. static int peercnt_hash_cb(const void *obj, const int flags)
  2033. {
  2034. const struct peercnt *peercnt = obj;
  2035. return abs((int) peercnt->addr);
  2036. }
  2037. static int peercnt_cmp_cb(void *obj, void *arg, int flags)
  2038. {
  2039. struct peercnt *peercnt1 = obj, *peercnt2 = arg;
  2040. return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
  2041. }
  2042. static int addr_range_match_address_cb(void *obj, void *arg, int flags)
  2043. {
  2044. struct addr_range *addr_range = obj;
  2045. struct sockaddr_in *sin = arg;
  2046. struct sockaddr_in ha_netmask_sin;
  2047. struct sockaddr_in ha_addr_sin;
  2048. ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
  2049. ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
  2050. if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
  2051. return CMP_MATCH | CMP_STOP;
  2052. }
  2053. return 0;
  2054. }
  2055. /*!
  2056. * \internal
  2057. *
  2058. * \brief compares sin to calltoken_ignores table to determine if validation is required.
  2059. */
  2060. static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
  2061. {
  2062. struct addr_range *addr_range;
  2063. struct iax2_peer *peer = NULL;
  2064. struct iax2_user *user = NULL;
  2065. /* if no username is given, check for guest accounts */
  2066. const char *find = S_OR(name, "guest");
  2067. int res = 1; /* required by default */
  2068. int optional = 0;
  2069. enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
  2070. /* There are only two cases in which calltoken validation is not required.
  2071. * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
  2072. * the peer definition has not set the requirecalltoken option.
  2073. * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
  2074. */
  2075. /* ----- Case 1 ----- */
  2076. if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
  2077. ao2_ref(addr_range, -1);
  2078. optional = 1;
  2079. }
  2080. /* ----- Case 2 ----- */
  2081. if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
  2082. calltoken_required = user->calltoken_required;
  2083. } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
  2084. calltoken_required = user->calltoken_required;
  2085. } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
  2086. calltoken_required = peer->calltoken_required;
  2087. } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
  2088. calltoken_required = peer->calltoken_required;
  2089. }
  2090. if (peer) {
  2091. peer_unref(peer);
  2092. }
  2093. if (user) {
  2094. user_unref(user);
  2095. }
  2096. ast_debug(1, "Determining if address %s with username %s requires calltoken validation. Optional = %d calltoken_required = %u\n", ast_inet_ntoa(sin->sin_addr), name, optional, calltoken_required);
  2097. if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
  2098. (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
  2099. res = 0;
  2100. }
  2101. return res;
  2102. }
  2103. /*!
  2104. * \internal
  2105. *
  2106. * \brief set peercnt callno limit.
  2107. *
  2108. * \details
  2109. * First looks in custom definitions. If not found, global limit
  2110. * is used. Entries marked as reg already have
  2111. * a custom limit set by a registration and are not modified.
  2112. */
  2113. static void set_peercnt_limit(struct peercnt *peercnt)
  2114. {
  2115. uint16_t limit = global_maxcallno;
  2116. struct addr_range *addr_range;
  2117. struct sockaddr_in sin = {
  2118. .sin_addr.s_addr = peercnt->addr,
  2119. };
  2120. if (peercnt->reg && peercnt->limit) {
  2121. return; /* this peercnt has a custom limit set by a registration */
  2122. }
  2123. if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
  2124. limit = addr_range->limit;
  2125. ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
  2126. ao2_ref(addr_range, -1);
  2127. }
  2128. peercnt->limit = limit;
  2129. }
  2130. /*!
  2131. * \internal
  2132. * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
  2133. */
  2134. static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
  2135. {
  2136. struct peercnt *peercnt = obj;
  2137. set_peercnt_limit(peercnt);
  2138. ast_debug(1, "Reset limits for peercnts table\n");
  2139. return 0;
  2140. }
  2141. /*!
  2142. * \internal
  2143. * \brief returns match if delme is set.
  2144. */
  2145. static int prune_addr_range_cb(void *obj, void *arg, int flags)
  2146. {
  2147. struct addr_range *addr_range = obj;
  2148. return addr_range->delme ? CMP_MATCH : 0;
  2149. }
  2150. /*!
  2151. * \internal
  2152. * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
  2153. */
  2154. static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
  2155. {
  2156. /* this function turns off and on custom callno limits set by peer registration */
  2157. struct peercnt *peercnt;
  2158. struct peercnt tmp = {
  2159. .addr = 0,
  2160. };
  2161. struct sockaddr_in sin;
  2162. ast_sockaddr_to_sin(sockaddr, &sin);
  2163. tmp.addr = sin.sin_addr.s_addr;
  2164. if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
  2165. peercnt->reg = reg;
  2166. if (limit) {
  2167. peercnt->limit = limit;
  2168. } else {
  2169. set_peercnt_limit(peercnt);
  2170. }
  2171. ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
  2172. ao2_ref(peercnt, -1); /* decrement ref from find */
  2173. }
  2174. }
  2175. /*!
  2176. * \internal
  2177. * \brief adds an ip to the peercnts table, increments connection count if it already exists
  2178. *
  2179. * \details First searches for the address in the peercnts table. If found
  2180. * the current count is incremented. If not found a new peercnt is allocated
  2181. * and linked into the peercnts table with a call number count of 1.
  2182. */
  2183. static int peercnt_add(struct sockaddr_in *sin)
  2184. {
  2185. struct peercnt *peercnt;
  2186. unsigned long addr = sin->sin_addr.s_addr;
  2187. int res = 0;
  2188. struct peercnt tmp = {
  2189. .addr = addr,
  2190. };
  2191. /* Reasoning for peercnts container lock: Two identical ip addresses
  2192. * could be added by different threads at the "same time". Without the container
  2193. * lock, both threads could alloc space for the same object and attempt
  2194. * to link to table. With the lock, one would create the object and link
  2195. * to table while the other would find the already created peercnt object
  2196. * rather than creating a new one. */
  2197. ao2_lock(peercnts);
  2198. if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
  2199. ao2_lock(peercnt);
  2200. } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
  2201. ao2_lock(peercnt);
  2202. /* create and set defaults */
  2203. peercnt->addr = addr;
  2204. set_peercnt_limit(peercnt);
  2205. /* guarantees it does not go away after unlocking table
  2206. * ao2_find automatically adds this */
  2207. ao2_link(peercnts, peercnt);
  2208. } else {
  2209. ao2_unlock(peercnts);
  2210. return -1;
  2211. }
  2212. /* check to see if the address has hit its callno limit. If not increment cur. */
  2213. if (peercnt->limit > peercnt->cur) {
  2214. peercnt->cur++;
  2215. ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
  2216. } else { /* max num call numbers for this peer has been reached! */
  2217. ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
  2218. res = -1;
  2219. }
  2220. /* clean up locks and ref count */
  2221. ao2_unlock(peercnt);
  2222. ao2_unlock(peercnts);
  2223. ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
  2224. return res;
  2225. }
  2226. /*!
  2227. * \internal
  2228. * \brief decrements a peercnts table entry
  2229. */
  2230. static void peercnt_remove(struct peercnt *peercnt)
  2231. {
  2232. struct sockaddr_in sin = {
  2233. .sin_addr.s_addr = peercnt->addr,
  2234. };
  2235. /*
  2236. * Container locked here since peercnt may be unlinked from
  2237. * list. If left unlocked, peercnt_add could try and grab this
  2238. * entry from the table and modify it at the "same time" this
  2239. * thread attemps to unlink it.
  2240. */
  2241. ao2_lock(peercnts);
  2242. peercnt->cur--;
  2243. ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
  2244. /* if this was the last connection from the peer remove it from table */
  2245. if (peercnt->cur == 0) {
  2246. ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
  2247. }
  2248. ao2_unlock(peercnts);
  2249. }
  2250. /*!
  2251. * \internal
  2252. * \brief called by scheduler to decrement object
  2253. */
  2254. static int peercnt_remove_cb(const void *obj)
  2255. {
  2256. struct peercnt *peercnt = (struct peercnt *) obj;
  2257. peercnt_remove(peercnt);
  2258. ao2_ref(peercnt, -1); /* decrement ref from scheduler */
  2259. return 0;
  2260. }
  2261. /*!
  2262. * \internal
  2263. * \brief decrements peercnts connection count, finds by addr
  2264. */
  2265. static int peercnt_remove_by_addr(struct sockaddr_in *sin)
  2266. {
  2267. struct peercnt *peercnt;
  2268. struct peercnt tmp = {
  2269. .addr = sin->sin_addr.s_addr,
  2270. };
  2271. if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
  2272. peercnt_remove(peercnt);
  2273. ao2_ref(peercnt, -1); /* decrement ref from find */
  2274. }
  2275. return 0;
  2276. }
  2277. /*!
  2278. * \internal
  2279. * \brief Create callno_limit entry based on configuration
  2280. */
  2281. static void build_callno_limits(struct ast_variable *v)
  2282. {
  2283. struct addr_range *addr_range = NULL;
  2284. struct addr_range tmp;
  2285. struct ast_ha *ha;
  2286. int limit;
  2287. int error;
  2288. int found;
  2289. for (; v; v = v->next) {
  2290. limit = -1;
  2291. error = 0;
  2292. found = 0;
  2293. ha = ast_append_ha("permit", v->name, NULL, &error);
  2294. /* check for valid config information */
  2295. if (error) {
  2296. ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
  2297. continue;
  2298. } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
  2299. ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
  2300. ast_free_ha(ha);
  2301. continue;
  2302. }
  2303. ast_copy_ha(ha, &tmp.ha);
  2304. /* find or create the addr_range */
  2305. if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
  2306. ao2_lock(addr_range);
  2307. found = 1;
  2308. } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
  2309. ast_free_ha(ha);
  2310. return; /* out of memory */
  2311. }
  2312. /* copy over config data into addr_range object */
  2313. ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
  2314. ast_free_ha(ha); /* cleanup the tmp ha */
  2315. addr_range->limit = limit;
  2316. addr_range->delme = 0;
  2317. /* cleanup */
  2318. if (found) {
  2319. ao2_unlock(addr_range);
  2320. } else {
  2321. ao2_link(callno_limits, addr_range);
  2322. }
  2323. ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
  2324. }
  2325. }
  2326. /*!
  2327. * \internal
  2328. * \brief Create calltoken_ignores entry based on configuration
  2329. */
  2330. static int add_calltoken_ignore(const char *addr)
  2331. {
  2332. struct addr_range tmp;
  2333. struct addr_range *addr_range = NULL;
  2334. struct ast_ha *ha = NULL;
  2335. int error = 0;
  2336. if (ast_strlen_zero(addr)) {
  2337. ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
  2338. return -1;
  2339. }
  2340. ha = ast_append_ha("permit", addr, NULL, &error);
  2341. /* check for valid config information */
  2342. if (error) {
  2343. ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
  2344. return -1;
  2345. }
  2346. ast_copy_ha(ha, &tmp.ha);
  2347. /* find or create the addr_range */
  2348. if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
  2349. ao2_lock(addr_range);
  2350. addr_range->delme = 0;
  2351. ao2_unlock(addr_range);
  2352. } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
  2353. /* copy over config data into addr_range object */
  2354. ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
  2355. ao2_link(calltoken_ignores, addr_range);
  2356. } else {
  2357. ast_free_ha(ha);
  2358. return -1;
  2359. }
  2360. ast_free_ha(ha);
  2361. ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
  2362. return 0;
  2363. }
  2364. static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2365. {
  2366. struct ao2_iterator i;
  2367. struct peercnt *peercnt;
  2368. struct sockaddr_in sin;
  2369. int found = 0;
  2370. switch (cmd) {
  2371. case CLI_INIT:
  2372. e->command = "iax2 show callnumber usage";
  2373. e->usage =
  2374. "Usage: iax2 show callnumber usage [IP address]\n"
  2375. " Shows current IP addresses which are consuming iax2 call numbers\n";
  2376. return NULL;
  2377. case CLI_GENERATE:
  2378. return NULL;
  2379. case CLI_HANDLER:
  2380. if (a->argc < 4 || a->argc > 5)
  2381. return CLI_SHOWUSAGE;
  2382. if (a->argc == 4) {
  2383. ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
  2384. }
  2385. i = ao2_iterator_init(peercnts, 0);
  2386. while ((peercnt = ao2_iterator_next(&i))) {
  2387. sin.sin_addr.s_addr = peercnt->addr;
  2388. if (a->argc == 5) {
  2389. if (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr))) {
  2390. ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
  2391. ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
  2392. ao2_ref(peercnt, -1);
  2393. found = 1;
  2394. break;
  2395. }
  2396. } else {
  2397. ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
  2398. }
  2399. ao2_ref(peercnt, -1);
  2400. }
  2401. ao2_iterator_destroy(&i);
  2402. if (a->argc == 4) {
  2403. ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
  2404. "Non-CallToken Validated Callno Used: %d\n",
  2405. global_maxcallno_nonval,
  2406. total_nonval_callno_used);
  2407. ast_cli(a->fd, "Total Available Callno: %d\n"
  2408. "Regular Callno Available: %d\n"
  2409. "Trunk Callno Available: %d\n",
  2410. ao2_container_count(callno_pool) + ao2_container_count(callno_pool_trunk),
  2411. ao2_container_count(callno_pool),
  2412. ao2_container_count(callno_pool_trunk));
  2413. } else if (a->argc == 5 && !found) {
  2414. ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
  2415. }
  2416. return CLI_SUCCESS;
  2417. default:
  2418. return NULL;
  2419. }
  2420. }
  2421. static struct callno_entry *get_unused_callno(int trunk, int validated)
  2422. {
  2423. struct callno_entry *callno_entry = NULL;
  2424. if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
  2425. ast_log(LOG_WARNING, "Out of CallNumbers\n");
  2426. /* Minor optimization for the extreme case. */
  2427. return NULL;
  2428. }
  2429. /* the callno_pool container is locked here primarily to ensure thread
  2430. * safety of the total_nonval_callno_used check and increment */
  2431. ao2_lock(callno_pool);
  2432. /* only a certain number of nonvalidated call numbers should be allocated.
  2433. * If there ever is an attack, this separates the calltoken validating
  2434. * users from the non calltoken validating users. */
  2435. if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
  2436. ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
  2437. ao2_unlock(callno_pool);
  2438. return NULL;
  2439. }
  2440. /* unlink the object from the container, taking over ownership
  2441. * of the reference the container had to the object */
  2442. callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
  2443. if (callno_entry) {
  2444. callno_entry->validated = validated;
  2445. if (!validated) {
  2446. total_nonval_callno_used++;
  2447. }
  2448. }
  2449. ao2_unlock(callno_pool);
  2450. return callno_entry;
  2451. }
  2452. static int replace_callno(const void *obj)
  2453. {
  2454. struct callno_entry *callno_entry = (struct callno_entry *) obj;
  2455. /* the callno_pool container is locked here primarily to ensure thread
  2456. * safety of the total_nonval_callno_used check and decrement */
  2457. ao2_lock(callno_pool);
  2458. if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
  2459. total_nonval_callno_used--;
  2460. } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
  2461. ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
  2462. }
  2463. if (callno_entry->callno < TRUNK_CALL_START) {
  2464. ao2_link(callno_pool, callno_entry);
  2465. } else {
  2466. ao2_link(callno_pool_trunk, callno_entry);
  2467. }
  2468. ao2_ref(callno_entry, -1); /* only container ref remains */
  2469. ao2_unlock(callno_pool);
  2470. return 0;
  2471. }
  2472. static int callno_hash(const void *obj, const int flags)
  2473. {
  2474. return abs(ast_random());
  2475. }
  2476. static int create_callno_pools(void)
  2477. {
  2478. uint16_t i;
  2479. if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
  2480. return -1;
  2481. }
  2482. if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
  2483. return -1;
  2484. }
  2485. /* start at 2, 0 and 1 are reserved */
  2486. for (i = 2; i < IAX_MAX_CALLS; i++) {
  2487. struct callno_entry *callno_entry;
  2488. if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
  2489. return -1;
  2490. }
  2491. callno_entry->callno = i;
  2492. if (i < TRUNK_CALL_START) {
  2493. ao2_link(callno_pool, callno_entry);
  2494. } else {
  2495. ao2_link(callno_pool_trunk, callno_entry);
  2496. }
  2497. ao2_ref(callno_entry, -1);
  2498. }
  2499. return 0;
  2500. }
  2501. /*!
  2502. * \internal
  2503. * \brief Schedules delayed removal of iax2_pvt call number data
  2504. *
  2505. * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
  2506. * available again, and the address from the previous connection must be decremented
  2507. * from the peercnts table. This function schedules these operations to take place.
  2508. */
  2509. static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
  2510. {
  2511. int i;
  2512. struct peercnt *peercnt;
  2513. struct peercnt tmp = {
  2514. .addr = sin->sin_addr.s_addr,
  2515. };
  2516. if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
  2517. /* refcount is incremented with ao2_find. keep that ref for the scheduler */
  2518. ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
  2519. i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
  2520. if (i == -1) {
  2521. ao2_ref(peercnt, -1);
  2522. }
  2523. }
  2524. iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
  2525. }
  2526. /*!
  2527. * \internal
  2528. * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
  2529. *
  2530. * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
  2531. * a new callno.
  2532. */
  2533. static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
  2534. {
  2535. if (frametype != AST_FRAME_IAX) {
  2536. return 0;
  2537. }
  2538. switch (subclass) {
  2539. case IAX_COMMAND_NEW:
  2540. case IAX_COMMAND_REGREQ:
  2541. case IAX_COMMAND_FWDOWNL:
  2542. case IAX_COMMAND_REGREL:
  2543. return 1;
  2544. case IAX_COMMAND_POKE:
  2545. if (!inbound) {
  2546. return 1;
  2547. }
  2548. break;
  2549. }
  2550. return 0;
  2551. }
  2552. /*
  2553. * \note Calling this function while holding another pvt lock can cause a deadlock.
  2554. */
  2555. static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
  2556. {
  2557. int res = 0;
  2558. int x;
  2559. /* this call is calltoken validated as long as it is either NEW_FORCE
  2560. * or NEW_ALLOW_CALLTOKEN_VALIDATED */
  2561. int validated = (new > NEW_ALLOW) ? 1 : 0;
  2562. char host[80];
  2563. if (new <= NEW_ALLOW) {
  2564. if (callno) {
  2565. struct chan_iax2_pvt *pvt;
  2566. struct chan_iax2_pvt tmp_pvt = {
  2567. .callno = dcallno,
  2568. .peercallno = callno,
  2569. .transfercallno = callno,
  2570. /* hack!! */
  2571. .frames_received = check_dcallno,
  2572. };
  2573. memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
  2574. /* this works for finding normal call numbers not involving transfering */
  2575. if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
  2576. if (return_locked) {
  2577. ast_mutex_lock(&iaxsl[pvt->callno]);
  2578. }
  2579. res = pvt->callno;
  2580. ao2_ref(pvt, -1);
  2581. pvt = NULL;
  2582. return res;
  2583. }
  2584. /* this searches for transfer call numbers that might not get caught otherwise */
  2585. memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
  2586. memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
  2587. if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
  2588. if (return_locked) {
  2589. ast_mutex_lock(&iaxsl[pvt->callno]);
  2590. }
  2591. res = pvt->callno;
  2592. ao2_ref(pvt, -1);
  2593. pvt = NULL;
  2594. return res;
  2595. }
  2596. }
  2597. /* This will occur on the first response to a message that we initiated,
  2598. * such as a PING. */
  2599. if (dcallno) {
  2600. ast_mutex_lock(&iaxsl[dcallno]);
  2601. }
  2602. if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
  2603. iaxs[dcallno]->peercallno = callno;
  2604. res = dcallno;
  2605. store_by_peercallno(iaxs[dcallno]);
  2606. if (!res || !return_locked) {
  2607. ast_mutex_unlock(&iaxsl[dcallno]);
  2608. }
  2609. return res;
  2610. }
  2611. if (dcallno) {
  2612. ast_mutex_unlock(&iaxsl[dcallno]);
  2613. }
  2614. }
  2615. if (!res && (new >= NEW_ALLOW)) {
  2616. struct callno_entry *callno_entry;
  2617. /* It may seem odd that we look through the peer list for a name for
  2618. * this *incoming* call. Well, it is weird. However, users don't
  2619. * have an IP address/port number that we can match against. So,
  2620. * this is just checking for a peer that has that IP/port and
  2621. * assuming that we have a user of the same name. This isn't always
  2622. * correct, but it will be changed if needed after authentication. */
  2623. if (!iax2_getpeername(*sin, host, sizeof(host)))
  2624. snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
  2625. if (peercnt_add(sin)) {
  2626. /* This address has hit its callnumber limit. When the limit
  2627. * is reached, the connection is not added to the peercnts table.*/
  2628. return 0;
  2629. }
  2630. if (!(callno_entry = get_unused_callno(0, validated))) {
  2631. /* since we ran out of space, remove the peercnt
  2632. * entry we added earlier */
  2633. peercnt_remove_by_addr(sin);
  2634. ast_log(LOG_WARNING, "No more space\n");
  2635. return 0;
  2636. }
  2637. x = callno_entry->callno;
  2638. ast_mutex_lock(&iaxsl[x]);
  2639. iaxs[x] = new_iax(sin, host);
  2640. if (iaxs[x]) {
  2641. if (iaxdebug)
  2642. ast_debug(1, "Creating new call structure %d\n", x);
  2643. iaxs[x]->callno_entry = callno_entry;
  2644. iaxs[x]->sockfd = sockfd;
  2645. iaxs[x]->addr.sin_port = sin->sin_port;
  2646. iaxs[x]->addr.sin_family = sin->sin_family;
  2647. iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
  2648. iaxs[x]->peercallno = callno;
  2649. iaxs[x]->callno = x;
  2650. iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
  2651. iaxs[x]->expiry = min_reg_expire;
  2652. iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
  2653. iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
  2654. iaxs[x]->amaflags = amaflags;
  2655. ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
  2656. ast_string_field_set(iaxs[x], accountcode, accountcode);
  2657. ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
  2658. ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
  2659. ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
  2660. if (iaxs[x]->peercallno) {
  2661. store_by_peercallno(iaxs[x]);
  2662. }
  2663. } else {
  2664. ast_log(LOG_WARNING, "Out of resources\n");
  2665. ast_mutex_unlock(&iaxsl[x]);
  2666. replace_callno(callno_entry);
  2667. return 0;
  2668. }
  2669. if (!return_locked)
  2670. ast_mutex_unlock(&iaxsl[x]);
  2671. res = x;
  2672. }
  2673. return res;
  2674. }
  2675. static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
  2676. return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
  2677. }
  2678. static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
  2679. return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
  2680. }
  2681. /*!
  2682. * \brief Queue a frame to a call's owning asterisk channel
  2683. *
  2684. * \pre This function assumes that iaxsl[callno] is locked when called.
  2685. *
  2686. * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
  2687. * was valid before calling it, it may no longer be valid after calling it.
  2688. * This function may unlock and lock the mutex associated with this callno,
  2689. * meaning that another thread may grab it and destroy the call.
  2690. */
  2691. static int iax2_queue_frame(int callno, struct ast_frame *f)
  2692. {
  2693. iax2_lock_owner(callno);
  2694. if (iaxs[callno] && iaxs[callno]->owner) {
  2695. ast_queue_frame(iaxs[callno]->owner, f);
  2696. ast_channel_unlock(iaxs[callno]->owner);
  2697. }
  2698. return 0;
  2699. }
  2700. /*!
  2701. * \brief Queue a hangup frame on the ast_channel owner
  2702. *
  2703. * This function queues a hangup frame on the owner of the IAX2 pvt struct that
  2704. * is active for the given call number.
  2705. *
  2706. * \pre Assumes lock for callno is already held.
  2707. *
  2708. * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
  2709. * was valid before calling it, it may no longer be valid after calling it.
  2710. * This function may unlock and lock the mutex associated with this callno,
  2711. * meaning that another thread may grab it and destroy the call.
  2712. */
  2713. static int iax2_queue_hangup(int callno)
  2714. {
  2715. iax2_lock_owner(callno);
  2716. if (iaxs[callno] && iaxs[callno]->owner) {
  2717. ast_queue_hangup(iaxs[callno]->owner);
  2718. ast_channel_unlock(iaxs[callno]->owner);
  2719. }
  2720. return 0;
  2721. }
  2722. /*!
  2723. * \brief Queue a control frame on the ast_channel owner
  2724. *
  2725. * This function queues a control frame on the owner of the IAX2 pvt struct that
  2726. * is active for the given call number.
  2727. *
  2728. * \pre Assumes lock for callno is already held.
  2729. *
  2730. * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
  2731. * was valid before calling it, it may no longer be valid after calling it.
  2732. * This function may unlock and lock the mutex associated with this callno,
  2733. * meaning that another thread may grab it and destroy the call.
  2734. */
  2735. static int iax2_queue_control_data(int callno,
  2736. enum ast_control_frame_type control, const void *data, size_t datalen)
  2737. {
  2738. iax2_lock_owner(callno);
  2739. if (iaxs[callno] && iaxs[callno]->owner) {
  2740. ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
  2741. ast_channel_unlock(iaxs[callno]->owner);
  2742. }
  2743. return 0;
  2744. }
  2745. static void destroy_firmware(struct iax_firmware *cur)
  2746. {
  2747. /* Close firmware */
  2748. if (cur->fwh) {
  2749. munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
  2750. }
  2751. close(cur->fd);
  2752. ast_free(cur);
  2753. }
  2754. static int try_firmware(char *s)
  2755. {
  2756. struct stat stbuf;
  2757. struct iax_firmware *cur = NULL;
  2758. int ifd, fd, res, len, chunk;
  2759. struct ast_iax2_firmware_header *fwh, fwh2;
  2760. struct MD5Context md5;
  2761. unsigned char sum[16], buf[1024];
  2762. char *s2, *last;
  2763. s2 = ast_alloca(strlen(s) + 100);
  2764. last = strrchr(s, '/');
  2765. if (last)
  2766. last++;
  2767. else
  2768. last = s;
  2769. snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, ast_random());
  2770. if (stat(s, &stbuf) < 0) {
  2771. ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
  2772. return -1;
  2773. }
  2774. /* Make sure it's not a directory */
  2775. if (S_ISDIR(stbuf.st_mode))
  2776. return -1;
  2777. ifd = open(s, O_RDONLY);
  2778. if (ifd < 0) {
  2779. ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
  2780. return -1;
  2781. }
  2782. fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
  2783. if (fd < 0) {
  2784. ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
  2785. close(ifd);
  2786. return -1;
  2787. }
  2788. /* Unlink our newly created file */
  2789. unlink(s2);
  2790. /* Now copy the firmware into it */
  2791. len = stbuf.st_size;
  2792. while(len) {
  2793. chunk = len;
  2794. if (chunk > sizeof(buf))
  2795. chunk = sizeof(buf);
  2796. res = read(ifd, buf, chunk);
  2797. if (res != chunk) {
  2798. ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
  2799. close(ifd);
  2800. close(fd);
  2801. return -1;
  2802. }
  2803. res = write(fd, buf, chunk);
  2804. if (res != chunk) {
  2805. ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
  2806. close(ifd);
  2807. close(fd);
  2808. return -1;
  2809. }
  2810. len -= chunk;
  2811. }
  2812. close(ifd);
  2813. /* Return to the beginning */
  2814. lseek(fd, 0, SEEK_SET);
  2815. if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
  2816. ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
  2817. close(fd);
  2818. return -1;
  2819. }
  2820. if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
  2821. ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
  2822. close(fd);
  2823. return -1;
  2824. }
  2825. if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
  2826. ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
  2827. close(fd);
  2828. return -1;
  2829. }
  2830. if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
  2831. ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
  2832. close(fd);
  2833. return -1;
  2834. }
  2835. fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
  2836. if (fwh == MAP_FAILED) {
  2837. ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
  2838. close(fd);
  2839. return -1;
  2840. }
  2841. MD5Init(&md5);
  2842. MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
  2843. MD5Final(sum, &md5);
  2844. if (memcmp(sum, fwh->chksum, sizeof(sum))) {
  2845. ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
  2846. munmap((void*)fwh, stbuf.st_size);
  2847. close(fd);
  2848. return -1;
  2849. }
  2850. AST_LIST_TRAVERSE(&firmwares, cur, list) {
  2851. if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
  2852. /* Found a candidate */
  2853. if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
  2854. /* The version we have on loaded is older, load this one instead */
  2855. break;
  2856. /* This version is no newer than what we have. Don't worry about it.
  2857. We'll consider it a proper load anyhow though */
  2858. munmap((void*)fwh, stbuf.st_size);
  2859. close(fd);
  2860. return 0;
  2861. }
  2862. }
  2863. if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
  2864. cur->fd = -1;
  2865. AST_LIST_INSERT_TAIL(&firmwares, cur, list);
  2866. }
  2867. if (cur) {
  2868. if (cur->fwh)
  2869. munmap((void*)cur->fwh, cur->mmaplen);
  2870. if (cur->fd > -1)
  2871. close(cur->fd);
  2872. cur->fwh = fwh;
  2873. cur->fd = fd;
  2874. cur->mmaplen = stbuf.st_size;
  2875. cur->dead = 0;
  2876. }
  2877. return 0;
  2878. }
  2879. static int iax_check_version(char *dev)
  2880. {
  2881. int res = 0;
  2882. struct iax_firmware *cur = NULL;
  2883. if (ast_strlen_zero(dev))
  2884. return 0;
  2885. AST_LIST_LOCK(&firmwares);
  2886. AST_LIST_TRAVERSE(&firmwares, cur, list) {
  2887. if (!strcmp(dev, (char *)cur->fwh->devname)) {
  2888. res = ntohs(cur->fwh->version);
  2889. break;
  2890. }
  2891. }
  2892. AST_LIST_UNLOCK(&firmwares);
  2893. return res;
  2894. }
  2895. static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
  2896. {
  2897. int res = -1;
  2898. unsigned int bs = desc & 0xff;
  2899. unsigned int start = (desc >> 8) & 0xffffff;
  2900. unsigned int bytes;
  2901. struct iax_firmware *cur;
  2902. if (ast_strlen_zero((char *)dev) || !bs)
  2903. return -1;
  2904. start *= bs;
  2905. AST_LIST_LOCK(&firmwares);
  2906. AST_LIST_TRAVERSE(&firmwares, cur, list) {
  2907. if (strcmp((char *)dev, (char *)cur->fwh->devname))
  2908. continue;
  2909. iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
  2910. if (start < ntohl(cur->fwh->datalen)) {
  2911. bytes = ntohl(cur->fwh->datalen) - start;
  2912. if (bytes > bs)
  2913. bytes = bs;
  2914. iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
  2915. } else {
  2916. bytes = 0;
  2917. iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
  2918. }
  2919. if (bytes == bs)
  2920. res = 0;
  2921. else
  2922. res = 1;
  2923. break;
  2924. }
  2925. AST_LIST_UNLOCK(&firmwares);
  2926. return res;
  2927. }
  2928. static void reload_firmware(int unload)
  2929. {
  2930. struct iax_firmware *cur = NULL;
  2931. DIR *fwd;
  2932. struct dirent *de;
  2933. char dir[256], fn[256];
  2934. AST_LIST_LOCK(&firmwares);
  2935. /* Mark all as dead */
  2936. AST_LIST_TRAVERSE(&firmwares, cur, list)
  2937. cur->dead = 1;
  2938. /* Now that we have marked them dead... load new ones */
  2939. if (!unload) {
  2940. snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
  2941. fwd = opendir(dir);
  2942. if (fwd) {
  2943. while((de = readdir(fwd))) {
  2944. if (de->d_name[0] != '.') {
  2945. snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
  2946. if (!try_firmware(fn)) {
  2947. ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
  2948. }
  2949. }
  2950. }
  2951. closedir(fwd);
  2952. } else
  2953. ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
  2954. }
  2955. /* Clean up leftovers */
  2956. AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
  2957. if (!cur->dead)
  2958. continue;
  2959. AST_LIST_REMOVE_CURRENT(list);
  2960. destroy_firmware(cur);
  2961. }
  2962. AST_LIST_TRAVERSE_SAFE_END;
  2963. AST_LIST_UNLOCK(&firmwares);
  2964. }
  2965. /*!
  2966. * \note This function assumes that iaxsl[callno] is locked when called.
  2967. *
  2968. * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
  2969. * was valid before calling it, it may no longer be valid after calling it.
  2970. * This function calls iax2_queue_frame(), which may unlock and lock the mutex
  2971. * associated with this callno, meaning that another thread may grab it and destroy the call.
  2972. */
  2973. static int __do_deliver(void *data)
  2974. {
  2975. /* Just deliver the packet by using queueing. This is called by
  2976. the IAX thread with the iaxsl lock held. */
  2977. struct iax_frame *fr = data;
  2978. fr->retrans = -1;
  2979. ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
  2980. if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
  2981. iax2_queue_frame(fr->callno, &fr->af);
  2982. /* Free our iax frame */
  2983. iax2_frame_free(fr);
  2984. /* And don't run again */
  2985. return 0;
  2986. }
  2987. static int handle_error(void)
  2988. {
  2989. /* XXX Ideally we should figure out why an error occurred and then abort those
  2990. rather than continuing to try. Unfortunately, the published interface does
  2991. not seem to work XXX */
  2992. #if 0
  2993. struct sockaddr_in *sin;
  2994. int res;
  2995. struct msghdr m;
  2996. struct sock_extended_err e;
  2997. m.msg_name = NULL;
  2998. m.msg_namelen = 0;
  2999. m.msg_iov = NULL;
  3000. m.msg_control = &e;
  3001. m.msg_controllen = sizeof(e);
  3002. m.msg_flags = 0;
  3003. res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
  3004. if (res < 0)
  3005. ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
  3006. else {
  3007. if (m.msg_controllen) {
  3008. sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
  3009. if (sin)
  3010. ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
  3011. else
  3012. ast_log(LOG_WARNING, "No address detected??\n");
  3013. } else {
  3014. ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
  3015. }
  3016. }
  3017. #endif
  3018. return 0;
  3019. }
  3020. static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
  3021. {
  3022. int res;
  3023. res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
  3024. sizeof(*sin));
  3025. if (res < 0) {
  3026. ast_debug(1, "Received error: %s\n", strerror(errno));
  3027. handle_error();
  3028. } else
  3029. res = 0;
  3030. return res;
  3031. }
  3032. static int send_packet(struct iax_frame *f)
  3033. {
  3034. int res;
  3035. int callno = f->callno;
  3036. /* Don't send if there was an error, but return error instead */
  3037. if (!callno || !iaxs[callno] || iaxs[callno]->error)
  3038. return -1;
  3039. /* Called with iaxsl held */
  3040. if (iaxdebug)
  3041. ast_debug(3, "Sending %u on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
  3042. if (f->transfer) {
  3043. iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
  3044. res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
  3045. } else {
  3046. iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
  3047. res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
  3048. }
  3049. if (res < 0) {
  3050. if (iaxdebug)
  3051. ast_debug(1, "Received error: %s\n", strerror(errno));
  3052. handle_error();
  3053. } else
  3054. res = 0;
  3055. return res;
  3056. }
  3057. /*!
  3058. * \note Since this function calls iax2_queue_hangup(), the pvt struct
  3059. * for the given call number may disappear during its execution.
  3060. */
  3061. static int iax2_predestroy(int callno)
  3062. {
  3063. struct ast_channel *c = NULL;
  3064. struct chan_iax2_pvt *pvt = iaxs[callno];
  3065. if (!pvt)
  3066. return -1;
  3067. if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
  3068. iax2_destroy_helper(pvt);
  3069. ast_set_flag64(pvt, IAX_ALREADYGONE);
  3070. }
  3071. if ((c = pvt->owner)) {
  3072. ast_channel_tech_pvt_set(c, NULL);
  3073. iax2_queue_hangup(callno);
  3074. pvt->owner = NULL;
  3075. ast_module_unref(ast_module_info->self);
  3076. }
  3077. return 0;
  3078. }
  3079. static void iax2_destroy(int callno)
  3080. {
  3081. struct chan_iax2_pvt *pvt = NULL;
  3082. struct ast_channel *owner = NULL;
  3083. retry:
  3084. if ((pvt = iaxs[callno])) {
  3085. #if 0
  3086. /* iax2_destroy_helper gets called from this function later on. When
  3087. * called twice, we get the (previously) familiar FRACK! errors in
  3088. * devmode, from the scheduler. An alternative to this approach is to
  3089. * reset the scheduler entries to -1 when they're deleted in
  3090. * iax2_destroy_helper(). That approach was previously decided to be
  3091. * "wrong" because "the memory is going to be deallocated anyway. Why
  3092. * should we be resetting those values?" */
  3093. iax2_destroy_helper(pvt);
  3094. #endif
  3095. }
  3096. owner = pvt ? pvt->owner : NULL;
  3097. if (owner) {
  3098. if (ast_channel_trylock(owner)) {
  3099. ast_debug(3, "Avoiding IAX destroy deadlock\n");
  3100. DEADLOCK_AVOIDANCE(&iaxsl[callno]);
  3101. goto retry;
  3102. }
  3103. }
  3104. if (!owner) {
  3105. iaxs[callno] = NULL;
  3106. }
  3107. if (pvt) {
  3108. if (!owner) {
  3109. pvt->owner = NULL;
  3110. } else {
  3111. /* If there's an owner, prod it to give up */
  3112. /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
  3113. * because we already hold the owner channel lock. */
  3114. ast_queue_hangup(owner);
  3115. }
  3116. if (pvt->peercallno) {
  3117. remove_by_peercallno(pvt);
  3118. }
  3119. if (pvt->transfercallno) {
  3120. remove_by_transfercallno(pvt);
  3121. }
  3122. if (!owner) {
  3123. ao2_ref(pvt, -1);
  3124. pvt = NULL;
  3125. }
  3126. }
  3127. if (owner) {
  3128. ast_channel_unlock(owner);
  3129. }
  3130. }
  3131. static int update_packet(struct iax_frame *f)
  3132. {
  3133. /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
  3134. struct ast_iax2_full_hdr *fh = f->data;
  3135. struct ast_frame af;
  3136. /* if frame is encrypted. decrypt before updating it. */
  3137. if (f->encmethods) {
  3138. decode_frame(&f->mydcx, fh, &af, &f->datalen);
  3139. }
  3140. /* Mark this as a retransmission */
  3141. fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
  3142. /* Update iseqno */
  3143. f->iseqno = iaxs[f->callno]->iseqno;
  3144. fh->iseqno = f->iseqno;
  3145. /* Now re-encrypt the frame */
  3146. if (f->encmethods) {
  3147. /* since this is a retransmit frame, create a new random padding
  3148. * before re-encrypting. */
  3149. build_rand_pad(f->semirand, sizeof(f->semirand));
  3150. encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
  3151. }
  3152. return 0;
  3153. }
  3154. static int attempt_transmit(const void *data);
  3155. static void __attempt_transmit(const void *data)
  3156. {
  3157. /* Attempt to transmit the frame to the remote peer...
  3158. Called without iaxsl held. */
  3159. struct iax_frame *f = (struct iax_frame *)data;
  3160. int freeme = 0;
  3161. int callno = f->callno;
  3162. /* Make sure this call is still active */
  3163. if (callno)
  3164. ast_mutex_lock(&iaxsl[callno]);
  3165. if (callno && iaxs[callno]) {
  3166. if (f->retries < 0) {
  3167. /* Already ACK'd */
  3168. freeme = 1;
  3169. } else if (f->retries >= max_retries) {
  3170. /* Too many attempts. Record an error. */
  3171. if (f->transfer) {
  3172. /* Transfer timeout */
  3173. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
  3174. } else if (f->final) {
  3175. iax2_destroy(callno);
  3176. } else {
  3177. if (iaxs[callno]->owner) {
  3178. ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %u, subclass = %d, ts=%u, seqno=%d)\n",
  3179. ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),
  3180. ast_channel_name(iaxs[f->callno]->owner),
  3181. f->af.frametype,
  3182. f->af.subclass.integer,
  3183. f->ts,
  3184. f->oseqno);
  3185. }
  3186. iaxs[callno]->error = ETIMEDOUT;
  3187. if (iaxs[callno]->owner) {
  3188. struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
  3189. /* Hangup the fd */
  3190. iax2_queue_frame(callno, &fr); /* XXX */
  3191. /* Remember, owner could disappear */
  3192. if (iaxs[callno] && iaxs[callno]->owner)
  3193. ast_channel_hangupcause_set(iaxs[callno]->owner, AST_CAUSE_DESTINATION_OUT_OF_ORDER);
  3194. } else {
  3195. if (iaxs[callno]->reg) {
  3196. memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
  3197. iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
  3198. iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
  3199. }
  3200. iax2_destroy(callno);
  3201. }
  3202. }
  3203. freeme = 1;
  3204. } else {
  3205. /* Update it if it needs it */
  3206. update_packet(f);
  3207. /* Attempt transmission */
  3208. send_packet(f);
  3209. f->retries++;
  3210. /* Try again later after 10 times as long */
  3211. f->retrytime *= 10;
  3212. if (f->retrytime > MAX_RETRY_TIME)
  3213. f->retrytime = MAX_RETRY_TIME;
  3214. /* Transfer messages max out at one second */
  3215. if (f->transfer && (f->retrytime > 1000))
  3216. f->retrytime = 1000;
  3217. f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
  3218. }
  3219. } else {
  3220. /* Make sure it gets freed */
  3221. f->retries = -1;
  3222. freeme = 1;
  3223. }
  3224. if (freeme) {
  3225. /* Don't attempt delivery, just remove it from the queue */
  3226. AST_LIST_REMOVE(&frame_queue[callno], f, list);
  3227. ast_mutex_unlock(&iaxsl[callno]);
  3228. f->retrans = -1; /* this is safe because this is the scheduled function */
  3229. /* Free the IAX frame */
  3230. iax2_frame_free(f);
  3231. } else if (callno) {
  3232. ast_mutex_unlock(&iaxsl[callno]);
  3233. }
  3234. }
  3235. static int attempt_transmit(const void *data)
  3236. {
  3237. #ifdef SCHED_MULTITHREADED
  3238. if (schedule_action(__attempt_transmit, data))
  3239. #endif
  3240. __attempt_transmit(data);
  3241. return 0;
  3242. }
  3243. static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3244. {
  3245. struct iax2_peer *peer = NULL;
  3246. struct iax2_user *user = NULL;
  3247. static const char * const choices[] = { "all", NULL };
  3248. char *cmplt;
  3249. switch (cmd) {
  3250. case CLI_INIT:
  3251. e->command = "iax2 prune realtime";
  3252. e->usage =
  3253. "Usage: iax2 prune realtime [<peername>|all]\n"
  3254. " Prunes object(s) from the cache\n";
  3255. return NULL;
  3256. case CLI_GENERATE:
  3257. if (a->pos == 3) {
  3258. cmplt = ast_cli_complete(a->word, choices, a->n);
  3259. if (!cmplt)
  3260. cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
  3261. return cmplt;
  3262. }
  3263. return NULL;
  3264. }
  3265. if (a->argc != 4)
  3266. return CLI_SHOWUSAGE;
  3267. if (!strcmp(a->argv[3], "all")) {
  3268. prune_users();
  3269. prune_peers();
  3270. ast_cli(a->fd, "Cache flushed successfully.\n");
  3271. return CLI_SUCCESS;
  3272. }
  3273. peer = find_peer(a->argv[3], 0);
  3274. user = find_user(a->argv[3]);
  3275. if (peer || user) {
  3276. if (peer) {
  3277. if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
  3278. ast_set_flag64(peer, IAX_RTAUTOCLEAR);
  3279. expire_registry(peer_ref(peer));
  3280. ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
  3281. } else {
  3282. ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
  3283. }
  3284. peer_unref(peer);
  3285. }
  3286. if (user) {
  3287. if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
  3288. ast_set_flag64(user, IAX_RTAUTOCLEAR);
  3289. ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
  3290. } else {
  3291. ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
  3292. }
  3293. ao2_unlink(users,user);
  3294. user_unref(user);
  3295. }
  3296. } else {
  3297. ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
  3298. }
  3299. return CLI_SUCCESS;
  3300. }
  3301. static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3302. {
  3303. switch (cmd) {
  3304. case CLI_INIT:
  3305. e->command = "iax2 test losspct";
  3306. e->usage =
  3307. "Usage: iax2 test losspct <percentage>\n"
  3308. " For testing, throws away <percentage> percent of incoming packets\n";
  3309. return NULL;
  3310. case CLI_GENERATE:
  3311. return NULL;
  3312. }
  3313. if (a->argc != 4)
  3314. return CLI_SHOWUSAGE;
  3315. test_losspct = atoi(a->argv[3]);
  3316. return CLI_SUCCESS;
  3317. }
  3318. #ifdef IAXTESTS
  3319. static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3320. {
  3321. switch (cmd) {
  3322. case CLI_INIT:
  3323. e->command = "iax2 test late";
  3324. e->usage =
  3325. "Usage: iax2 test late <ms>\n"
  3326. " For testing, count the next frame as <ms> ms late\n";
  3327. return NULL;
  3328. case CLI_GENERATE:
  3329. return NULL;
  3330. }
  3331. if (a->argc != 4)
  3332. return CLI_SHOWUSAGE;
  3333. test_late = atoi(a->argv[3]);
  3334. return CLI_SUCCESS;
  3335. }
  3336. static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3337. {
  3338. switch (cmd) {
  3339. case CLI_INIT:
  3340. e->command = "iax2 test resync";
  3341. e->usage =
  3342. "Usage: iax2 test resync <ms>\n"
  3343. " For testing, adjust all future frames by <ms> ms\n";
  3344. return NULL;
  3345. case CLI_GENERATE:
  3346. return NULL;
  3347. }
  3348. if (a->argc != 4)
  3349. return CLI_SHOWUSAGE;
  3350. test_resync = atoi(a->argv[3]);
  3351. return CLI_SUCCESS;
  3352. }
  3353. static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3354. {
  3355. switch (cmd) {
  3356. case CLI_INIT:
  3357. e->command = "iax2 test jitter";
  3358. e->usage =
  3359. "Usage: iax2 test jitter <ms> <pct>\n"
  3360. " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
  3361. " percentage of packets. If <pct> is not specified, adds\n"
  3362. " jitter to all packets.\n";
  3363. return NULL;
  3364. case CLI_GENERATE:
  3365. return NULL;
  3366. }
  3367. if (a->argc < 4 || a->argc > 5)
  3368. return CLI_SHOWUSAGE;
  3369. test_jit = atoi(a->argv[3]);
  3370. if (a->argc == 5)
  3371. test_jitpct = atoi(a->argv[4]);
  3372. return CLI_SUCCESS;
  3373. }
  3374. #endif /* IAXTESTS */
  3375. /*! \brief peer_status: Report Peer status in character string */
  3376. /* returns 1 if peer is online, -1 if unmonitored */
  3377. static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
  3378. {
  3379. int res = 0;
  3380. if (peer->maxms) {
  3381. if (peer->lastms < 0) {
  3382. ast_copy_string(status, "UNREACHABLE", statuslen);
  3383. } else if (peer->lastms > peer->maxms) {
  3384. snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
  3385. res = 1;
  3386. } else if (peer->lastms) {
  3387. snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
  3388. res = 1;
  3389. } else {
  3390. ast_copy_string(status, "UNKNOWN", statuslen);
  3391. }
  3392. } else {
  3393. ast_copy_string(status, "Unmonitored", statuslen);
  3394. res = -1;
  3395. }
  3396. return res;
  3397. }
  3398. /*! \brief Show one peer in detail */
  3399. static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3400. {
  3401. char status[30];
  3402. char cbuf[256];
  3403. struct iax2_peer *peer;
  3404. char codec_buf[512];
  3405. struct ast_str *encmethods = ast_str_alloca(256);
  3406. int x = 0, load_realtime = 0;
  3407. switch (cmd) {
  3408. case CLI_INIT:
  3409. e->command = "iax2 show peer";
  3410. e->usage =
  3411. "Usage: iax2 show peer <name>\n"
  3412. " Display details on specific IAX peer\n";
  3413. return NULL;
  3414. case CLI_GENERATE:
  3415. if (a->pos == 3)
  3416. return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
  3417. return NULL;
  3418. }
  3419. if (a->argc < 4)
  3420. return CLI_SHOWUSAGE;
  3421. load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
  3422. peer = find_peer(a->argv[3], load_realtime);
  3423. if (peer) {
  3424. struct sockaddr_in peer_addr;
  3425. ast_sockaddr_to_sin(&peer->addr, &peer_addr);
  3426. encmethods_to_str(peer->encmethods, &encmethods);
  3427. ast_cli(a->fd, "\n\n");
  3428. ast_cli(a->fd, " * Name : %s\n", peer->name);
  3429. ast_cli(a->fd, " Description : %s\n", peer->description);
  3430. ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
  3431. ast_cli(a->fd, " Context : %s\n", peer->context);
  3432. ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
  3433. ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
  3434. ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
  3435. ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
  3436. ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
  3437. ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
  3438. ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
  3439. ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
  3440. ast_cli(a->fd, " Expire : %d\n", peer->expire);
  3441. ast_cli(a->fd, " ACL : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
  3442. ast_cli(a->fd, " Addr->IP : %s Port %d\n", peer_addr.sin_addr.s_addr ? ast_inet_ntoa(peer_addr.sin_addr) : "(Unspecified)", ntohs(peer_addr.sin_port));
  3443. ast_cli(a->fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
  3444. ast_cli(a->fd, " Username : %s\n", peer->username);
  3445. ast_cli(a->fd, " Codecs : ");
  3446. iax2_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
  3447. ast_cli(a->fd, "%s\n", codec_buf);
  3448. ast_cli(a->fd, " Codec Order : (");
  3449. for(x = 0; x < AST_CODEC_PREF_SIZE; x++) {
  3450. struct ast_format tmpfmt;
  3451. if(!(ast_codec_pref_index(&peer->prefs, x, &tmpfmt)))
  3452. break;
  3453. ast_cli(a->fd, "%s", ast_getformatname(&tmpfmt));
  3454. if(x < 31 && ast_codec_pref_index(&peer->prefs, x+1, &tmpfmt))
  3455. ast_cli(a->fd, "|");
  3456. }
  3457. if (!x)
  3458. ast_cli(a->fd, "none");
  3459. ast_cli(a->fd, ")\n");
  3460. ast_cli(a->fd, " Status : ");
  3461. peer_status(peer, status, sizeof(status));
  3462. ast_cli(a->fd, "%s\n",status);
  3463. ast_cli(a->fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
  3464. ast_cli(a->fd, "\n");
  3465. peer_unref(peer);
  3466. } else {
  3467. ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
  3468. ast_cli(a->fd, "\n");
  3469. }
  3470. return CLI_SUCCESS;
  3471. }
  3472. static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
  3473. {
  3474. int which = 0;
  3475. struct iax2_peer *peer;
  3476. char *res = NULL;
  3477. int wordlen = strlen(word);
  3478. struct ao2_iterator i;
  3479. i = ao2_iterator_init(peers, 0);
  3480. while ((peer = ao2_iterator_next(&i))) {
  3481. if (!strncasecmp(peer->name, word, wordlen) && ++which > state
  3482. && (!flags || ast_test_flag64(peer, flags))) {
  3483. res = ast_strdup(peer->name);
  3484. peer_unref(peer);
  3485. break;
  3486. }
  3487. peer_unref(peer);
  3488. }
  3489. ao2_iterator_destroy(&i);
  3490. return res;
  3491. }
  3492. static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3493. {
  3494. struct iax_frame *cur;
  3495. int cnt = 0, dead = 0, final = 0, i = 0;
  3496. switch (cmd) {
  3497. case CLI_INIT:
  3498. e->command = "iax2 show stats";
  3499. e->usage =
  3500. "Usage: iax2 show stats\n"
  3501. " Display statistics on IAX channel driver.\n";
  3502. return NULL;
  3503. case CLI_GENERATE:
  3504. return NULL;
  3505. }
  3506. if (a->argc != 3)
  3507. return CLI_SHOWUSAGE;
  3508. for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
  3509. ast_mutex_lock(&iaxsl[i]);
  3510. AST_LIST_TRAVERSE(&frame_queue[i], cur, list) {
  3511. if (cur->retries < 0)
  3512. dead++;
  3513. if (cur->final)
  3514. final++;
  3515. cnt++;
  3516. }
  3517. ast_mutex_unlock(&iaxsl[i]);
  3518. }
  3519. ast_cli(a->fd, " IAX Statistics\n");
  3520. ast_cli(a->fd, "---------------------\n");
  3521. ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
  3522. ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
  3523. trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
  3524. ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
  3525. trunk_timed = trunk_untimed = 0;
  3526. if (trunk_maxmtu > trunk_nmaxmtu)
  3527. trunk_nmaxmtu = trunk_maxmtu;
  3528. return CLI_SUCCESS;
  3529. }
  3530. /*! \brief Set trunk MTU from CLI */
  3531. static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3532. {
  3533. int mtuv;
  3534. switch (cmd) {
  3535. case CLI_INIT:
  3536. e->command = "iax2 set mtu";
  3537. e->usage =
  3538. "Usage: iax2 set mtu <value>\n"
  3539. " Set the system-wide IAX IP mtu to <value> bytes net or\n"
  3540. " zero to disable. Disabling means that the operating system\n"
  3541. " must handle fragmentation of UDP packets when the IAX2 trunk\n"
  3542. " packet exceeds the UDP payload size. This is substantially\n"
  3543. " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
  3544. " greater for G.711 samples.\n";
  3545. return NULL;
  3546. case CLI_GENERATE:
  3547. return NULL;
  3548. }
  3549. if (a->argc != 4)
  3550. return CLI_SHOWUSAGE;
  3551. if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
  3552. mtuv = MAX_TRUNK_MTU;
  3553. else
  3554. mtuv = atoi(a->argv[3]);
  3555. if (mtuv == 0) {
  3556. ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
  3557. global_max_trunk_mtu = 0;
  3558. return CLI_SUCCESS;
  3559. }
  3560. if (mtuv < 172 || mtuv > 4000) {
  3561. ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
  3562. return CLI_SHOWUSAGE;
  3563. }
  3564. ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
  3565. global_max_trunk_mtu = mtuv;
  3566. return CLI_SUCCESS;
  3567. }
  3568. static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3569. {
  3570. struct iax2_dpcache *dp = NULL;
  3571. char tmp[1024], *pc = NULL;
  3572. int s, x, y;
  3573. struct timeval now = ast_tvnow();
  3574. switch (cmd) {
  3575. case CLI_INIT:
  3576. e->command = "iax2 show cache";
  3577. e->usage =
  3578. "Usage: iax2 show cache\n"
  3579. " Display currently cached IAX Dialplan results.\n";
  3580. return NULL;
  3581. case CLI_GENERATE:
  3582. return NULL;
  3583. }
  3584. AST_LIST_LOCK(&dpcache);
  3585. ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
  3586. AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
  3587. s = dp->expiry.tv_sec - now.tv_sec;
  3588. tmp[0] = '\0';
  3589. if (dp->flags & CACHE_FLAG_EXISTS)
  3590. strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
  3591. if (dp->flags & CACHE_FLAG_NONEXISTENT)
  3592. strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
  3593. if (dp->flags & CACHE_FLAG_CANEXIST)
  3594. strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
  3595. if (dp->flags & CACHE_FLAG_PENDING)
  3596. strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
  3597. if (dp->flags & CACHE_FLAG_TIMEOUT)
  3598. strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
  3599. if (dp->flags & CACHE_FLAG_TRANSMITTED)
  3600. strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
  3601. if (dp->flags & CACHE_FLAG_MATCHMORE)
  3602. strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
  3603. if (dp->flags & CACHE_FLAG_UNKNOWN)
  3604. strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
  3605. /* Trim trailing pipe */
  3606. if (!ast_strlen_zero(tmp)) {
  3607. tmp[strlen(tmp) - 1] = '\0';
  3608. } else {
  3609. ast_copy_string(tmp, "(none)", sizeof(tmp));
  3610. }
  3611. y = 0;
  3612. pc = strchr(dp->peercontext, '@');
  3613. if (!pc) {
  3614. pc = dp->peercontext;
  3615. } else {
  3616. pc++;
  3617. }
  3618. for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
  3619. if (dp->waiters[x] > -1)
  3620. y++;
  3621. }
  3622. if (s > 0) {
  3623. ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
  3624. } else {
  3625. ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
  3626. }
  3627. }
  3628. AST_LIST_UNLOCK(&dpcache);
  3629. return CLI_SUCCESS;
  3630. }
  3631. static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
  3632. static void unwrap_timestamp(struct iax_frame *fr)
  3633. {
  3634. /* Video mini frames only encode the lower 15 bits of the session
  3635. * timestamp, but other frame types (e.g. audio) encode 16 bits. */
  3636. const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
  3637. const int lower_mask = (1 << ts_shift) - 1;
  3638. const int upper_mask = ~lower_mask;
  3639. const int last_upper = iaxs[fr->callno]->last & upper_mask;
  3640. if ( (fr->ts & upper_mask) == last_upper ) {
  3641. const int x = fr->ts - iaxs[fr->callno]->last;
  3642. const int threshold = (ts_shift == 15) ? 25000 : 50000;
  3643. if (x < -threshold) {
  3644. /* Sudden big jump backwards in timestamp:
  3645. What likely happened here is that miniframe timestamp has circled but we haven't
  3646. gotten the update from the main packet. We'll just pretend that we did, and
  3647. update the timestamp appropriately. */
  3648. fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
  3649. if (iaxdebug)
  3650. ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
  3651. } else if (x > threshold) {
  3652. /* Sudden apparent big jump forwards in timestamp:
  3653. What's likely happened is this is an old miniframe belonging to the previous
  3654. top 15 or 16-bit timestamp that has turned up out of order.
  3655. Adjust the timestamp appropriately. */
  3656. fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
  3657. if (iaxdebug)
  3658. ast_debug(1, "schedule_delivery: pushed back timestamp\n");
  3659. }
  3660. }
  3661. }
  3662. static int get_from_jb(const void *p);
  3663. static void update_jbsched(struct chan_iax2_pvt *pvt)
  3664. {
  3665. int when;
  3666. when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
  3667. when = jb_next(pvt->jb) - when;
  3668. if (when <= 0) {
  3669. /* XXX should really just empty until when > 0.. */
  3670. when = 1;
  3671. }
  3672. pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
  3673. CALLNO_TO_PTR(pvt->callno));
  3674. }
  3675. static void __get_from_jb(const void *p)
  3676. {
  3677. int callno = PTR_TO_CALLNO(p);
  3678. struct chan_iax2_pvt *pvt = NULL;
  3679. struct iax_frame *fr;
  3680. jb_frame frame;
  3681. int ret;
  3682. long ms;
  3683. long next;
  3684. struct timeval now = ast_tvnow();
  3685. /* Make sure we have a valid private structure before going on */
  3686. ast_mutex_lock(&iaxsl[callno]);
  3687. pvt = iaxs[callno];
  3688. if (!pvt) {
  3689. /* No go! */
  3690. ast_mutex_unlock(&iaxsl[callno]);
  3691. return;
  3692. }
  3693. pvt->jbid = -1;
  3694. /* round up a millisecond since ast_sched_runq does; */
  3695. /* prevents us from spinning while waiting for our now */
  3696. /* to catch up with runq's now */
  3697. now.tv_usec += 1000;
  3698. ms = ast_tvdiff_ms(now, pvt->rxcore);
  3699. if(ms >= (next = jb_next(pvt->jb))) {
  3700. struct ast_format voicefmt;
  3701. ast_format_from_old_bitfield(&voicefmt, pvt->voiceformat);
  3702. ret = jb_get(pvt->jb, &frame, ms, ast_codec_interp_len(&voicefmt));
  3703. switch(ret) {
  3704. case JB_OK:
  3705. fr = frame.data;
  3706. __do_deliver(fr);
  3707. /* __do_deliver() can cause the call to disappear */
  3708. pvt = iaxs[callno];
  3709. break;
  3710. case JB_INTERP:
  3711. {
  3712. struct ast_frame af = { 0, };
  3713. /* create an interpolation frame */
  3714. af.frametype = AST_FRAME_VOICE;
  3715. ast_format_copy(&af.subclass.format, &voicefmt);
  3716. af.samples = frame.ms * (ast_format_rate(&voicefmt) / 1000);
  3717. af.src = "IAX2 JB interpolation";
  3718. af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
  3719. af.offset = AST_FRIENDLY_OFFSET;
  3720. /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
  3721. * which we'd need to malloc, and then it would free it. That seems like a drag */
  3722. if (!ast_test_flag64(iaxs[callno], IAX_ALREADYGONE)) {
  3723. iax2_queue_frame(callno, &af);
  3724. /* iax2_queue_frame() could cause the call to disappear */
  3725. pvt = iaxs[callno];
  3726. }
  3727. }
  3728. break;
  3729. case JB_DROP:
  3730. iax2_frame_free(frame.data);
  3731. break;
  3732. case JB_NOFRAME:
  3733. case JB_EMPTY:
  3734. /* do nothing */
  3735. break;
  3736. default:
  3737. /* shouldn't happen */
  3738. break;
  3739. }
  3740. }
  3741. if (pvt)
  3742. update_jbsched(pvt);
  3743. ast_mutex_unlock(&iaxsl[callno]);
  3744. }
  3745. static int get_from_jb(const void *data)
  3746. {
  3747. #ifdef SCHED_MULTITHREADED
  3748. if (schedule_action(__get_from_jb, data))
  3749. #endif
  3750. __get_from_jb(data);
  3751. return 0;
  3752. }
  3753. /*!
  3754. * \note This function assumes fr->callno is locked
  3755. *
  3756. * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
  3757. * was valid before calling it, it may no longer be valid after calling it.
  3758. */
  3759. static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
  3760. {
  3761. int type, len;
  3762. int ret;
  3763. int needfree = 0;
  3764. struct ast_channel *owner = NULL;
  3765. struct ast_channel *bridge = NULL;
  3766. /*
  3767. * Clear fr->af.data if there is no data in the buffer. Things
  3768. * like AST_CONTROL_HOLD without a suggested music class must
  3769. * have a NULL pointer.
  3770. */
  3771. if (!fr->af.datalen) {
  3772. memset(&fr->af.data, 0, sizeof(fr->af.data));
  3773. }
  3774. /* Attempt to recover wrapped timestamps */
  3775. unwrap_timestamp(fr);
  3776. /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
  3777. if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
  3778. fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
  3779. else {
  3780. #if 0
  3781. ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
  3782. #endif
  3783. fr->af.delivery = ast_tv(0,0);
  3784. }
  3785. type = JB_TYPE_CONTROL;
  3786. len = 0;
  3787. if(fr->af.frametype == AST_FRAME_VOICE) {
  3788. type = JB_TYPE_VOICE;
  3789. len = ast_codec_get_samples(&fr->af) / (ast_format_rate(&fr->af.subclass.format) / 1000);
  3790. } else if(fr->af.frametype == AST_FRAME_CNG) {
  3791. type = JB_TYPE_SILENCE;
  3792. }
  3793. if ( (!ast_test_flag64(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
  3794. if (tsout)
  3795. *tsout = fr->ts;
  3796. __do_deliver(fr);
  3797. return -1;
  3798. }
  3799. iax2_lock_owner(fr->callno);
  3800. if (!iaxs[fr->callno]) {
  3801. /* The call dissappeared so discard this frame that we could not send. */
  3802. iax2_frame_free(fr);
  3803. return -1;
  3804. }
  3805. if ((owner = iaxs[fr->callno]->owner))
  3806. bridge = ast_bridged_channel(owner);
  3807. /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
  3808. * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
  3809. if ( (!ast_test_flag64(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (ast_channel_tech(bridge)->properties & AST_CHAN_TP_WANTSJITTER) ) {
  3810. jb_frame frame;
  3811. ast_channel_unlock(owner);
  3812. /* deliver any frames in the jb */
  3813. while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
  3814. __do_deliver(frame.data);
  3815. /* __do_deliver() can make the call disappear */
  3816. if (!iaxs[fr->callno])
  3817. return -1;
  3818. }
  3819. jb_reset(iaxs[fr->callno]->jb);
  3820. AST_SCHED_DEL(sched, iaxs[fr->callno]->jbid);
  3821. /* deliver this frame now */
  3822. if (tsout)
  3823. *tsout = fr->ts;
  3824. __do_deliver(fr);
  3825. return -1;
  3826. }
  3827. if (owner) {
  3828. ast_channel_unlock(owner);
  3829. }
  3830. /* insert into jitterbuffer */
  3831. /* TODO: Perhaps we could act immediately if it's not droppable and late */
  3832. ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
  3833. calc_rxstamp(iaxs[fr->callno],fr->ts));
  3834. if (ret == JB_DROP) {
  3835. needfree++;
  3836. } else if (ret == JB_SCHED) {
  3837. update_jbsched(iaxs[fr->callno]);
  3838. }
  3839. if (tsout)
  3840. *tsout = fr->ts;
  3841. if (needfree) {
  3842. /* Free our iax frame */
  3843. iax2_frame_free(fr);
  3844. return -1;
  3845. }
  3846. return 0;
  3847. }
  3848. static int transmit_frame(void *data)
  3849. {
  3850. struct iax_frame *fr = data;
  3851. ast_mutex_lock(&iaxsl[fr->callno]);
  3852. fr->sentyet = 1;
  3853. if (iaxs[fr->callno]) {
  3854. send_packet(fr);
  3855. }
  3856. if (fr->retries < 0) {
  3857. ast_mutex_unlock(&iaxsl[fr->callno]);
  3858. /* No retransmit requested */
  3859. iax_frame_free(fr);
  3860. } else {
  3861. /* We need reliable delivery. Schedule a retransmission */
  3862. AST_LIST_INSERT_TAIL(&frame_queue[fr->callno], fr, list);
  3863. fr->retries++;
  3864. fr->retrans = iax2_sched_add(sched, fr->retrytime, attempt_transmit, fr);
  3865. ast_mutex_unlock(&iaxsl[fr->callno]);
  3866. }
  3867. return 0;
  3868. }
  3869. static int iax2_transmit(struct iax_frame *fr)
  3870. {
  3871. fr->sentyet = 0;
  3872. return ast_taskprocessor_push(transmit_processor, transmit_frame, fr);
  3873. }
  3874. static int iax2_digit_begin(struct ast_channel *c, char digit)
  3875. {
  3876. return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
  3877. }
  3878. static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
  3879. {
  3880. return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
  3881. }
  3882. static int iax2_sendtext(struct ast_channel *c, const char *text)
  3883. {
  3884. return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_TEXT,
  3885. 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
  3886. }
  3887. static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
  3888. {
  3889. return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_IMAGE, img->subclass.integer, 0, img->data.ptr, img->datalen, -1);
  3890. }
  3891. static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
  3892. {
  3893. return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
  3894. }
  3895. static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
  3896. {
  3897. unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(newchan));
  3898. ast_mutex_lock(&iaxsl[callno]);
  3899. if (iaxs[callno])
  3900. iaxs[callno]->owner = newchan;
  3901. else
  3902. ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
  3903. ast_mutex_unlock(&iaxsl[callno]);
  3904. return 0;
  3905. }
  3906. /*!
  3907. * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
  3908. * so do not call this with a pvt lock held.
  3909. */
  3910. static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
  3911. {
  3912. struct ast_variable *var = NULL;
  3913. struct ast_variable *tmp;
  3914. struct iax2_peer *peer=NULL;
  3915. time_t regseconds = 0, nowtime;
  3916. int dynamic=0;
  3917. if (peername) {
  3918. var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
  3919. if (!var && sin)
  3920. var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
  3921. } else if (sin) {
  3922. char porta[25];
  3923. sprintf(porta, "%d", ntohs(sin->sin_port));
  3924. var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
  3925. if (var) {
  3926. /* We'll need the peer name in order to build the structure! */
  3927. for (tmp = var; tmp; tmp = tmp->next) {
  3928. if (!strcasecmp(tmp->name, "name"))
  3929. peername = tmp->value;
  3930. }
  3931. }
  3932. }
  3933. if (!var && peername) { /* Last ditch effort */
  3934. var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
  3935. /*!\note
  3936. * If this one loaded something, then we need to ensure that the host
  3937. * field matched. The only reason why we can't have this as a criteria
  3938. * is because we only have the IP address and the host field might be
  3939. * set as a name (and the reverse PTR might not match).
  3940. */
  3941. if (var && sin) {
  3942. for (tmp = var; tmp; tmp = tmp->next) {
  3943. if (!strcasecmp(tmp->name, "host")) {
  3944. struct ast_hostent ahp;
  3945. struct hostent *hp;
  3946. if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || memcmp(hp->h_addr, &sin->sin_addr, hp->h_length)) {
  3947. /* No match */
  3948. ast_variables_destroy(var);
  3949. var = NULL;
  3950. }
  3951. break;
  3952. }
  3953. }
  3954. }
  3955. }
  3956. if (!var)
  3957. return NULL;
  3958. peer = build_peer(peername, var, NULL, ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
  3959. if (!peer) {
  3960. ast_variables_destroy(var);
  3961. return NULL;
  3962. }
  3963. for (tmp = var; tmp; tmp = tmp->next) {
  3964. /* Make sure it's not a user only... */
  3965. if (!strcasecmp(tmp->name, "type")) {
  3966. if (strcasecmp(tmp->value, "friend") &&
  3967. strcasecmp(tmp->value, "peer")) {
  3968. /* Whoops, we weren't supposed to exist! */
  3969. peer = peer_unref(peer);
  3970. break;
  3971. }
  3972. } else if (!strcasecmp(tmp->name, "regseconds")) {
  3973. ast_get_time_t(tmp->value, &regseconds, 0, NULL);
  3974. } else if (!strcasecmp(tmp->name, "ipaddr")) {
  3975. if (!ast_sockaddr_parse(&peer->addr, tmp->value, PARSE_PORT_IGNORE)) {
  3976. ast_log(LOG_WARNING, "Failed to parse sockaddr '%s' for ipaddr of realtime peer '%s'\n", tmp->value, tmp->name);
  3977. }
  3978. } else if (!strcasecmp(tmp->name, "port")) {
  3979. ast_sockaddr_set_port(&peer->addr, atoi(tmp->value));
  3980. } else if (!strcasecmp(tmp->name, "host")) {
  3981. if (!strcasecmp(tmp->value, "dynamic"))
  3982. dynamic = 1;
  3983. }
  3984. }
  3985. ast_variables_destroy(var);
  3986. if (!peer)
  3987. return NULL;
  3988. if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
  3989. ast_copy_flags64(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
  3990. if (ast_test_flag64(peer, IAX_RTAUTOCLEAR)) {
  3991. if (peer->expire > -1) {
  3992. if (!AST_SCHED_DEL(sched, peer->expire)) {
  3993. peer->expire = -1;
  3994. peer_unref(peer);
  3995. }
  3996. }
  3997. peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
  3998. if (peer->expire == -1)
  3999. peer_unref(peer);
  4000. }
  4001. ao2_link(peers, peer);
  4002. if (ast_test_flag64(peer, IAX_DYNAMIC))
  4003. reg_source_db(peer);
  4004. } else {
  4005. ast_set_flag64(peer, IAX_TEMPONLY);
  4006. }
  4007. if (!ast_test_flag64(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
  4008. time(&nowtime);
  4009. if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
  4010. memset(&peer->addr, 0, sizeof(peer->addr));
  4011. realtime_update_peer(peer->name, &peer->addr, 0);
  4012. ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
  4013. peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
  4014. }
  4015. else {
  4016. ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
  4017. peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
  4018. }
  4019. }
  4020. return peer;
  4021. }
  4022. static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
  4023. {
  4024. struct ast_variable *var;
  4025. struct ast_variable *tmp;
  4026. struct iax2_user *user=NULL;
  4027. var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", SENTINEL);
  4028. if (!var)
  4029. var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
  4030. if (!var && sin) {
  4031. char porta[6];
  4032. snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
  4033. var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
  4034. if (!var)
  4035. var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
  4036. }
  4037. if (!var) { /* Last ditch effort */
  4038. var = ast_load_realtime("iaxusers", "name", username, SENTINEL);
  4039. /*!\note
  4040. * If this one loaded something, then we need to ensure that the host
  4041. * field matched. The only reason why we can't have this as a criteria
  4042. * is because we only have the IP address and the host field might be
  4043. * set as a name (and the reverse PTR might not match).
  4044. */
  4045. if (var) {
  4046. for (tmp = var; tmp; tmp = tmp->next) {
  4047. if (!strcasecmp(tmp->name, "host")) {
  4048. struct ast_hostent ahp;
  4049. struct hostent *hp;
  4050. if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || memcmp(hp->h_addr, &sin->sin_addr, hp->h_length)) {
  4051. /* No match */
  4052. ast_variables_destroy(var);
  4053. var = NULL;
  4054. }
  4055. break;
  4056. }
  4057. }
  4058. }
  4059. }
  4060. if (!var)
  4061. return NULL;
  4062. tmp = var;
  4063. while(tmp) {
  4064. /* Make sure it's not a peer only... */
  4065. if (!strcasecmp(tmp->name, "type")) {
  4066. if (strcasecmp(tmp->value, "friend") &&
  4067. strcasecmp(tmp->value, "user")) {
  4068. return NULL;
  4069. }
  4070. }
  4071. tmp = tmp->next;
  4072. }
  4073. user = build_user(username, var, NULL, !ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS));
  4074. ast_variables_destroy(var);
  4075. if (!user)
  4076. return NULL;
  4077. if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
  4078. ast_set_flag64(user, IAX_RTCACHEFRIENDS);
  4079. ao2_link(users, user);
  4080. } else {
  4081. ast_set_flag64(user, IAX_TEMPONLY);
  4082. }
  4083. return user;
  4084. }
  4085. static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
  4086. {
  4087. char port[10];
  4088. char regseconds[20];
  4089. const char *sysname = ast_config_AST_SYSTEM_NAME;
  4090. char *syslabel = NULL;
  4091. if (ast_strlen_zero(sysname)) /* No system name, disable this */
  4092. sysname = NULL;
  4093. else if (ast_test_flag64(&globalflags, IAX_RTSAVE_SYSNAME))
  4094. syslabel = "regserver";
  4095. snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
  4096. snprintf(port, sizeof(port), "%d", ast_sockaddr_port(sockaddr));
  4097. ast_update_realtime("iaxpeers", "name", peername,
  4098. "ipaddr", ast_sockaddr_stringify_addr(sockaddr), "port", port,
  4099. "regseconds", regseconds, syslabel, sysname, SENTINEL); /* note syslable can be NULL */
  4100. }
  4101. struct create_addr_info {
  4102. iax2_format capability;
  4103. uint64_t flags;
  4104. int maxtime;
  4105. int encmethods;
  4106. int found;
  4107. int sockfd;
  4108. int adsi;
  4109. char username[80];
  4110. char secret[80];
  4111. char outkey[80];
  4112. char timezone[80];
  4113. char prefs[32];
  4114. char cid_num[80];
  4115. char cid_name[80];
  4116. char context[AST_MAX_CONTEXT];
  4117. char peercontext[AST_MAX_CONTEXT];
  4118. char mohinterpret[MAX_MUSICCLASS];
  4119. char mohsuggest[MAX_MUSICCLASS];
  4120. };
  4121. static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
  4122. {
  4123. struct iax2_peer *peer;
  4124. int res = -1;
  4125. struct ast_codec_pref ourprefs;
  4126. struct sockaddr_in peer_addr;
  4127. ast_clear_flag64(cai, IAX_SENDANI | IAX_TRUNK);
  4128. cai->sockfd = defaultsockfd;
  4129. cai->maxtime = 0;
  4130. sin->sin_family = AF_INET;
  4131. if (!(peer = find_peer(peername, 1))) {
  4132. struct ast_sockaddr sin_tmp;
  4133. cai->found = 0;
  4134. sin_tmp.ss.ss_family = AF_INET;
  4135. if (ast_get_ip_or_srv(&sin_tmp, peername, srvlookup ? "_iax._udp" : NULL)) {
  4136. ast_log(LOG_WARNING, "No such host: %s\n", peername);
  4137. return -1;
  4138. }
  4139. ast_sockaddr_to_sin(&sin_tmp, sin);
  4140. if (sin->sin_port == 0) {
  4141. sin->sin_port = htons(IAX_DEFAULT_PORTNO);
  4142. }
  4143. /* use global iax prefs for unknown peer/user */
  4144. /* But move the calling channel's native codec to the top of the preference list */
  4145. memcpy(&ourprefs, &prefs, sizeof(ourprefs));
  4146. if (c) {
  4147. struct ast_format tmpfmt;
  4148. ast_format_cap_iter_start(ast_channel_nativeformats(c));
  4149. while (!(ast_format_cap_iter_next(ast_channel_nativeformats(c), &tmpfmt))) {
  4150. ast_codec_pref_prepend(&ourprefs, &tmpfmt, 1);
  4151. }
  4152. ast_format_cap_iter_end(ast_channel_nativeformats(c));
  4153. }
  4154. ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
  4155. return 0;
  4156. }
  4157. cai->found = 1;
  4158. ast_sockaddr_to_sin(&peer->addr, &peer_addr);
  4159. /* if the peer has no address (current or default), return failure */
  4160. if (!(peer_addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
  4161. goto return_unref;
  4162. }
  4163. /* if the peer is being monitored and is currently unreachable, return failure */
  4164. if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
  4165. goto return_unref;
  4166. ast_copy_flags64(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
  4167. cai->maxtime = peer->maxms;
  4168. cai->capability = peer->capability;
  4169. cai->encmethods = peer->encmethods;
  4170. cai->sockfd = peer->sockfd;
  4171. cai->adsi = peer->adsi;
  4172. memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
  4173. /* Move the calling channel's native codec to the top of the preference list */
  4174. if (c) {
  4175. struct ast_format tmpfmt;
  4176. ast_format_cap_iter_start(ast_channel_nativeformats(c));
  4177. while (!(ast_format_cap_iter_next(ast_channel_nativeformats(c), &tmpfmt))) {
  4178. ast_debug(1, "prepending %s to prefs\n", ast_getformatname(&tmpfmt));
  4179. ast_codec_pref_prepend(&ourprefs, &tmpfmt, 1);
  4180. }
  4181. ast_format_cap_iter_end(ast_channel_nativeformats(c));
  4182. }
  4183. ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
  4184. ast_copy_string(cai->context, peer->context, sizeof(cai->context));
  4185. ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
  4186. ast_copy_string(cai->username, peer->username, sizeof(cai->username));
  4187. ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
  4188. ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
  4189. ast_copy_string(cai->cid_num, peer->cid_num, sizeof(cai->cid_num));
  4190. ast_copy_string(cai->cid_name, peer->cid_name, sizeof(cai->cid_name));
  4191. ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
  4192. ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
  4193. if (ast_strlen_zero(peer->dbsecret)) {
  4194. ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
  4195. } else {
  4196. char *family;
  4197. char *key = NULL;
  4198. family = ast_strdupa(peer->dbsecret);
  4199. key = strchr(family, '/');
  4200. if (key)
  4201. *key++ = '\0';
  4202. if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
  4203. ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
  4204. goto return_unref;
  4205. }
  4206. }
  4207. if (peer_addr.sin_addr.s_addr) {
  4208. sin->sin_addr = peer_addr.sin_addr;
  4209. sin->sin_port = peer_addr.sin_port;
  4210. } else {
  4211. sin->sin_addr = peer->defaddr.sin_addr;
  4212. sin->sin_port = peer->defaddr.sin_port;
  4213. }
  4214. res = 0;
  4215. return_unref:
  4216. peer_unref(peer);
  4217. return res;
  4218. }
  4219. static void __auto_congest(const void *nothing)
  4220. {
  4221. int callno = PTR_TO_CALLNO(nothing);
  4222. struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_CONGESTION } };
  4223. ast_mutex_lock(&iaxsl[callno]);
  4224. if (iaxs[callno]) {
  4225. iaxs[callno]->initid = -1;
  4226. iax2_queue_frame(callno, &f);
  4227. ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
  4228. }
  4229. ast_mutex_unlock(&iaxsl[callno]);
  4230. }
  4231. static int auto_congest(const void *data)
  4232. {
  4233. #ifdef SCHED_MULTITHREADED
  4234. if (schedule_action(__auto_congest, data))
  4235. #endif
  4236. __auto_congest(data);
  4237. return 0;
  4238. }
  4239. static unsigned int iax2_datetime(const char *tz)
  4240. {
  4241. struct timeval t = ast_tvnow();
  4242. struct ast_tm tm;
  4243. unsigned int tmp;
  4244. ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
  4245. tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
  4246. tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
  4247. tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
  4248. tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
  4249. tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
  4250. tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
  4251. return tmp;
  4252. }
  4253. struct parsed_dial_string {
  4254. char *username;
  4255. char *password;
  4256. char *key;
  4257. char *peer;
  4258. char *port;
  4259. char *exten;
  4260. char *context;
  4261. char *options;
  4262. };
  4263. static int send_apathetic_reply(unsigned short callno, unsigned short dcallno,
  4264. struct sockaddr_in *sin, int command, int ts, unsigned char seqno,
  4265. int sockfd, struct iax_ie_data *ied)
  4266. {
  4267. struct {
  4268. struct ast_iax2_full_hdr f;
  4269. struct iax_ie_data ied;
  4270. } data;
  4271. size_t size = sizeof(struct ast_iax2_full_hdr);
  4272. if (ied) {
  4273. size += ied->pos;
  4274. memcpy(&data.ied, ied->buf, ied->pos);
  4275. }
  4276. data.f.scallno = htons(0x8000 | callno);
  4277. data.f.dcallno = htons(dcallno & ~IAX_FLAG_RETRANS);
  4278. data.f.ts = htonl(ts);
  4279. data.f.iseqno = seqno;
  4280. data.f.oseqno = 0;
  4281. data.f.type = AST_FRAME_IAX;
  4282. data.f.csub = compress_subclass(command);
  4283. iax_outputframe(NULL, &data.f, 0, sin, size - sizeof(struct ast_iax2_full_hdr));
  4284. return sendto(sockfd, &data, size, 0, (struct sockaddr *)sin, sizeof(*sin));
  4285. }
  4286. static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
  4287. {
  4288. /* first make sure their are two empty bytes left in ied->buf */
  4289. if (pvt && ied && (2 < ((int) sizeof(ied->buf) - ied->pos))) {
  4290. ied->buf[ied->pos++] = IAX_IE_CALLTOKEN; /* type */
  4291. ied->buf[ied->pos++] = 0; /* data size, ZERO in this case */
  4292. pvt->calltoken_ie_len = 2;
  4293. }
  4294. }
  4295. static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
  4296. {
  4297. struct chan_iax2_pvt *pvt = iaxs[callno];
  4298. int frametype = f->af.frametype;
  4299. int subclass = f->af.subclass.integer;
  4300. struct {
  4301. struct ast_iax2_full_hdr fh;
  4302. struct iax_ie_data ied;
  4303. } data = {
  4304. .ied.buf = { 0 },
  4305. .ied.pos = 0,
  4306. };
  4307. /* total len - header len gives us the frame's IE len */
  4308. int ie_data_pos = f->datalen - sizeof(struct ast_iax2_full_hdr);
  4309. if (!pvt) {
  4310. return; /* this should not be possible if called from socket_process() */
  4311. }
  4312. /*
  4313. * Check to make sure last frame sent is valid for call token resend
  4314. * 1. Frame should _NOT_ be encrypted since it starts the IAX dialog
  4315. * 2. Frame should _NOT_ already have a destination callno
  4316. * 3. Frame must be a valid iax_frame subclass capable of starting dialog
  4317. * 4. Pvt must have a calltoken_ie_len which represents the number of
  4318. * bytes at the end of the frame used for the previous calltoken ie.
  4319. * 5. Pvt's calltoken_ie_len must be _LESS_ than the total IE length
  4320. * 6. Total length of f->data must be _LESS_ than size of our data struct
  4321. * because f->data must be able to fit within data.
  4322. */
  4323. if (f->encmethods || f->dcallno || !iax2_allow_new(frametype, subclass, 0)
  4324. || !pvt->calltoken_ie_len || (pvt->calltoken_ie_len > ie_data_pos) ||
  4325. (f->datalen > sizeof(data))) {
  4326. return; /* ignore resend, token was not valid for the dialog */
  4327. }
  4328. /* token is valid
  4329. * 1. Copy frame data over
  4330. * 2. Redo calltoken IE, it will always be the last ie in the frame.
  4331. * NOTE: Having the ie always be last is not protocol specified,
  4332. * it is only an implementation choice. Since we only expect the ie to
  4333. * be last for frames we have sent, this can no way be affected by
  4334. * another end point.
  4335. * 3. Remove frame from queue
  4336. * 4. Free old frame
  4337. * 5. Clear previous seqnos
  4338. * 6. Resend with CALLTOKEN ie.
  4339. */
  4340. /* ---1.--- */
  4341. memcpy(&data, f->data, f->datalen);
  4342. data.ied.pos = ie_data_pos;
  4343. /* ---2.--- */
  4344. /* move to the beginning of the calltoken ie so we can write over it */
  4345. data.ied.pos -= pvt->calltoken_ie_len;
  4346. iax_ie_append_str(&data.ied, IAX_IE_CALLTOKEN, newtoken);
  4347. /* make sure to update token length incase it ever has to be stripped off again */
  4348. pvt->calltoken_ie_len = data.ied.pos - ie_data_pos; /* new pos minus old pos tells how big token ie is */
  4349. /* ---3.--- */
  4350. AST_LIST_REMOVE(&frame_queue[callno], f, list);
  4351. /* ---4.--- */
  4352. iax2_frame_free(f);
  4353. /* ---5.--- */
  4354. pvt->oseqno = 0;
  4355. pvt->rseqno = 0;
  4356. pvt->iseqno = 0;
  4357. pvt->aseqno = 0;
  4358. if (pvt->peercallno) {
  4359. remove_by_peercallno(pvt);
  4360. pvt->peercallno = 0;
  4361. }
  4362. /* ---6.--- */
  4363. send_command(pvt, AST_FRAME_IAX, subclass, 0, data.ied.buf, data.ied.pos, -1);
  4364. }
  4365. static void requirecalltoken_mark_auto(const char *name, int subclass)
  4366. {
  4367. struct iax2_user *user = NULL;
  4368. struct iax2_peer *peer = NULL;
  4369. if (ast_strlen_zero(name)) {
  4370. return; /* no username given */
  4371. }
  4372. if ((subclass == IAX_COMMAND_NEW) && (user = find_user(name)) && (user->calltoken_required == CALLTOKEN_AUTO)) {
  4373. user->calltoken_required = CALLTOKEN_YES;
  4374. } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(name, 1)) && (peer->calltoken_required == CALLTOKEN_AUTO)) {
  4375. peer->calltoken_required = CALLTOKEN_YES;
  4376. }
  4377. if (peer) {
  4378. peer_unref(peer);
  4379. }
  4380. if (user) {
  4381. user_unref(user);
  4382. }
  4383. }
  4384. /*!
  4385. * \internal
  4386. *
  4387. * \brief handles calltoken logic for a received iax_frame.
  4388. *
  4389. * \note frametype must be AST_FRAME_IAX.
  4390. *
  4391. * \note
  4392. * Three different cases are possible here.
  4393. * Case 1. An empty calltoken is provided. This means the client supports
  4394. * calltokens but has not yet received one from us. In this case
  4395. * a full calltoken IE is created and sent in a calltoken fullframe.
  4396. * Case 2. A full calltoken is received and must be checked for validity.
  4397. * Case 3. No calltoken is received indicating that the client does not
  4398. * support calltokens. In this case it is up to the configuration
  4399. * to decide how this should be handled (reject or permit without calltoken)
  4400. */
  4401. static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies,
  4402. struct sockaddr_in *sin, int fd)
  4403. {
  4404. #define CALLTOKEN_HASH_FORMAT "%s%d%u%d" /* address + port + ts + randomcalldata */
  4405. #define CALLTOKEN_IE_FORMAT "%u?%s" /* time + ? + (40 char hash) */
  4406. struct ast_str *buf = ast_str_alloca(256);
  4407. time_t t = time(NULL);
  4408. char hash[41]; /* 40 char sha1 hash */
  4409. int subclass = uncompress_subclass(fh->csub);
  4410. /* ----- Case 1 ----- */
  4411. if (ies->calltoken && !ies->calltokendata) { /* empty calltoken is provided, client supports calltokens */
  4412. struct iax_ie_data ied = {
  4413. .buf = { 0 },
  4414. .pos = 0,
  4415. };
  4416. /* create the hash with their address data and our timestamp */
  4417. ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) t, randomcalltokendata);
  4418. ast_sha1_hash(hash, ast_str_buffer(buf));
  4419. ast_str_set(&buf, 0, CALLTOKEN_IE_FORMAT, (unsigned int) t, hash);
  4420. iax_ie_append_str(&ied, IAX_IE_CALLTOKEN, ast_str_buffer(buf));
  4421. send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_CALLTOKEN, ntohl(fh->ts), fh->iseqno + 1, fd, &ied);
  4422. return 1;
  4423. /* ----- Case 2 ----- */
  4424. } else if (ies->calltoken && ies->calltokendata) { /* calltoken received, check to see if it is valid */
  4425. char *rec_hash = NULL; /* the received hash, make sure it matches with ours. */
  4426. char *rec_ts = NULL; /* received timestamp */
  4427. unsigned int rec_time; /* received time_t */
  4428. /* split the timestamp from the hash data */
  4429. rec_hash = strchr((char *) ies->calltokendata, '?');
  4430. if (rec_hash) {
  4431. *rec_hash++ = '\0';
  4432. rec_ts = (char *) ies->calltokendata;
  4433. }
  4434. /* check that we have valid data before we do any comparisons */
  4435. if (!rec_hash || !rec_ts) {
  4436. goto reject;
  4437. } else if (sscanf(rec_ts, "%u", &rec_time) != 1) {
  4438. goto reject;
  4439. }
  4440. /* create a hash with their address and the _TOKEN'S_ timestamp */
  4441. ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) rec_time, randomcalltokendata);
  4442. ast_sha1_hash(hash, ast_str_buffer(buf));
  4443. /* compare hashes and then check timestamp delay */
  4444. if (strcmp(hash, rec_hash)) {
  4445. ast_log(LOG_WARNING, "Address %s failed CallToken hash inspection\n", ast_inet_ntoa(sin->sin_addr));
  4446. goto reject; /* received hash does not match ours, reject */
  4447. } else if ((t < rec_time) || ((t - rec_time) >= MAX_CALLTOKEN_DELAY)) {
  4448. ast_log(LOG_WARNING, "Too much delay in IAX2 calltoken timestamp from address %s\n", ast_inet_ntoa(sin->sin_addr));
  4449. goto reject; /* too much delay, reject */
  4450. }
  4451. /* at this point the call token is valid, returning 0
  4452. * will allow socket_process to continue as usual */
  4453. requirecalltoken_mark_auto(ies->username, subclass);
  4454. return 0;
  4455. /* ----- Case 3 ----- */
  4456. } else { /* calltokens are not supported for this client, how do we respond? */
  4457. if (calltoken_required(sin, ies->username, subclass)) {
  4458. ast_log(LOG_ERROR, "Call rejected, CallToken Support required. If unexpected, resolve by placing address %s in the calltokenoptional list or setting user %s requirecalltoken=no\n", ast_inet_ntoa(sin->sin_addr), S_OR(ies->username, "guest"));
  4459. goto reject;
  4460. }
  4461. return 0; /* calltoken is not required for this addr, so permit it. */
  4462. }
  4463. reject:
  4464. /* received frame has failed calltoken inspection, send apathetic reject messages */
  4465. if (subclass == IAX_COMMAND_REGREQ || subclass == IAX_COMMAND_REGREL) {
  4466. send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
  4467. } else {
  4468. send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
  4469. }
  4470. return 1;
  4471. }
  4472. /*!
  4473. * \brief Parses an IAX dial string into its component parts.
  4474. * \param data the string to be parsed
  4475. * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
  4476. * \return nothing
  4477. *
  4478. * This function parses the string and fills the structure
  4479. * with pointers to its component parts. The input string
  4480. * will be modified.
  4481. *
  4482. * \note This function supports both plaintext passwords and RSA
  4483. * key names; if the password string is formatted as '[keyname]',
  4484. * then the keyname will be placed into the key field, and the
  4485. * password field will be set to NULL.
  4486. *
  4487. * \note The dial string format is:
  4488. * [username[:password]@]peer[:port][/exten[@@context]][/options]
  4489. */
  4490. static void parse_dial_string(char *data, struct parsed_dial_string *pds)
  4491. {
  4492. if (ast_strlen_zero(data))
  4493. return;
  4494. pds->peer = strsep(&data, "/");
  4495. pds->exten = strsep(&data, "/");
  4496. pds->options = data;
  4497. if (pds->exten) {
  4498. data = pds->exten;
  4499. pds->exten = strsep(&data, "@");
  4500. pds->context = data;
  4501. }
  4502. if (strchr(pds->peer, '@')) {
  4503. data = pds->peer;
  4504. pds->username = strsep(&data, "@");
  4505. pds->peer = data;
  4506. }
  4507. if (pds->username) {
  4508. data = pds->username;
  4509. pds->username = strsep(&data, ":");
  4510. pds->password = data;
  4511. }
  4512. data = pds->peer;
  4513. pds->peer = strsep(&data, ":");
  4514. pds->port = data;
  4515. /* check for a key name wrapped in [] in the secret position, if found,
  4516. move it to the key field instead
  4517. */
  4518. if (pds->password && (pds->password[0] == '[')) {
  4519. pds->key = ast_strip_quoted(pds->password, "[", "]");
  4520. pds->password = NULL;
  4521. }
  4522. }
  4523. static int iax2_call(struct ast_channel *c, const char *dest, int timeout)
  4524. {
  4525. struct sockaddr_in sin;
  4526. char *l=NULL, *n=NULL, *tmpstr;
  4527. struct iax_ie_data ied;
  4528. char *defaultrdest = "s";
  4529. unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
  4530. struct parsed_dial_string pds;
  4531. struct create_addr_info cai;
  4532. struct ast_var_t *var;
  4533. struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
  4534. const char* osp_token_ptr;
  4535. unsigned int osp_token_length;
  4536. unsigned char osp_block_index;
  4537. unsigned int osp_block_length;
  4538. unsigned char osp_buffer[256];
  4539. iax2_format iax2_tmpfmt;
  4540. if ((ast_channel_state(c) != AST_STATE_DOWN) && (ast_channel_state(c) != AST_STATE_RESERVED)) {
  4541. ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", ast_channel_name(c));
  4542. return -1;
  4543. }
  4544. memset(&cai, 0, sizeof(cai));
  4545. cai.encmethods = iax2_encryption;
  4546. memset(&pds, 0, sizeof(pds));
  4547. tmpstr = ast_strdupa(dest);
  4548. parse_dial_string(tmpstr, &pds);
  4549. if (ast_strlen_zero(pds.peer)) {
  4550. ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
  4551. return -1;
  4552. }
  4553. if (!pds.exten) {
  4554. pds.exten = defaultrdest;
  4555. }
  4556. if (create_addr(pds.peer, c, &sin, &cai)) {
  4557. ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
  4558. return -1;
  4559. }
  4560. if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) && !cai.encmethods) {
  4561. ast_log(LOG_WARNING, "Encryption forced for call, but not enabled\n");
  4562. ast_channel_hangupcause_set(c, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  4563. return -1;
  4564. }
  4565. if (ast_strlen_zero(cai.secret) && ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
  4566. ast_log(LOG_WARNING, "Call terminated. No secret given and force encrypt enabled\n");
  4567. return -1;
  4568. }
  4569. if (!pds.username && !ast_strlen_zero(cai.username))
  4570. pds.username = cai.username;
  4571. if (!pds.password && !ast_strlen_zero(cai.secret))
  4572. pds.password = cai.secret;
  4573. if (!pds.key && !ast_strlen_zero(cai.outkey))
  4574. pds.key = cai.outkey;
  4575. if (!pds.context && !ast_strlen_zero(cai.peercontext))
  4576. pds.context = cai.peercontext;
  4577. /* Keep track of the context for outgoing calls too */
  4578. ast_channel_context_set(c, cai.context);
  4579. if (pds.port)
  4580. sin.sin_port = htons(atoi(pds.port));
  4581. l = ast_channel_connected(c)->id.number.valid ? ast_channel_connected(c)->id.number.str : NULL;
  4582. n = ast_channel_connected(c)->id.name.valid ? ast_channel_connected(c)->id.name.str : NULL;
  4583. /* Now build request */
  4584. memset(&ied, 0, sizeof(ied));
  4585. /* On new call, first IE MUST be IAX version of caller */
  4586. iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
  4587. iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
  4588. if (pds.options && strchr(pds.options, 'a')) {
  4589. /* Request auto answer */
  4590. iax_ie_append(&ied, IAX_IE_AUTOANSWER);
  4591. }
  4592. /* WARNING: this breaks down at 190 bits! */
  4593. iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
  4594. if (l) {
  4595. iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
  4596. iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES,
  4597. ast_party_id_presentation(&ast_channel_connected(c)->id));
  4598. } else if (n) {
  4599. iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES,
  4600. ast_party_id_presentation(&ast_channel_connected(c)->id));
  4601. } else {
  4602. iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
  4603. }
  4604. iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, ast_channel_connected(c)->id.number.plan);
  4605. iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, ast_channel_dialed(c)->transit_network_select);
  4606. if (n)
  4607. iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
  4608. if (ast_test_flag64(iaxs[callno], IAX_SENDANI)
  4609. && ast_channel_connected(c)->ani.number.valid
  4610. && ast_channel_connected(c)->ani.number.str) {
  4611. iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, ast_channel_connected(c)->ani.number.str);
  4612. }
  4613. if (!ast_strlen_zero(ast_channel_language(c)))
  4614. iax_ie_append_str(&ied, IAX_IE_LANGUAGE, ast_channel_language(c));
  4615. if (!ast_strlen_zero(ast_channel_dialed(c)->number.str)) {
  4616. iax_ie_append_str(&ied, IAX_IE_DNID, ast_channel_dialed(c)->number.str);
  4617. }
  4618. if (ast_channel_redirecting(c)->from.number.valid
  4619. && !ast_strlen_zero(ast_channel_redirecting(c)->from.number.str)) {
  4620. iax_ie_append_str(&ied, IAX_IE_RDNIS, ast_channel_redirecting(c)->from.number.str);
  4621. }
  4622. if (pds.context)
  4623. iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
  4624. if (pds.username)
  4625. iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
  4626. if (cai.encmethods)
  4627. iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
  4628. ast_mutex_lock(&iaxsl[callno]);
  4629. if (!ast_strlen_zero(ast_channel_context(c)))
  4630. ast_string_field_set(iaxs[callno], context, ast_channel_context(c));
  4631. if (pds.username)
  4632. ast_string_field_set(iaxs[callno], username, pds.username);
  4633. iaxs[callno]->encmethods = cai.encmethods;
  4634. iaxs[callno]->adsi = cai.adsi;
  4635. ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
  4636. ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
  4637. if (pds.key)
  4638. ast_string_field_set(iaxs[callno], outkey, pds.key);
  4639. if (pds.password)
  4640. ast_string_field_set(iaxs[callno], secret, pds.password);
  4641. iax2_tmpfmt = ast_format_cap_to_old_bitfield(ast_channel_nativeformats(c));
  4642. iax_ie_append_int(&ied, IAX_IE_FORMAT, (int) iax2_tmpfmt);
  4643. iax_ie_append_versioned_uint64(&ied, IAX_IE_FORMAT2, 0, iax2_tmpfmt);
  4644. iax_ie_append_int(&ied, IAX_IE_CAPABILITY, (int) iaxs[callno]->capability);
  4645. iax_ie_append_versioned_uint64(&ied, IAX_IE_CAPABILITY2, 0, iaxs[callno]->capability);
  4646. iax_ie_append_short(&ied, IAX_IE_ADSICPE, ast_channel_adsicpe(c));
  4647. iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
  4648. if (iaxs[callno]->maxtime) {
  4649. /* Initialize pingtime and auto-congest time */
  4650. iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
  4651. iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
  4652. } else if (autokill) {
  4653. iaxs[callno]->pingtime = autokill / 2;
  4654. iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
  4655. }
  4656. /* Check if there is an OSP token */
  4657. osp_token_ptr = pbx_builtin_getvar_helper(c, "IAX2OSPTOKEN");
  4658. if (!ast_strlen_zero(osp_token_ptr)) {
  4659. if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
  4660. osp_block_index = 0;
  4661. while (osp_token_length > 0) {
  4662. osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
  4663. osp_buffer[0] = osp_block_index;
  4664. memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
  4665. iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
  4666. osp_block_index++;
  4667. osp_token_ptr += osp_block_length;
  4668. osp_token_length -= osp_block_length;
  4669. }
  4670. } else
  4671. ast_log(LOG_WARNING, "OSP token is too long\n");
  4672. } else if (iaxdebug)
  4673. ast_debug(1, "OSP token is undefined\n");
  4674. /* send the command using the appropriate socket for this peer */
  4675. iaxs[callno]->sockfd = cai.sockfd;
  4676. /* Add remote vars */
  4677. if (variablestore) {
  4678. AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
  4679. ast_debug(1, "Found an IAX variable store on this channel\n");
  4680. AST_LIST_LOCK(variablelist);
  4681. AST_LIST_TRAVERSE(variablelist, var, entries) {
  4682. char tmp[256];
  4683. int i;
  4684. ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
  4685. /* Automatically divide the value up into sized chunks */
  4686. for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
  4687. snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
  4688. iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
  4689. }
  4690. }
  4691. AST_LIST_UNLOCK(variablelist);
  4692. }
  4693. /* Transmit the string in a "NEW" request */
  4694. add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
  4695. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
  4696. ast_mutex_unlock(&iaxsl[callno]);
  4697. ast_setstate(c, AST_STATE_RINGING);
  4698. return 0;
  4699. }
  4700. static int iax2_hangup(struct ast_channel *c)
  4701. {
  4702. unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
  4703. struct iax_ie_data ied;
  4704. int alreadygone;
  4705. memset(&ied, 0, sizeof(ied));
  4706. ast_mutex_lock(&iaxsl[callno]);
  4707. if (callno && iaxs[callno]) {
  4708. ast_debug(1, "We're hanging up %s now...\n", ast_channel_name(c));
  4709. alreadygone = ast_test_flag64(iaxs[callno], IAX_ALREADYGONE);
  4710. /* Send the hangup unless we have had a transmission error or are already gone */
  4711. iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)ast_channel_hangupcause(c));
  4712. if (!iaxs[callno]->error && !alreadygone) {
  4713. if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
  4714. ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
  4715. }
  4716. if (!iaxs[callno]) {
  4717. ast_mutex_unlock(&iaxsl[callno]);
  4718. return 0;
  4719. }
  4720. }
  4721. /* Explicitly predestroy it */
  4722. iax2_predestroy(callno);
  4723. /* If we were already gone to begin with, destroy us now */
  4724. if (iaxs[callno] && alreadygone) {
  4725. ast_debug(1, "Really destroying %s now...\n", ast_channel_name(c));
  4726. iax2_destroy(callno);
  4727. } else if (iaxs[callno]) {
  4728. if (ast_sched_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
  4729. ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!! Destroying immediately.\n", callno);
  4730. iax2_destroy(callno);
  4731. }
  4732. }
  4733. } else if (ast_channel_tech_pvt(c)) {
  4734. /* If this call no longer exists, but the channel still
  4735. * references it we need to set the channel's tech_pvt to null
  4736. * to avoid ast_channel_free() trying to free it.
  4737. */
  4738. ast_channel_tech_pvt_set(c, NULL);
  4739. }
  4740. ast_mutex_unlock(&iaxsl[callno]);
  4741. ast_verb(3, "Hungup '%s'\n", ast_channel_name(c));
  4742. return 0;
  4743. }
  4744. /*!
  4745. * \note expects the pvt to be locked
  4746. */
  4747. static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
  4748. {
  4749. unsigned short callno = pvt->callno;
  4750. if (!pvt->peercallno) {
  4751. /* We don't know the remote side's call number, yet. :( */
  4752. int count = 10;
  4753. while (count-- && pvt && !pvt->peercallno) {
  4754. DEADLOCK_AVOIDANCE(&iaxsl[callno]);
  4755. pvt = iaxs[callno];
  4756. }
  4757. if (!pvt || !pvt->peercallno) {
  4758. return -1;
  4759. }
  4760. }
  4761. return 0;
  4762. }
  4763. static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
  4764. {
  4765. struct ast_option_header *h;
  4766. int res;
  4767. switch (option) {
  4768. case AST_OPTION_TXGAIN:
  4769. case AST_OPTION_RXGAIN:
  4770. /* these two cannot be sent, because they require a result */
  4771. errno = ENOSYS;
  4772. return -1;
  4773. case AST_OPTION_OPRMODE:
  4774. errno = EINVAL;
  4775. return -1;
  4776. case AST_OPTION_SECURE_SIGNALING:
  4777. case AST_OPTION_SECURE_MEDIA:
  4778. {
  4779. unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
  4780. ast_mutex_lock(&iaxsl[callno]);
  4781. if ((*(int *) data)) {
  4782. ast_set_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
  4783. } else {
  4784. ast_clear_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
  4785. }
  4786. ast_mutex_unlock(&iaxsl[callno]);
  4787. return 0;
  4788. }
  4789. /* These options are sent to the other side across the network where
  4790. * they will be passed to whatever channel is bridged there. Don't
  4791. * do anything silly like pass an option that transmits pointers to
  4792. * memory on this machine to a remote machine to use */
  4793. case AST_OPTION_TONE_VERIFY:
  4794. case AST_OPTION_TDD:
  4795. case AST_OPTION_RELAXDTMF:
  4796. case AST_OPTION_AUDIO_MODE:
  4797. case AST_OPTION_DIGIT_DETECT:
  4798. case AST_OPTION_FAX_DETECT:
  4799. {
  4800. unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
  4801. struct chan_iax2_pvt *pvt;
  4802. ast_mutex_lock(&iaxsl[callno]);
  4803. pvt = iaxs[callno];
  4804. if (wait_for_peercallno(pvt)) {
  4805. ast_mutex_unlock(&iaxsl[callno]);
  4806. return -1;
  4807. }
  4808. ast_mutex_unlock(&iaxsl[callno]);
  4809. if (!(h = ast_malloc(datalen + sizeof(*h)))) {
  4810. return -1;
  4811. }
  4812. h->flag = AST_OPTION_FLAG_REQUEST;
  4813. h->option = htons(option);
  4814. memcpy(h->data, data, datalen);
  4815. res = send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_CONTROL,
  4816. AST_CONTROL_OPTION, 0, (unsigned char *) h,
  4817. datalen + sizeof(*h), -1);
  4818. ast_free(h);
  4819. return res;
  4820. }
  4821. default:
  4822. return -1;
  4823. }
  4824. /* Just in case someone does a break instead of a return */
  4825. return -1;
  4826. }
  4827. static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
  4828. {
  4829. switch (option) {
  4830. case AST_OPTION_SECURE_SIGNALING:
  4831. case AST_OPTION_SECURE_MEDIA:
  4832. {
  4833. unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
  4834. ast_mutex_lock(&iaxsl[callno]);
  4835. *((int *) data) = ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) ? 1 : 0;
  4836. ast_mutex_unlock(&iaxsl[callno]);
  4837. return 0;
  4838. }
  4839. default:
  4840. return -1;
  4841. }
  4842. }
  4843. static struct ast_frame *iax2_read(struct ast_channel *c)
  4844. {
  4845. ast_debug(1, "I should never be called!\n");
  4846. return &ast_null_frame;
  4847. }
  4848. static int iax2_key_rotate(const void *vpvt)
  4849. {
  4850. int res = 0;
  4851. struct chan_iax2_pvt *pvt = (void *) vpvt;
  4852. struct MD5Context md5;
  4853. char key[17] = "";
  4854. struct iax_ie_data ied = {
  4855. .pos = 0,
  4856. };
  4857. ast_mutex_lock(&iaxsl[pvt->callno]);
  4858. pvt->keyrotateid = ast_sched_add(sched, 120000 + (ast_random() % 180001), iax2_key_rotate, vpvt);
  4859. snprintf(key, sizeof(key), "%lX", (unsigned long)ast_random());
  4860. MD5Init(&md5);
  4861. MD5Update(&md5, (unsigned char *) key, strlen(key));
  4862. MD5Final((unsigned char *) key, &md5);
  4863. IAX_DEBUGDIGEST("Sending", key);
  4864. iax_ie_append_raw(&ied, IAX_IE_CHALLENGE, key, 16);
  4865. res = send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_RTKEY, 0, ied.buf, ied.pos, -1);
  4866. build_ecx_key((unsigned char *) key, pvt);
  4867. ast_mutex_unlock(&iaxsl[pvt->callno]);
  4868. return res;
  4869. }
  4870. static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
  4871. {
  4872. int res;
  4873. struct iax_ie_data ied0;
  4874. struct iax_ie_data ied1;
  4875. unsigned int transferid = (unsigned int)ast_random();
  4876. if (IAX_CALLENCRYPTED(iaxs[callno0]) || IAX_CALLENCRYPTED(iaxs[callno1])) {
  4877. ast_debug(1, "transfers are not supported for encrypted calls at this time\n");
  4878. ast_set_flag64(iaxs[callno0], IAX_NOTRANSFER);
  4879. ast_set_flag64(iaxs[callno1], IAX_NOTRANSFER);
  4880. return 0;
  4881. }
  4882. memset(&ied0, 0, sizeof(ied0));
  4883. iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
  4884. iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
  4885. iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
  4886. memset(&ied1, 0, sizeof(ied1));
  4887. iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
  4888. iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
  4889. iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
  4890. res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
  4891. if (res)
  4892. return -1;
  4893. res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
  4894. if (res)
  4895. return -1;
  4896. iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
  4897. iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
  4898. return 0;
  4899. }
  4900. static void lock_both(unsigned short callno0, unsigned short callno1)
  4901. {
  4902. ast_mutex_lock(&iaxsl[callno0]);
  4903. while (ast_mutex_trylock(&iaxsl[callno1])) {
  4904. DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
  4905. }
  4906. }
  4907. static void unlock_both(unsigned short callno0, unsigned short callno1)
  4908. {
  4909. ast_mutex_unlock(&iaxsl[callno1]);
  4910. ast_mutex_unlock(&iaxsl[callno0]);
  4911. }
  4912. static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
  4913. {
  4914. struct ast_channel *cs[3];
  4915. struct ast_channel *who, *other;
  4916. int to = -1;
  4917. int res = -1;
  4918. int transferstarted=0;
  4919. struct ast_frame *f;
  4920. unsigned short callno0 = PTR_TO_CALLNO(ast_channel_tech_pvt(c0));
  4921. unsigned short callno1 = PTR_TO_CALLNO(ast_channel_tech_pvt(c1));
  4922. struct timeval waittimer = {0, 0};
  4923. /* We currently do not support native bridging if a timeoutms value has been provided */
  4924. if (timeoutms > 0) {
  4925. return AST_BRIDGE_FAILED;
  4926. }
  4927. timeoutms = -1;
  4928. lock_both(callno0, callno1);
  4929. if (!iaxs[callno0] || !iaxs[callno1]) {
  4930. unlock_both(callno0, callno1);
  4931. return AST_BRIDGE_FAILED;
  4932. }
  4933. /* Put them in native bridge mode */
  4934. if (!(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
  4935. iaxs[callno0]->bridgecallno = callno1;
  4936. iaxs[callno1]->bridgecallno = callno0;
  4937. }
  4938. unlock_both(callno0, callno1);
  4939. /* If not, try to bridge until we can execute a transfer, if we can */
  4940. cs[0] = c0;
  4941. cs[1] = c1;
  4942. for (/* ever */;;) {
  4943. /* Check in case we got masqueraded into */
  4944. if ((ast_channel_tech(c0) != &iax2_tech) || (ast_channel_tech(c1) != &iax2_tech)) {
  4945. ast_verb(3, "Can't masquerade, we're different...\n");
  4946. /* Remove from native mode */
  4947. if (ast_channel_tech(c0) == &iax2_tech) {
  4948. ast_mutex_lock(&iaxsl[callno0]);
  4949. iaxs[callno0]->bridgecallno = 0;
  4950. ast_mutex_unlock(&iaxsl[callno0]);
  4951. }
  4952. if (ast_channel_tech(c1) == &iax2_tech) {
  4953. ast_mutex_lock(&iaxsl[callno1]);
  4954. iaxs[callno1]->bridgecallno = 0;
  4955. ast_mutex_unlock(&iaxsl[callno1]);
  4956. }
  4957. return AST_BRIDGE_FAILED_NOWARN;
  4958. }
  4959. if (!(ast_format_cap_identical(ast_channel_nativeformats(c0), ast_channel_nativeformats(c1)))) {
  4960. char buf0[256];
  4961. char buf1[256];
  4962. ast_getformatname_multiple(buf0, sizeof(buf0), ast_channel_nativeformats(c0));
  4963. ast_getformatname_multiple(buf1, sizeof(buf1), ast_channel_nativeformats(c1));
  4964. ast_verb(3, "Operating with different codecs [%s] [%s] , can't native bridge...\n", buf0, buf1);
  4965. /* Remove from native mode */
  4966. lock_both(callno0, callno1);
  4967. if (iaxs[callno0])
  4968. iaxs[callno0]->bridgecallno = 0;
  4969. if (iaxs[callno1])
  4970. iaxs[callno1]->bridgecallno = 0;
  4971. unlock_both(callno0, callno1);
  4972. return AST_BRIDGE_FAILED_NOWARN;
  4973. }
  4974. /* check if transferred and if we really want native bridging */
  4975. if (!transferstarted && !ast_test_flag64(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag64(iaxs[callno1], IAX_NOTRANSFER)) {
  4976. /* Try the transfer */
  4977. if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
  4978. ast_test_flag64(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag64(iaxs[callno1], IAX_TRANSFERMEDIA)))
  4979. ast_log(LOG_WARNING, "Unable to start the transfer\n");
  4980. transferstarted = 1;
  4981. }
  4982. if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
  4983. /* Call has been transferred. We're no longer involved */
  4984. struct timeval now = ast_tvnow();
  4985. if (ast_tvzero(waittimer)) {
  4986. waittimer = now;
  4987. } else if (now.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
  4988. ast_channel_softhangup_internal_flag_add(c0, AST_SOFTHANGUP_DEV);
  4989. ast_channel_softhangup_internal_flag_add(c1, AST_SOFTHANGUP_DEV);
  4990. *fo = NULL;
  4991. *rc = c0;
  4992. res = AST_BRIDGE_COMPLETE;
  4993. break;
  4994. }
  4995. }
  4996. to = 1000;
  4997. who = ast_waitfor_n(cs, 2, &to);
  4998. /* XXX This will need to be updated to calculate
  4999. * timeout correctly once timeoutms is allowed to be
  5000. * > 0. Right now, this can go badly if the waitfor
  5001. * times out in less than a millisecond
  5002. */
  5003. if (timeoutms > -1) {
  5004. timeoutms -= (1000 - to);
  5005. if (timeoutms < 0)
  5006. timeoutms = 0;
  5007. }
  5008. if (!who) {
  5009. if (!timeoutms) {
  5010. res = AST_BRIDGE_RETRY;
  5011. break;
  5012. }
  5013. if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
  5014. res = AST_BRIDGE_FAILED;
  5015. break;
  5016. }
  5017. continue;
  5018. }
  5019. f = ast_read(who);
  5020. if (!f) {
  5021. *fo = NULL;
  5022. *rc = who;
  5023. res = AST_BRIDGE_COMPLETE;
  5024. break;
  5025. }
  5026. other = (who == c0) ? c1 : c0; /* the 'other' channel */
  5027. if (f->frametype == AST_FRAME_CONTROL && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
  5028. switch (f->subclass.integer) {
  5029. case AST_CONTROL_VIDUPDATE:
  5030. case AST_CONTROL_SRCUPDATE:
  5031. case AST_CONTROL_SRCCHANGE:
  5032. case AST_CONTROL_T38_PARAMETERS:
  5033. ast_write(other, f);
  5034. break;
  5035. case AST_CONTROL_PVT_CAUSE_CODE:
  5036. ast_channel_hangupcause_hash_set(other, f->data.ptr, f->datalen);
  5037. break;
  5038. default:
  5039. *fo = f;
  5040. *rc = who;
  5041. res = AST_BRIDGE_COMPLETE;
  5042. break;
  5043. }
  5044. if (res == AST_BRIDGE_COMPLETE) {
  5045. break;
  5046. }
  5047. } else if (f->frametype == AST_FRAME_VOICE
  5048. || f->frametype == AST_FRAME_TEXT
  5049. || f->frametype == AST_FRAME_VIDEO
  5050. || f->frametype == AST_FRAME_IMAGE) {
  5051. ast_write(other, f);
  5052. } else if (f->frametype == AST_FRAME_DTMF) {
  5053. /* monitored dtmf take out of the bridge.
  5054. * check if we monitor the specific source.
  5055. */
  5056. int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
  5057. if (flags & monitored_source) {
  5058. *rc = who;
  5059. *fo = f;
  5060. res = AST_BRIDGE_COMPLETE;
  5061. /* Remove from native mode */
  5062. break;
  5063. }
  5064. ast_write(other, f);
  5065. }
  5066. ast_frfree(f);
  5067. /* Swap who gets priority */
  5068. cs[2] = cs[0];
  5069. cs[0] = cs[1];
  5070. cs[1] = cs[2];
  5071. }
  5072. lock_both(callno0, callno1);
  5073. if(iaxs[callno0])
  5074. iaxs[callno0]->bridgecallno = 0;
  5075. if(iaxs[callno1])
  5076. iaxs[callno1]->bridgecallno = 0;
  5077. unlock_both(callno0, callno1);
  5078. return res;
  5079. }
  5080. static int iax2_answer(struct ast_channel *c)
  5081. {
  5082. unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
  5083. ast_debug(1, "Answering IAX2 call\n");
  5084. ast_mutex_lock(&iaxsl[callno]);
  5085. if (iaxs[callno])
  5086. iax2_ami_channelupdate(iaxs[callno]);
  5087. ast_mutex_unlock(&iaxsl[callno]);
  5088. return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
  5089. }
  5090. static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
  5091. {
  5092. unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
  5093. struct chan_iax2_pvt *pvt;
  5094. int res = 0;
  5095. if (iaxdebug)
  5096. ast_debug(1, "Indicating condition %d\n", condition);
  5097. ast_mutex_lock(&iaxsl[callno]);
  5098. pvt = iaxs[callno];
  5099. if (wait_for_peercallno(pvt)) {
  5100. res = -1;
  5101. goto done;
  5102. }
  5103. switch (condition) {
  5104. case AST_CONTROL_HOLD:
  5105. if (strcasecmp(pvt->mohinterpret, "passthrough")) {
  5106. ast_moh_start(c, data, pvt->mohinterpret);
  5107. goto done;
  5108. }
  5109. break;
  5110. case AST_CONTROL_UNHOLD:
  5111. if (strcasecmp(pvt->mohinterpret, "passthrough")) {
  5112. ast_moh_stop(c);
  5113. goto done;
  5114. }
  5115. break;
  5116. case AST_CONTROL_CONNECTED_LINE:
  5117. case AST_CONTROL_REDIRECTING:
  5118. if (!ast_test_flag64(pvt, IAX_SENDCONNECTEDLINE)) {
  5119. /* We are not configured to allow sending these updates. */
  5120. ast_debug(2, "Callno %d: Config blocked sending control frame %d.\n",
  5121. callno, condition);
  5122. goto done;
  5123. }
  5124. break;
  5125. case AST_CONTROL_PVT_CAUSE_CODE:
  5126. res = -1;
  5127. goto done;
  5128. }
  5129. res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
  5130. done:
  5131. ast_mutex_unlock(&iaxsl[callno]);
  5132. return res;
  5133. }
  5134. static int iax2_transfer(struct ast_channel *c, const char *dest)
  5135. {
  5136. unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
  5137. struct iax_ie_data ied = { "", };
  5138. char tmp[256], *context;
  5139. enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
  5140. ast_copy_string(tmp, dest, sizeof(tmp));
  5141. context = strchr(tmp, '@');
  5142. if (context) {
  5143. *context = '\0';
  5144. context++;
  5145. }
  5146. iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
  5147. if (context)
  5148. iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
  5149. ast_debug(1, "Transferring '%s' to '%s'\n", ast_channel_name(c), dest);
  5150. ast_queue_control_data(c, AST_CONTROL_TRANSFER, &message, sizeof(message));
  5151. return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
  5152. }
  5153. static int iax2_getpeertrunk(struct sockaddr_in sin)
  5154. {
  5155. struct iax2_peer *peer;
  5156. int res = 0;
  5157. struct ao2_iterator i;
  5158. i = ao2_iterator_init(peers, 0);
  5159. while ((peer = ao2_iterator_next(&i))) {
  5160. struct sockaddr_in peer_addr;
  5161. ast_sockaddr_to_sin(&peer->addr, &peer_addr);
  5162. if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
  5163. (peer_addr.sin_port == sin.sin_port)) {
  5164. res = ast_test_flag64(peer, IAX_TRUNK);
  5165. peer_unref(peer);
  5166. break;
  5167. }
  5168. peer_unref(peer);
  5169. }
  5170. ao2_iterator_destroy(&i);
  5171. return res;
  5172. }
  5173. /*! \brief Create new call, interface with the PBX core */
  5174. static struct ast_channel *ast_iax2_new(int callno, int state, iax2_format capability, const char *linkedid, unsigned int cachable)
  5175. {
  5176. struct ast_channel *tmp;
  5177. struct chan_iax2_pvt *i;
  5178. struct ast_variable *v = NULL;
  5179. struct ast_format tmpfmt;
  5180. struct ast_callid *callid;
  5181. if (!(i = iaxs[callno])) {
  5182. ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
  5183. return NULL;
  5184. }
  5185. /* Don't hold call lock */
  5186. ast_mutex_unlock(&iaxsl[callno]);
  5187. tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, linkedid, i->amaflags, "IAX2/%s-%d", i->host, i->callno);
  5188. ast_mutex_lock(&iaxsl[callno]);
  5189. if (i != iaxs[callno]) {
  5190. if (tmp) {
  5191. /* unlock and relock iaxsl[callno] to preserve locking order */
  5192. ast_mutex_unlock(&iaxsl[callno]);
  5193. tmp = ast_channel_release(tmp);
  5194. ast_mutex_lock(&iaxsl[callno]);
  5195. }
  5196. return NULL;
  5197. }
  5198. iax2_ami_channelupdate(i);
  5199. if (!tmp) {
  5200. return NULL;
  5201. }
  5202. if ((callid = iaxs[callno]->callid)) {
  5203. ast_channel_callid_set(tmp, callid);
  5204. }
  5205. ast_channel_tech_set(tmp, &iax2_tech);
  5206. /* We can support any format by default, until we get restricted */
  5207. ast_format_cap_from_old_bitfield(ast_channel_nativeformats(tmp), capability);
  5208. ast_best_codec(ast_channel_nativeformats(tmp), &tmpfmt);
  5209. ast_format_copy(ast_channel_readformat(tmp), &tmpfmt);
  5210. ast_format_copy(ast_channel_rawreadformat(tmp), &tmpfmt);
  5211. ast_format_copy(ast_channel_writeformat(tmp), &tmpfmt);
  5212. ast_format_copy(ast_channel_rawwriteformat(tmp), &tmpfmt);
  5213. ast_channel_tech_pvt_set(tmp, CALLNO_TO_PTR(i->callno));
  5214. if (!ast_strlen_zero(i->parkinglot))
  5215. ast_channel_parkinglot_set(tmp, i->parkinglot);
  5216. /* Don't use ast_set_callerid() here because it will
  5217. * generate a NewCallerID event before the NewChannel event */
  5218. if (!ast_strlen_zero(i->ani)) {
  5219. ast_channel_caller(tmp)->ani.number.valid = 1;
  5220. ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->ani);
  5221. } else if (!ast_strlen_zero(i->cid_num)) {
  5222. ast_channel_caller(tmp)->ani.number.valid = 1;
  5223. ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->cid_num);
  5224. }
  5225. ast_channel_dialed(tmp)->number.str = ast_strdup(i->dnid);
  5226. if (!ast_strlen_zero(i->rdnis)) {
  5227. ast_channel_redirecting(tmp)->from.number.valid = 1;
  5228. ast_channel_redirecting(tmp)->from.number.str = ast_strdup(i->rdnis);
  5229. }
  5230. ast_channel_caller(tmp)->id.name.presentation = i->calling_pres;
  5231. ast_channel_caller(tmp)->id.number.presentation = i->calling_pres;
  5232. ast_channel_caller(tmp)->id.number.plan = i->calling_ton;
  5233. ast_channel_dialed(tmp)->transit_network_select = i->calling_tns;
  5234. if (!ast_strlen_zero(i->language))
  5235. ast_channel_language_set(tmp, i->language);
  5236. if (!ast_strlen_zero(i->accountcode))
  5237. ast_channel_accountcode_set(tmp, i->accountcode);
  5238. if (i->amaflags)
  5239. ast_channel_amaflags_set(tmp, i->amaflags);
  5240. ast_channel_context_set(tmp, i->context);
  5241. ast_channel_exten_set(tmp, i->exten);
  5242. if (i->adsi)
  5243. ast_channel_adsicpe_set(tmp, i->peeradsicpe);
  5244. else
  5245. ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
  5246. i->owner = tmp;
  5247. i->capability = capability;
  5248. if (!cachable) {
  5249. ast_set_flag(ast_channel_flags(tmp), AST_FLAG_DISABLE_DEVSTATE_CACHE);
  5250. }
  5251. /* Set inherited variables */
  5252. if (i->vars) {
  5253. for (v = i->vars ; v ; v = v->next)
  5254. pbx_builtin_setvar_helper(tmp, v->name, v->value);
  5255. }
  5256. if (i->iaxvars) {
  5257. struct ast_datastore *variablestore;
  5258. struct ast_variable *var, *prev = NULL;
  5259. AST_LIST_HEAD(, ast_var_t) *varlist;
  5260. ast_debug(1, "Loading up the channel with IAXVARs\n");
  5261. varlist = ast_calloc(1, sizeof(*varlist));
  5262. variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
  5263. if (variablestore && varlist) {
  5264. variablestore->data = varlist;
  5265. variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
  5266. AST_LIST_HEAD_INIT(varlist);
  5267. for (var = i->iaxvars; var; var = var->next) {
  5268. struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
  5269. if (prev)
  5270. ast_free(prev);
  5271. prev = var;
  5272. if (!newvar) {
  5273. /* Don't abort list traversal, as this would leave i->iaxvars in an inconsistent state. */
  5274. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  5275. } else {
  5276. AST_LIST_INSERT_TAIL(varlist, newvar, entries);
  5277. }
  5278. }
  5279. if (prev)
  5280. ast_free(prev);
  5281. i->iaxvars = NULL;
  5282. ast_channel_datastore_add(i->owner, variablestore);
  5283. } else {
  5284. if (variablestore) {
  5285. ast_datastore_free(variablestore);
  5286. }
  5287. if (varlist) {
  5288. ast_free(varlist);
  5289. }
  5290. }
  5291. }
  5292. if (state != AST_STATE_DOWN) {
  5293. if (ast_pbx_start(tmp)) {
  5294. ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
  5295. ast_hangup(tmp);
  5296. i->owner = NULL;
  5297. return NULL;
  5298. }
  5299. }
  5300. ast_module_ref(ast_module_info->self);
  5301. return tmp;
  5302. }
  5303. static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
  5304. {
  5305. unsigned long int mssincetx; /* unsigned to handle overflows */
  5306. long int ms, pred;
  5307. tpeer->trunkact = *now;
  5308. mssincetx = ast_tvdiff_ms(*now, tpeer->lasttxtime);
  5309. if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
  5310. /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
  5311. tpeer->txtrunktime = *now;
  5312. tpeer->lastsent = 999999;
  5313. }
  5314. /* Update last transmit time now */
  5315. tpeer->lasttxtime = *now;
  5316. /* Calculate ms offset */
  5317. ms = ast_tvdiff_ms(*now, tpeer->txtrunktime);
  5318. /* Predict from last value */
  5319. pred = tpeer->lastsent + sampms;
  5320. if (labs(ms - pred) < MAX_TIMESTAMP_SKEW)
  5321. ms = pred;
  5322. /* We never send the same timestamp twice, so fudge a little if we must */
  5323. if (ms == tpeer->lastsent)
  5324. ms = tpeer->lastsent + 1;
  5325. tpeer->lastsent = ms;
  5326. return ms;
  5327. }
  5328. static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
  5329. {
  5330. long ms; /* NOT unsigned */
  5331. if (ast_tvzero(iaxs[callno]->rxcore)) {
  5332. /* Initialize rxcore time if appropriate */
  5333. iaxs[callno]->rxcore = ast_tvnow();
  5334. /* Round to nearest 20ms so traces look pretty */
  5335. iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
  5336. }
  5337. /* Calculate difference between trunk and channel */
  5338. ms = ast_tvdiff_ms(*rxtrunktime, iaxs[callno]->rxcore);
  5339. /* Return as the sum of trunk time and the difference between trunk and real time */
  5340. return ms + ts;
  5341. }
  5342. static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
  5343. {
  5344. int ms;
  5345. int voice = 0;
  5346. int genuine = 0;
  5347. int adjust;
  5348. int rate = ast_format_rate(&f->subclass.format) / 1000;
  5349. struct timeval *delivery = NULL;
  5350. /* What sort of frame do we have?: voice is self-explanatory
  5351. "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
  5352. non-genuine frames are CONTROL frames [ringing etc], DTMF
  5353. The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
  5354. the others need a timestamp slaved to the voice frames so that they go in sequence
  5355. */
  5356. if (f->frametype == AST_FRAME_VOICE) {
  5357. voice = 1;
  5358. delivery = &f->delivery;
  5359. } else if (f->frametype == AST_FRAME_IAX) {
  5360. genuine = 1;
  5361. } else if (f->frametype == AST_FRAME_CNG) {
  5362. p->notsilenttx = 0;
  5363. }
  5364. if (ast_tvzero(p->offset)) {
  5365. p->offset = ast_tvnow();
  5366. /* Round to nearest 20ms for nice looking traces */
  5367. p->offset.tv_usec -= p->offset.tv_usec % 20000;
  5368. }
  5369. /* If the timestamp is specified, just send it as is */
  5370. if (ts)
  5371. return ts;
  5372. /* If we have a time that the frame arrived, always use it to make our timestamp */
  5373. if (delivery && !ast_tvzero(*delivery)) {
  5374. ms = ast_tvdiff_ms(*delivery, p->offset);
  5375. if (ms < 0) {
  5376. ms = 0;
  5377. }
  5378. if (iaxdebug)
  5379. ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
  5380. } else {
  5381. ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
  5382. if (ms < 0)
  5383. ms = 0;
  5384. if (voice) {
  5385. /* On a voice frame, use predicted values if appropriate */
  5386. adjust = (ms - p->nextpred);
  5387. if (p->notsilenttx && abs(adjust) <= MAX_TIMESTAMP_SKEW) {
  5388. /* Adjust our txcore, keeping voice and non-voice synchronized */
  5389. /* AN EXPLANATION:
  5390. When we send voice, we usually send "calculated" timestamps worked out
  5391. on the basis of the number of samples sent. When we send other frames,
  5392. we usually send timestamps worked out from the real clock.
  5393. The problem is that they can tend to drift out of step because the
  5394. source channel's clock and our clock may not be exactly at the same rate.
  5395. We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
  5396. for this call. Moving it adjusts timestamps for non-voice frames.
  5397. We make the adjustment in the style of a moving average. Each time we
  5398. adjust p->offset by 10% of the difference between our clock-derived
  5399. timestamp and the predicted timestamp. That's why you see "10000"
  5400. below even though IAX2 timestamps are in milliseconds.
  5401. The use of a moving average avoids offset moving too radically.
  5402. Generally, "adjust" roams back and forth around 0, with offset hardly
  5403. changing at all. But if a consistent different starts to develop it
  5404. will be eliminated over the course of 10 frames (200-300msecs)
  5405. */
  5406. if (adjust < 0)
  5407. p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
  5408. else if (adjust > 0)
  5409. p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
  5410. if (!p->nextpred) {
  5411. p->nextpred = ms; /*f->samples / rate;*/
  5412. if (p->nextpred <= p->lastsent)
  5413. p->nextpred = p->lastsent + 3;
  5414. }
  5415. ms = p->nextpred;
  5416. } else {
  5417. /* in this case, just use the actual
  5418. * time, since we're either way off
  5419. * (shouldn't happen), or we're ending a
  5420. * silent period -- and seed the next
  5421. * predicted time. Also, round ms to the
  5422. * next multiple of frame size (so our
  5423. * silent periods are multiples of
  5424. * frame size too) */
  5425. if (iaxdebug && abs(adjust) > MAX_TIMESTAMP_SKEW )
  5426. ast_debug(1, "predicted timestamp skew (%d) > max (%d), using real ts instead.\n",
  5427. abs(adjust), MAX_TIMESTAMP_SKEW);
  5428. if (f->samples >= rate) /* check to make sure we don't core dump */
  5429. {
  5430. int diff = ms % (f->samples / rate);
  5431. if (diff)
  5432. ms += f->samples/rate - diff;
  5433. }
  5434. p->nextpred = ms;
  5435. p->notsilenttx = 1;
  5436. }
  5437. } else if ( f->frametype == AST_FRAME_VIDEO ) {
  5438. /*
  5439. * IAX2 draft 03 says that timestamps MUST be in order.
  5440. * It does not say anything about several frames having the same timestamp
  5441. * When transporting video, we can have a frame that spans multiple iax packets
  5442. * (so called slices), so it would make sense to use the same timestamp for all of
  5443. * them
  5444. * We do want to make sure that frames don't go backwards though
  5445. */
  5446. if ( (unsigned int)ms < p->lastsent )
  5447. ms = p->lastsent;
  5448. } else {
  5449. /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
  5450. it's a genuine frame */
  5451. adjust = (ms - p->lastsent);
  5452. if (genuine) {
  5453. /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
  5454. if (ms <= p->lastsent)
  5455. ms = p->lastsent + 3;
  5456. } else if (abs(adjust) <= MAX_TIMESTAMP_SKEW) {
  5457. /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
  5458. ms = p->lastsent + 3;
  5459. }
  5460. }
  5461. }
  5462. p->lastsent = ms;
  5463. if (voice)
  5464. p->nextpred = p->nextpred + f->samples / rate;
  5465. return ms;
  5466. }
  5467. static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
  5468. {
  5469. /* Returns where in "receive time" we are. That is, how many ms
  5470. since we received (or would have received) the frame with timestamp 0 */
  5471. int ms;
  5472. #ifdef IAXTESTS
  5473. int jit;
  5474. #endif /* IAXTESTS */
  5475. /* Setup rxcore if necessary */
  5476. if (ast_tvzero(p->rxcore)) {
  5477. p->rxcore = ast_tvnow();
  5478. if (iaxdebug)
  5479. ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %ums\n",
  5480. p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
  5481. p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
  5482. #if 1
  5483. if (iaxdebug)
  5484. ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
  5485. p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
  5486. #endif
  5487. }
  5488. ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
  5489. #ifdef IAXTESTS
  5490. if (test_jit) {
  5491. if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
  5492. jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
  5493. if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
  5494. jit = -jit;
  5495. ms += jit;
  5496. }
  5497. }
  5498. if (test_late) {
  5499. ms += test_late;
  5500. test_late = 0;
  5501. }
  5502. #endif /* IAXTESTS */
  5503. return ms;
  5504. }
  5505. static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
  5506. {
  5507. struct iax2_trunk_peer *tpeer = NULL;
  5508. /* Finds and locks trunk peer */
  5509. AST_LIST_LOCK(&tpeers);
  5510. AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
  5511. if (!inaddrcmp(&tpeer->addr, sin)) {
  5512. ast_mutex_lock(&tpeer->lock);
  5513. break;
  5514. }
  5515. }
  5516. if (!tpeer) {
  5517. if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
  5518. ast_mutex_init(&tpeer->lock);
  5519. tpeer->lastsent = 9999;
  5520. memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
  5521. tpeer->trunkact = ast_tvnow();
  5522. ast_mutex_lock(&tpeer->lock);
  5523. tpeer->sockfd = fd;
  5524. #ifdef SO_NO_CHECK
  5525. setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
  5526. #endif
  5527. ast_debug(1, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
  5528. AST_LIST_INSERT_TAIL(&tpeers, tpeer, list);
  5529. }
  5530. }
  5531. AST_LIST_UNLOCK(&tpeers);
  5532. return tpeer;
  5533. }
  5534. static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
  5535. {
  5536. struct ast_frame *f;
  5537. struct iax2_trunk_peer *tpeer;
  5538. void *tmp, *ptr;
  5539. struct timeval now;
  5540. struct ast_iax2_meta_trunk_entry *met;
  5541. struct ast_iax2_meta_trunk_mini *mtm;
  5542. f = &fr->af;
  5543. tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
  5544. if (tpeer) {
  5545. if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
  5546. /* Need to reallocate space */
  5547. if (tpeer->trunkdataalloc < trunkmaxsize) {
  5548. if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
  5549. ast_mutex_unlock(&tpeer->lock);
  5550. return -1;
  5551. }
  5552. tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
  5553. tpeer->trunkdata = tmp;
  5554. ast_debug(1, "Expanded trunk '%s:%d' to %u bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), tpeer->trunkdataalloc);
  5555. } else {
  5556. ast_log(LOG_WARNING, "Maximum trunk data space exceeded to %s:%d\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
  5557. ast_mutex_unlock(&tpeer->lock);
  5558. return -1;
  5559. }
  5560. }
  5561. /* Append to meta frame */
  5562. ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
  5563. if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS)) {
  5564. mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
  5565. mtm->len = htons(f->datalen);
  5566. mtm->mini.callno = htons(pvt->callno);
  5567. mtm->mini.ts = htons(0xffff & fr->ts);
  5568. ptr += sizeof(struct ast_iax2_meta_trunk_mini);
  5569. tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
  5570. } else {
  5571. met = (struct ast_iax2_meta_trunk_entry *)ptr;
  5572. /* Store call number and length in meta header */
  5573. met->callno = htons(pvt->callno);
  5574. met->len = htons(f->datalen);
  5575. /* Advance pointers/decrease length past trunk entry header */
  5576. ptr += sizeof(struct ast_iax2_meta_trunk_entry);
  5577. tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
  5578. }
  5579. /* Copy actual trunk data */
  5580. memcpy(ptr, f->data.ptr, f->datalen);
  5581. tpeer->trunkdatalen += f->datalen;
  5582. tpeer->calls++;
  5583. /* track the largest mtu we actually have sent */
  5584. if (tpeer->trunkdatalen + f->datalen + 4 > trunk_maxmtu)
  5585. trunk_maxmtu = tpeer->trunkdatalen + f->datalen + 4 ;
  5586. /* if we have enough for a full MTU, ship it now without waiting */
  5587. if (global_max_trunk_mtu > 0 && tpeer->trunkdatalen + f->datalen + 4 >= global_max_trunk_mtu) {
  5588. now = ast_tvnow();
  5589. send_trunk(tpeer, &now);
  5590. trunk_untimed ++;
  5591. }
  5592. ast_mutex_unlock(&tpeer->lock);
  5593. }
  5594. return 0;
  5595. }
  5596. /* IAX2 encryption requires 16 to 32 bytes of random padding to be present
  5597. * before the encryption data. This function randomizes that data. */
  5598. static void build_rand_pad(unsigned char *buf, ssize_t len)
  5599. {
  5600. long tmp;
  5601. for (tmp = ast_random(); len > 0; tmp = ast_random()) {
  5602. memcpy(buf, (unsigned char *) &tmp, (len > sizeof(tmp)) ? sizeof(tmp) : len);
  5603. buf += sizeof(tmp);
  5604. len -= sizeof(tmp);
  5605. }
  5606. }
  5607. static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
  5608. {
  5609. build_ecx_key(digest, pvt);
  5610. ast_aes_set_decrypt_key(digest, &pvt->dcx);
  5611. }
  5612. static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
  5613. {
  5614. /* it is required to hold the corresponding decrypt key to our encrypt key
  5615. * in the pvt struct because queued frames occasionally need to be decrypted and
  5616. * re-encrypted when updated for a retransmission */
  5617. build_rand_pad(pvt->semirand, sizeof(pvt->semirand));
  5618. ast_aes_set_encrypt_key(digest, &pvt->ecx);
  5619. ast_aes_set_decrypt_key(digest, &pvt->mydcx);
  5620. }
  5621. static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
  5622. {
  5623. #if 0
  5624. /* Debug with "fake encryption" */
  5625. int x;
  5626. if (len % 16)
  5627. ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
  5628. for (x=0;x<len;x++)
  5629. dst[x] = src[x] ^ 0xff;
  5630. #else
  5631. unsigned char lastblock[16] = { 0 };
  5632. int x;
  5633. while(len > 0) {
  5634. ast_aes_decrypt(src, dst, dcx);
  5635. for (x=0;x<16;x++)
  5636. dst[x] ^= lastblock[x];
  5637. memcpy(lastblock, src, sizeof(lastblock));
  5638. dst += 16;
  5639. src += 16;
  5640. len -= 16;
  5641. }
  5642. #endif
  5643. }
  5644. static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
  5645. {
  5646. #if 0
  5647. /* Debug with "fake encryption" */
  5648. int x;
  5649. if (len % 16)
  5650. ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
  5651. for (x=0;x<len;x++)
  5652. dst[x] = src[x] ^ 0xff;
  5653. #else
  5654. unsigned char curblock[16] = { 0 };
  5655. int x;
  5656. while(len > 0) {
  5657. for (x=0;x<16;x++)
  5658. curblock[x] ^= src[x];
  5659. ast_aes_encrypt(curblock, dst, ecx);
  5660. memcpy(curblock, dst, sizeof(curblock));
  5661. dst += 16;
  5662. src += 16;
  5663. len -= 16;
  5664. }
  5665. #endif
  5666. }
  5667. static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
  5668. {
  5669. int padding;
  5670. unsigned char *workspace;
  5671. workspace = ast_alloca(*datalen);
  5672. memset(f, 0, sizeof(*f));
  5673. if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
  5674. struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
  5675. if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
  5676. return -1;
  5677. /* Decrypt */
  5678. memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
  5679. padding = 16 + (workspace[15] & 0x0f);
  5680. if (iaxdebug)
  5681. ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02hhx)\n", *datalen, padding, workspace[15]);
  5682. if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
  5683. return -1;
  5684. *datalen -= padding;
  5685. memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
  5686. f->frametype = fh->type;
  5687. if (f->frametype == AST_FRAME_VIDEO) {
  5688. ast_format_from_old_bitfield(&f->subclass.format, (uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1)));
  5689. } else if (f->frametype == AST_FRAME_VOICE) {
  5690. ast_format_from_old_bitfield(&f->subclass.format, uncompress_subclass(fh->csub));
  5691. } else {
  5692. f->subclass.integer = uncompress_subclass(fh->csub);
  5693. }
  5694. } else {
  5695. struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
  5696. if (iaxdebug)
  5697. ast_debug(1, "Decoding mini with length %d\n", *datalen);
  5698. if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
  5699. return -1;
  5700. /* Decrypt */
  5701. memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
  5702. padding = 16 + (workspace[15] & 0x0f);
  5703. if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
  5704. return -1;
  5705. *datalen -= padding;
  5706. memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
  5707. }
  5708. return 0;
  5709. }
  5710. static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
  5711. {
  5712. int padding;
  5713. unsigned char *workspace;
  5714. workspace = ast_alloca(*datalen + 32);
  5715. if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
  5716. struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
  5717. if (iaxdebug)
  5718. ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
  5719. padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
  5720. padding = 16 + (padding & 0xf);
  5721. memcpy(workspace, poo, padding);
  5722. memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
  5723. workspace[15] &= 0xf0;
  5724. workspace[15] |= (padding & 0xf);
  5725. if (iaxdebug)
  5726. ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02hhx)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
  5727. *datalen += padding;
  5728. memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
  5729. if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
  5730. memcpy(poo, workspace + *datalen - 32, 32);
  5731. } else {
  5732. struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
  5733. if (iaxdebug)
  5734. ast_debug(1, "Encoding mini frame with length %d\n", *datalen);
  5735. padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
  5736. padding = 16 + (padding & 0xf);
  5737. memcpy(workspace, poo, padding);
  5738. memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
  5739. workspace[15] &= 0xf0;
  5740. workspace[15] |= (padding & 0x0f);
  5741. *datalen += padding;
  5742. memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
  5743. if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
  5744. memcpy(poo, workspace + *datalen - 32, 32);
  5745. }
  5746. return 0;
  5747. }
  5748. static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
  5749. {
  5750. int res=-1;
  5751. if (!ast_test_flag64(iaxs[callno], IAX_KEYPOPULATED)) {
  5752. /* Search for possible keys, given secrets */
  5753. struct MD5Context md5;
  5754. unsigned char digest[16];
  5755. char *tmppw, *stringp;
  5756. tmppw = ast_strdupa(iaxs[callno]->secret);
  5757. stringp = tmppw;
  5758. while ((tmppw = strsep(&stringp, ";"))) {
  5759. MD5Init(&md5);
  5760. MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
  5761. MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
  5762. MD5Final(digest, &md5);
  5763. build_encryption_keys(digest, iaxs[callno]);
  5764. res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
  5765. if (!res) {
  5766. ast_set_flag64(iaxs[callno], IAX_KEYPOPULATED);
  5767. break;
  5768. }
  5769. }
  5770. } else
  5771. res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
  5772. return res;
  5773. }
  5774. static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
  5775. {
  5776. /* Queue a packet for delivery on a given private structure. Use "ts" for
  5777. timestamp, or calculate if ts is 0. Send immediately without retransmission
  5778. or delayed, with retransmission */
  5779. struct ast_iax2_full_hdr *fh;
  5780. struct ast_iax2_mini_hdr *mh;
  5781. struct ast_iax2_video_hdr *vh;
  5782. struct {
  5783. struct iax_frame fr2;
  5784. unsigned char buffer[4096];
  5785. } frb;
  5786. struct iax_frame *fr;
  5787. int res;
  5788. int sendmini=0;
  5789. unsigned int lastsent;
  5790. unsigned int fts;
  5791. frb.fr2.afdatalen = sizeof(frb.buffer);
  5792. if (!pvt) {
  5793. ast_log(LOG_WARNING, "No private structure for packet?\n");
  5794. return -1;
  5795. }
  5796. lastsent = pvt->lastsent;
  5797. /* Calculate actual timestamp */
  5798. fts = calc_timestamp(pvt, ts, f);
  5799. /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
  5800. * (the endpoint should detect the lost packet itself). But, we want to do this here, so that we
  5801. * increment the "predicted timestamps" for voice, if we're predicting */
  5802. if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
  5803. return 0;
  5804. #if 0
  5805. ast_log(LOG_NOTICE,
  5806. "f->frametype %c= AST_FRAME_VOICE, %sencrypted, %srotation scheduled...\n",
  5807. *("=!" + (f->frametype == AST_FRAME_VOICE)),
  5808. IAX_CALLENCRYPTED(pvt) ? "" : "not ",
  5809. pvt->keyrotateid != -1 ? "" : "no "
  5810. );
  5811. #endif
  5812. if (pvt->keyrotateid == -1 && f->frametype == AST_FRAME_VOICE && IAX_CALLENCRYPTED(pvt)) {
  5813. iax2_key_rotate(pvt);
  5814. }
  5815. if ((ast_test_flag64(pvt, IAX_TRUNK) ||
  5816. (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
  5817. ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
  5818. /* High two bytes are the same on timestamp, or sending on a trunk */ &&
  5819. (f->frametype == AST_FRAME_VOICE)
  5820. /* is a voice frame */ &&
  5821. (f->subclass.format.id == ast_format_id_from_old_bitfield(pvt->svoiceformat))
  5822. /* is the same type */ ) {
  5823. /* Force immediate rather than delayed transmission */
  5824. now = 1;
  5825. /* Mark that mini-style frame is appropriate */
  5826. sendmini = 1;
  5827. }
  5828. if ( f->frametype == AST_FRAME_VIDEO ) {
  5829. /*
  5830. * If the lower 15 bits of the timestamp roll over, or if
  5831. * the video format changed then send a full frame.
  5832. * Otherwise send a mini video frame
  5833. */
  5834. if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
  5835. ((f->subclass.format.id) == ast_format_id_from_old_bitfield(pvt->svideoformat))
  5836. ) {
  5837. now = 1;
  5838. sendmini = 1;
  5839. } else {
  5840. now = 0;
  5841. sendmini = 0;
  5842. }
  5843. pvt->lastvsent = fts;
  5844. }
  5845. if (f->frametype == AST_FRAME_IAX) {
  5846. /* 0x8000 marks this message as TX:, this bit will be stripped later */
  5847. pvt->last_iax_message = f->subclass.integer | MARK_IAX_SUBCLASS_TX;
  5848. if (!pvt->first_iax_message) {
  5849. pvt->first_iax_message = pvt->last_iax_message;
  5850. }
  5851. }
  5852. /* Allocate an iax_frame */
  5853. if (now) {
  5854. fr = &frb.fr2;
  5855. } else
  5856. fr = iax_frame_new(DIRECTION_OUTGRESS, ast_test_flag64(pvt, IAX_ENCRYPTED) ? f->datalen + 32 : f->datalen, (f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_VIDEO));
  5857. if (!fr) {
  5858. ast_log(LOG_WARNING, "Out of memory\n");
  5859. return -1;
  5860. }
  5861. /* Copy our prospective frame into our immediate or retransmitted wrapper */
  5862. iax_frame_wrap(fr, f);
  5863. fr->ts = fts;
  5864. fr->callno = pvt->callno;
  5865. fr->transfer = transfer;
  5866. fr->final = final;
  5867. fr->encmethods = 0;
  5868. if (!sendmini) {
  5869. /* We need a full frame */
  5870. if (seqno > -1)
  5871. fr->oseqno = seqno;
  5872. else
  5873. fr->oseqno = pvt->oseqno++;
  5874. fr->iseqno = pvt->iseqno;
  5875. fh = (struct ast_iax2_full_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_full_hdr));
  5876. fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
  5877. fh->ts = htonl(fr->ts);
  5878. fh->oseqno = fr->oseqno;
  5879. if (transfer) {
  5880. fh->iseqno = 0;
  5881. } else
  5882. fh->iseqno = fr->iseqno;
  5883. /* Keep track of the last thing we've acknowledged */
  5884. if (!transfer)
  5885. pvt->aseqno = fr->iseqno;
  5886. fh->type = fr->af.frametype & 0xFF;
  5887. if (fr->af.frametype == AST_FRAME_VIDEO) {
  5888. iax2_format tmpfmt = ast_format_to_old_bitfield(&fr->af.subclass.format);
  5889. tmpfmt |= ast_format_get_video_mark(&fr->af.subclass.format) ? 0x1LL : 0;
  5890. fh->csub = compress_subclass(tmpfmt | ((tmpfmt & 0x1LL) << 6));
  5891. } else if (fr->af.frametype == AST_FRAME_VOICE) {
  5892. fh->csub = compress_subclass(ast_format_to_old_bitfield(&fr->af.subclass.format));
  5893. } else {
  5894. fh->csub = compress_subclass(fr->af.subclass.integer);
  5895. }
  5896. if (transfer) {
  5897. fr->dcallno = pvt->transfercallno;
  5898. } else
  5899. fr->dcallno = pvt->peercallno;
  5900. fh->dcallno = htons(fr->dcallno);
  5901. fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
  5902. fr->data = fh;
  5903. fr->retries = 0;
  5904. /* Retry after 2x the ping time has passed */
  5905. fr->retrytime = pvt->pingtime * 2;
  5906. if (fr->retrytime < MIN_RETRY_TIME)
  5907. fr->retrytime = MIN_RETRY_TIME;
  5908. if (fr->retrytime > MAX_RETRY_TIME)
  5909. fr->retrytime = MAX_RETRY_TIME;
  5910. /* Acks' don't get retried */
  5911. if ((f->frametype == AST_FRAME_IAX) && (f->subclass.integer == IAX_COMMAND_ACK))
  5912. fr->retries = -1;
  5913. else if (f->frametype == AST_FRAME_VOICE)
  5914. pvt->svoiceformat = ast_format_to_old_bitfield(&f->subclass.format);
  5915. else if (f->frametype == AST_FRAME_VIDEO)
  5916. pvt->svideoformat = ast_format_to_old_bitfield(&f->subclass.format);
  5917. if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
  5918. if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
  5919. if (fr->transfer)
  5920. iax_outputframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
  5921. else
  5922. iax_outputframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
  5923. encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
  5924. fr->encmethods = pvt->encmethods;
  5925. fr->ecx = pvt->ecx;
  5926. fr->mydcx = pvt->mydcx;
  5927. memcpy(fr->semirand, pvt->semirand, sizeof(fr->semirand));
  5928. } else
  5929. ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
  5930. }
  5931. if (now) {
  5932. res = send_packet(fr);
  5933. } else
  5934. res = iax2_transmit(fr);
  5935. } else {
  5936. if (ast_test_flag64(pvt, IAX_TRUNK)) {
  5937. iax2_trunk_queue(pvt, fr);
  5938. res = 0;
  5939. } else if (fr->af.frametype == AST_FRAME_VIDEO) {
  5940. /* Video frame have no sequence number */
  5941. fr->oseqno = -1;
  5942. fr->iseqno = -1;
  5943. vh = (struct ast_iax2_video_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_video_hdr));
  5944. vh->zeros = 0;
  5945. vh->callno = htons(0x8000 | fr->callno);
  5946. vh->ts = htons((fr->ts & 0x7FFF) | (ast_format_get_video_mark(&fr->af.subclass.format) ? 0x8000 : 0));
  5947. fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
  5948. fr->data = vh;
  5949. fr->retries = -1;
  5950. res = send_packet(fr);
  5951. } else {
  5952. /* Mini-frames have no sequence number */
  5953. fr->oseqno = -1;
  5954. fr->iseqno = -1;
  5955. /* Mini frame will do */
  5956. mh = (struct ast_iax2_mini_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_mini_hdr));
  5957. mh->callno = htons(fr->callno);
  5958. mh->ts = htons(fr->ts & 0xFFFF);
  5959. fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
  5960. fr->data = mh;
  5961. fr->retries = -1;
  5962. if (pvt->transferring == TRANSFER_MEDIAPASS)
  5963. fr->transfer = 1;
  5964. if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
  5965. if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
  5966. encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
  5967. } else
  5968. ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
  5969. }
  5970. res = send_packet(fr);
  5971. }
  5972. }
  5973. return res;
  5974. }
  5975. static char *handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  5976. {
  5977. regex_t regexbuf;
  5978. int havepattern = 0;
  5979. #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
  5980. #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
  5981. struct iax2_user *user = NULL;
  5982. char auth[90];
  5983. char *pstr = "";
  5984. struct ao2_iterator i;
  5985. switch (cmd) {
  5986. case CLI_INIT:
  5987. e->command = "iax2 show users [like]";
  5988. e->usage =
  5989. "Usage: iax2 show users [like <pattern>]\n"
  5990. " Lists all known IAX2 users.\n"
  5991. " Optional regular expression pattern is used to filter the user list.\n";
  5992. return NULL;
  5993. case CLI_GENERATE:
  5994. return NULL;
  5995. }
  5996. switch (a->argc) {
  5997. case 5:
  5998. if (!strcasecmp(a->argv[3], "like")) {
  5999. if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
  6000. return CLI_SHOWUSAGE;
  6001. havepattern = 1;
  6002. } else
  6003. return CLI_SHOWUSAGE;
  6004. case 3:
  6005. break;
  6006. default:
  6007. return CLI_SHOWUSAGE;
  6008. }
  6009. ast_cli(a->fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
  6010. i = ao2_iterator_init(users, 0);
  6011. for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
  6012. if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
  6013. continue;
  6014. if (!ast_strlen_zero(user->secret)) {
  6015. ast_copy_string(auth,user->secret, sizeof(auth));
  6016. } else if (!ast_strlen_zero(user->inkeys)) {
  6017. snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
  6018. } else
  6019. ast_copy_string(auth, "-no secret-", sizeof(auth));
  6020. if(ast_test_flag64(user, IAX_CODEC_NOCAP))
  6021. pstr = "REQ Only";
  6022. else if(ast_test_flag64(user, IAX_CODEC_NOPREFS))
  6023. pstr = "Disabled";
  6024. else
  6025. pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
  6026. ast_cli(a->fd, FORMAT2, user->name, auth, user->authmethods,
  6027. user->contexts ? user->contexts->context : DEFAULT_CONTEXT,
  6028. ast_acl_list_is_empty(user->acl) ? "No" : "Yes", pstr);
  6029. }
  6030. ao2_iterator_destroy(&i);
  6031. if (havepattern)
  6032. regfree(&regexbuf);
  6033. return CLI_SUCCESS;
  6034. #undef FORMAT
  6035. #undef FORMAT2
  6036. }
  6037. static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char * const argv[])
  6038. {
  6039. regex_t regexbuf;
  6040. int havepattern = 0;
  6041. int total_peers = 0;
  6042. int online_peers = 0;
  6043. int offline_peers = 0;
  6044. int unmonitored_peers = 0;
  6045. struct ao2_iterator i;
  6046. #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %s %-11s %-32.32s\n"
  6047. #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %s %-11s %-32.32s\n"
  6048. struct iax2_peer *peer = NULL;
  6049. char name[256];
  6050. struct ast_str *encmethods = ast_str_alloca(256);
  6051. int registeredonly=0;
  6052. char idtext[256] = "";
  6053. switch (argc) {
  6054. case 6:
  6055. if (!strcasecmp(argv[3], "registered"))
  6056. registeredonly = 1;
  6057. else
  6058. return RESULT_SHOWUSAGE;
  6059. if (!strcasecmp(argv[4], "like")) {
  6060. if (regcomp(&regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
  6061. return RESULT_SHOWUSAGE;
  6062. havepattern = 1;
  6063. } else
  6064. return RESULT_SHOWUSAGE;
  6065. break;
  6066. case 5:
  6067. if (!strcasecmp(argv[3], "like")) {
  6068. if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
  6069. return RESULT_SHOWUSAGE;
  6070. havepattern = 1;
  6071. } else
  6072. return RESULT_SHOWUSAGE;
  6073. break;
  6074. case 4:
  6075. if (!strcasecmp(argv[3], "registered"))
  6076. registeredonly = 1;
  6077. else
  6078. return RESULT_SHOWUSAGE;
  6079. break;
  6080. case 3:
  6081. break;
  6082. default:
  6083. return RESULT_SHOWUSAGE;
  6084. }
  6085. if (!s)
  6086. ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", "Description");
  6087. i = ao2_iterator_init(peers, 0);
  6088. for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
  6089. char nm[20];
  6090. char status[20];
  6091. int retstatus;
  6092. struct sockaddr_in peer_addr;
  6093. ast_sockaddr_to_sin(&peer->addr, &peer_addr);
  6094. if (registeredonly && !peer_addr.sin_addr.s_addr) {
  6095. continue;
  6096. }
  6097. if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
  6098. continue;
  6099. }
  6100. if (!ast_strlen_zero(peer->username))
  6101. snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
  6102. else
  6103. ast_copy_string(name, peer->name, sizeof(name));
  6104. encmethods_to_str(peer->encmethods, &encmethods);
  6105. retstatus = peer_status(peer, status, sizeof(status));
  6106. if (retstatus > 0)
  6107. online_peers++;
  6108. else if (!retstatus)
  6109. offline_peers++;
  6110. else
  6111. unmonitored_peers++;
  6112. ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
  6113. if (s) {
  6114. astman_append(s,
  6115. "Event: PeerEntry\r\n%s"
  6116. "Channeltype: IAX2\r\n"
  6117. "ObjectName: %s\r\n"
  6118. "ChanObjectType: peer\r\n"
  6119. "IPaddress: %s\r\n"
  6120. "IPport: %d\r\n"
  6121. "Dynamic: %s\r\n"
  6122. "Trunk: %s\r\n"
  6123. "Encryption: %s\r\n"
  6124. "Status: %s\r\n"
  6125. "Description: %s\r\n\r\n",
  6126. idtext,
  6127. name,
  6128. ast_sockaddr_stringify_addr(&peer->addr),
  6129. ast_sockaddr_port(&peer->addr),
  6130. ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no",
  6131. ast_test_flag64(peer, IAX_TRUNK) ? "yes" : "no",
  6132. peer->encmethods ? ast_str_buffer(encmethods) : "no",
  6133. status,
  6134. peer->description);
  6135. } else {
  6136. ast_cli(fd, FORMAT, name,
  6137. ast_sockaddr_stringify_addr(&peer->addr),
  6138. ast_test_flag64(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
  6139. nm,
  6140. ast_sockaddr_port(&peer->addr),
  6141. ast_test_flag64(peer, IAX_TRUNK) ? "(T)" : " ",
  6142. peer->encmethods ? "(E)" : " ",
  6143. status,
  6144. peer->description);
  6145. }
  6146. total_peers++;
  6147. }
  6148. ao2_iterator_destroy(&i);
  6149. if (!s)
  6150. ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]\n",
  6151. total_peers, online_peers, offline_peers, unmonitored_peers);
  6152. if (havepattern)
  6153. regfree(&regexbuf);
  6154. if (total)
  6155. *total = total_peers;
  6156. return RESULT_SUCCESS;
  6157. #undef FORMAT
  6158. #undef FORMAT2
  6159. }
  6160. static char *handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  6161. {
  6162. struct iax2_thread *thread = NULL;
  6163. time_t t;
  6164. int threadcount = 0, dynamiccount = 0;
  6165. char type;
  6166. switch (cmd) {
  6167. case CLI_INIT:
  6168. e->command = "iax2 show threads";
  6169. e->usage =
  6170. "Usage: iax2 show threads\n"
  6171. " Lists status of IAX helper threads\n";
  6172. return NULL;
  6173. case CLI_GENERATE:
  6174. return NULL;
  6175. }
  6176. if (a->argc != 3)
  6177. return CLI_SHOWUSAGE;
  6178. ast_cli(a->fd, "IAX2 Thread Information\n");
  6179. time(&t);
  6180. ast_cli(a->fd, "Idle Threads:\n");
  6181. AST_LIST_LOCK(&idle_list);
  6182. AST_LIST_TRAVERSE(&idle_list, thread, list) {
  6183. #ifdef DEBUG_SCHED_MULTITHREAD
  6184. ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d, func='%s'\n",
  6185. thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
  6186. #else
  6187. ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d\n",
  6188. thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
  6189. #endif
  6190. threadcount++;
  6191. }
  6192. AST_LIST_UNLOCK(&idle_list);
  6193. ast_cli(a->fd, "Active Threads:\n");
  6194. AST_LIST_LOCK(&active_list);
  6195. AST_LIST_TRAVERSE(&active_list, thread, list) {
  6196. if (thread->type == IAX_THREAD_TYPE_DYNAMIC)
  6197. type = 'D';
  6198. else
  6199. type = 'P';
  6200. #ifdef DEBUG_SCHED_MULTITHREAD
  6201. ast_cli(a->fd, "Thread %c%d: state=%u, update=%d, actions=%d, func='%s'\n",
  6202. type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
  6203. #else
  6204. ast_cli(a->fd, "Thread %c%d: state=%u, update=%d, actions=%d\n",
  6205. type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
  6206. #endif
  6207. threadcount++;
  6208. }
  6209. AST_LIST_UNLOCK(&active_list);
  6210. ast_cli(a->fd, "Dynamic Threads:\n");
  6211. AST_LIST_LOCK(&dynamic_list);
  6212. AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
  6213. #ifdef DEBUG_SCHED_MULTITHREAD
  6214. ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d, func='%s'\n",
  6215. thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
  6216. #else
  6217. ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d\n",
  6218. thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
  6219. #endif
  6220. dynamiccount++;
  6221. }
  6222. AST_LIST_UNLOCK(&dynamic_list);
  6223. ast_cli(a->fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
  6224. return CLI_SUCCESS;
  6225. }
  6226. static char *handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  6227. {
  6228. struct iax2_peer *p;
  6229. switch (cmd) {
  6230. case CLI_INIT:
  6231. e->command = "iax2 unregister";
  6232. e->usage =
  6233. "Usage: iax2 unregister <peername>\n"
  6234. " Unregister (force expiration) an IAX2 peer from the registry.\n";
  6235. return NULL;
  6236. case CLI_GENERATE:
  6237. return complete_iax2_unregister(a->line, a->word, a->pos, a->n);
  6238. }
  6239. if (a->argc != 3)
  6240. return CLI_SHOWUSAGE;
  6241. p = find_peer(a->argv[2], 1);
  6242. if (p) {
  6243. if (p->expire > 0) {
  6244. struct iax2_peer *peer;
  6245. peer = ao2_find(peers, a->argv[2], OBJ_KEY);
  6246. if (peer) {
  6247. expire_registry(peer_ref(peer)); /* will release its own reference when done */
  6248. peer_unref(peer); /* ref from ao2_find() */
  6249. ast_cli(a->fd, "Peer %s unregistered\n", a->argv[2]);
  6250. } else {
  6251. ast_cli(a->fd, "Peer %s not found\n", a->argv[2]);
  6252. }
  6253. } else {
  6254. ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
  6255. }
  6256. peer_unref(p);
  6257. } else {
  6258. ast_cli(a->fd, "Peer unknown: %s. Not unregistered\n", a->argv[2]);
  6259. }
  6260. return CLI_SUCCESS;
  6261. }
  6262. static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state)
  6263. {
  6264. int which = 0;
  6265. struct iax2_peer *p = NULL;
  6266. char *res = NULL;
  6267. int wordlen = strlen(word);
  6268. /* 0 - iax2; 1 - unregister; 2 - <peername> */
  6269. if (pos == 2) {
  6270. struct ao2_iterator i = ao2_iterator_init(peers, 0);
  6271. while ((p = ao2_iterator_next(&i))) {
  6272. if (!strncasecmp(p->name, word, wordlen) &&
  6273. ++which > state && p->expire > 0) {
  6274. res = ast_strdup(p->name);
  6275. peer_unref(p);
  6276. break;
  6277. }
  6278. peer_unref(p);
  6279. }
  6280. ao2_iterator_destroy(&i);
  6281. }
  6282. return res;
  6283. }
  6284. static char *handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  6285. {
  6286. switch (cmd) {
  6287. case CLI_INIT:
  6288. e->command = "iax2 show peers";
  6289. e->usage =
  6290. "Usage: iax2 show peers [registered] [like <pattern>]\n"
  6291. " Lists all known IAX2 peers.\n"
  6292. " Optional 'registered' argument lists only peers with known addresses.\n"
  6293. " Optional regular expression pattern is used to filter the peer list.\n";
  6294. return NULL;
  6295. case CLI_GENERATE:
  6296. return NULL;
  6297. }
  6298. switch (__iax2_show_peers(a->fd, NULL, NULL, a->argc, a->argv)) {
  6299. case RESULT_SHOWUSAGE:
  6300. return CLI_SHOWUSAGE;
  6301. case RESULT_FAILURE:
  6302. return CLI_FAILURE;
  6303. default:
  6304. return CLI_SUCCESS;
  6305. }
  6306. }
  6307. static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
  6308. {
  6309. ast_cli_netstats(s, -1, 0);
  6310. astman_append(s, "\r\n");
  6311. return RESULT_SUCCESS;
  6312. }
  6313. static char *handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  6314. {
  6315. struct iax_firmware *cur = NULL;
  6316. switch (cmd) {
  6317. case CLI_INIT:
  6318. e->command = "iax2 show firmware";
  6319. e->usage =
  6320. "Usage: iax2 show firmware\n"
  6321. " Lists all known IAX firmware images.\n";
  6322. return NULL;
  6323. case CLI_GENERATE:
  6324. return NULL;
  6325. }
  6326. if (a->argc != 3 && a->argc != 4)
  6327. return CLI_SHOWUSAGE;
  6328. ast_cli(a->fd, "%-15.15s %-15.15s %-15.15s\n", "Device", "Version", "Size");
  6329. AST_LIST_LOCK(&firmwares);
  6330. AST_LIST_TRAVERSE(&firmwares, cur, list) {
  6331. if ((a->argc == 3) || (!strcasecmp(a->argv[3], (char *) cur->fwh->devname))) {
  6332. ast_cli(a->fd, "%-15.15s %-15d %-15d\n", cur->fwh->devname,
  6333. ntohs(cur->fwh->version), (int)ntohl(cur->fwh->datalen));
  6334. }
  6335. }
  6336. AST_LIST_UNLOCK(&firmwares);
  6337. return CLI_SUCCESS;
  6338. }
  6339. /*! \brief callback to display iax peers in manager */
  6340. static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
  6341. {
  6342. static const char * const a[] = { "iax2", "show", "peers" };
  6343. const char *id = astman_get_header(m,"ActionID");
  6344. char idtext[256] = "";
  6345. int total = 0;
  6346. if (!ast_strlen_zero(id))
  6347. snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
  6348. astman_send_listack(s, m, "Peer status list will follow", "start");
  6349. /* List the peers in separate manager events */
  6350. __iax2_show_peers(-1, &total, s, 3, a);
  6351. /* Send final confirmation */
  6352. astman_append(s,
  6353. "Event: PeerlistComplete\r\n"
  6354. "EventList: Complete\r\n"
  6355. "ListItems: %d\r\n"
  6356. "%s"
  6357. "\r\n", total, idtext);
  6358. return 0;
  6359. }
  6360. /*! \brief callback to display iax peers in manager format */
  6361. static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
  6362. {
  6363. struct iax2_peer *peer = NULL;
  6364. int peer_count = 0;
  6365. char nm[20];
  6366. char status[20];
  6367. const char *id = astman_get_header(m,"ActionID");
  6368. char idtext[256] = "";
  6369. struct ast_str *encmethods = ast_str_alloca(256);
  6370. struct ao2_iterator i;
  6371. if (!ast_strlen_zero(id))
  6372. snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
  6373. astman_append(s, "Response: Success\r\n%sMessage: IAX Peer status list will follow\r\n\r\n", idtext);
  6374. i = ao2_iterator_init(peers, 0);
  6375. for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
  6376. encmethods_to_str(peer->encmethods, &encmethods);
  6377. astman_append(s, "Event: PeerEntry\r\n%sChanneltype: IAX\r\n", idtext);
  6378. if (!ast_strlen_zero(peer->username)) {
  6379. astman_append(s, "ObjectName: %s\r\nObjectUsername: %s\r\n", peer->name, peer->username);
  6380. } else {
  6381. astman_append(s, "ObjectName: %s\r\n", peer->name);
  6382. }
  6383. astman_append(s, "ChanObjectType: peer\r\n");
  6384. astman_append(s, "IPaddress: %s\r\n", ast_sockaddr_stringify_addr(&peer->addr));
  6385. ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
  6386. astman_append(s, "Mask: %s\r\n", nm);
  6387. astman_append(s, "Port: %d\r\n", ast_sockaddr_port(&peer->addr));
  6388. astman_append(s, "Dynamic: %s\r\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
  6389. astman_append(s, "Trunk: %s\r\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
  6390. astman_append(s, "Encryption: %s\r\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
  6391. peer_status(peer, status, sizeof(status));
  6392. astman_append(s, "Status: %s\r\n\r\n", status);
  6393. peer_count++;
  6394. }
  6395. ao2_iterator_destroy(&i);
  6396. astman_append(s, "Event: PeerlistComplete\r\n%sListItems: %d\r\n\r\n", idtext, peer_count);
  6397. return RESULT_SUCCESS;
  6398. }
  6399. static char *regstate2str(int regstate)
  6400. {
  6401. switch(regstate) {
  6402. case REG_STATE_UNREGISTERED:
  6403. return "Unregistered";
  6404. case REG_STATE_REGSENT:
  6405. return "Request Sent";
  6406. case REG_STATE_AUTHSENT:
  6407. return "Auth. Sent";
  6408. case REG_STATE_REGISTERED:
  6409. return "Registered";
  6410. case REG_STATE_REJECTED:
  6411. return "Rejected";
  6412. case REG_STATE_TIMEOUT:
  6413. return "Timeout";
  6414. case REG_STATE_NOAUTH:
  6415. return "No Authentication";
  6416. default:
  6417. return "Unknown";
  6418. }
  6419. }
  6420. static char *handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  6421. {
  6422. #define FORMAT2 "%-20.20s %-6.6s %-10.10s %-20.20s %8.8s %s\n"
  6423. #define FORMAT "%-20.20s %-6.6s %-10.10s %-20.20s %8d %s\n"
  6424. struct iax2_registry *reg = NULL;
  6425. char host[80];
  6426. char perceived[80];
  6427. int counter = 0;
  6428. switch (cmd) {
  6429. case CLI_INIT:
  6430. e->command = "iax2 show registry";
  6431. e->usage =
  6432. "Usage: iax2 show registry\n"
  6433. " Lists all registration requests and status.\n";
  6434. return NULL;
  6435. case CLI_GENERATE:
  6436. return NULL;
  6437. }
  6438. if (a->argc != 3)
  6439. return CLI_SHOWUSAGE;
  6440. ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
  6441. AST_LIST_LOCK(&registrations);
  6442. AST_LIST_TRAVERSE(&registrations, reg, entry) {
  6443. snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
  6444. if (reg->us.sin_addr.s_addr)
  6445. snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
  6446. else
  6447. ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
  6448. ast_cli(a->fd, FORMAT, host,
  6449. (reg->dnsmgr) ? "Y" : "N",
  6450. reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
  6451. counter++;
  6452. }
  6453. AST_LIST_UNLOCK(&registrations);
  6454. ast_cli(a->fd, "%d IAX2 registrations.\n", counter);
  6455. return CLI_SUCCESS;
  6456. #undef FORMAT
  6457. #undef FORMAT2
  6458. }
  6459. static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
  6460. {
  6461. const char *id = astman_get_header(m, "ActionID");
  6462. struct iax2_registry *reg = NULL;
  6463. char idtext[256] = "";
  6464. char host[80] = "";
  6465. char perceived[80] = "";
  6466. int total = 0;
  6467. if (!ast_strlen_zero(id))
  6468. snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
  6469. astman_send_listack(s, m, "Registrations will follow", "start");
  6470. AST_LIST_LOCK(&registrations);
  6471. AST_LIST_TRAVERSE(&registrations, reg, entry) {
  6472. snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
  6473. if (reg->us.sin_addr.s_addr) {
  6474. snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
  6475. } else {
  6476. ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
  6477. }
  6478. astman_append(s,
  6479. "Event: RegistryEntry\r\n"
  6480. "%s"
  6481. "Host: %s\r\n"
  6482. "DNSmanager: %s\r\n"
  6483. "Username: %s\r\n"
  6484. "Perceived: %s\r\n"
  6485. "Refresh: %d\r\n"
  6486. "State: %s\r\n"
  6487. "\r\n", idtext, host, (reg->dnsmgr) ? "Y" : "N", reg->username, perceived,
  6488. reg->refresh, regstate2str(reg->regstate));
  6489. total++;
  6490. }
  6491. AST_LIST_UNLOCK(&registrations);
  6492. astman_append(s,
  6493. "Event: RegistrationsComplete\r\n"
  6494. "EventList: Complete\r\n"
  6495. "ListItems: %d\r\n"
  6496. "%s"
  6497. "\r\n", total, idtext);
  6498. return 0;
  6499. }
  6500. static char *handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  6501. {
  6502. #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s %s %9s\n"
  6503. #define FORMAT "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-4.4dms %-6.6s %s%s %3s%s\n"
  6504. #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
  6505. int x;
  6506. int numchans = 0;
  6507. char first_message[10] = { 0, };
  6508. char last_message[10] = { 0, };
  6509. switch (cmd) {
  6510. case CLI_INIT:
  6511. e->command = "iax2 show channels";
  6512. e->usage =
  6513. "Usage: iax2 show channels\n"
  6514. " Lists all currently active IAX channels.\n";
  6515. return NULL;
  6516. case CLI_GENERATE:
  6517. return NULL;
  6518. }
  6519. if (a->argc != 3)
  6520. return CLI_SHOWUSAGE;
  6521. ast_cli(a->fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format", "FirstMsg", "LastMsg");
  6522. for (x = 0; x < ARRAY_LEN(iaxs); x++) {
  6523. ast_mutex_lock(&iaxsl[x]);
  6524. if (iaxs[x]) {
  6525. int lag, jitter, localdelay;
  6526. jb_info jbinfo;
  6527. if (ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
  6528. jb_getinfo(iaxs[x]->jb, &jbinfo);
  6529. jitter = jbinfo.jitter;
  6530. localdelay = jbinfo.current - jbinfo.min;
  6531. } else {
  6532. jitter = -1;
  6533. localdelay = 0;
  6534. }
  6535. iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
  6536. iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
  6537. lag = iaxs[x]->remote_rr.delay;
  6538. ast_cli(a->fd, FORMAT,
  6539. iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
  6540. ast_inet_ntoa(iaxs[x]->addr.sin_addr),
  6541. S_OR(iaxs[x]->username, "(None)"),
  6542. iaxs[x]->callno, iaxs[x]->peercallno,
  6543. iaxs[x]->oseqno, iaxs[x]->iseqno,
  6544. lag,
  6545. jitter,
  6546. localdelay,
  6547. iax2_getformatname(iaxs[x]->voiceformat),
  6548. (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
  6549. first_message,
  6550. (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
  6551. last_message);
  6552. numchans++;
  6553. }
  6554. ast_mutex_unlock(&iaxsl[x]);
  6555. }
  6556. ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
  6557. return CLI_SUCCESS;
  6558. #undef FORMAT
  6559. #undef FORMAT2
  6560. #undef FORMATB
  6561. }
  6562. static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
  6563. {
  6564. int x;
  6565. int numchans = 0;
  6566. char first_message[10] = { 0, };
  6567. char last_message[10] = { 0, };
  6568. #define ACN_FORMAT1 "%-20.25s %4u %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d %s%s %4s%s\n"
  6569. #define ACN_FORMAT2 "%s %u %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"
  6570. for (x = 0; x < ARRAY_LEN(iaxs); x++) {
  6571. ast_mutex_lock(&iaxsl[x]);
  6572. if (iaxs[x]) {
  6573. int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
  6574. jb_info jbinfo;
  6575. iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
  6576. iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
  6577. if(ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
  6578. jb_getinfo(iaxs[x]->jb, &jbinfo);
  6579. localjitter = jbinfo.jitter;
  6580. localdelay = jbinfo.current - jbinfo.min;
  6581. locallost = jbinfo.frames_lost;
  6582. locallosspct = jbinfo.losspct/1000;
  6583. localdropped = jbinfo.frames_dropped;
  6584. localooo = jbinfo.frames_ooo;
  6585. } else {
  6586. localjitter = -1;
  6587. localdelay = 0;
  6588. locallost = -1;
  6589. locallosspct = -1;
  6590. localdropped = 0;
  6591. localooo = -1;
  6592. }
  6593. if (s)
  6594. astman_append(s, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
  6595. iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
  6596. iaxs[x]->pingtime,
  6597. localjitter,
  6598. localdelay,
  6599. locallost,
  6600. locallosspct,
  6601. localdropped,
  6602. localooo,
  6603. iaxs[x]->frames_received/1000,
  6604. iaxs[x]->remote_rr.jitter,
  6605. iaxs[x]->remote_rr.delay,
  6606. iaxs[x]->remote_rr.losscnt,
  6607. iaxs[x]->remote_rr.losspct,
  6608. iaxs[x]->remote_rr.dropped,
  6609. iaxs[x]->remote_rr.ooo,
  6610. iaxs[x]->remote_rr.packets/1000,
  6611. (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
  6612. first_message,
  6613. (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
  6614. last_message);
  6615. else
  6616. ast_cli(fd, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
  6617. iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
  6618. iaxs[x]->pingtime,
  6619. localjitter,
  6620. localdelay,
  6621. locallost,
  6622. locallosspct,
  6623. localdropped,
  6624. localooo,
  6625. iaxs[x]->frames_received/1000,
  6626. iaxs[x]->remote_rr.jitter,
  6627. iaxs[x]->remote_rr.delay,
  6628. iaxs[x]->remote_rr.losscnt,
  6629. iaxs[x]->remote_rr.losspct,
  6630. iaxs[x]->remote_rr.dropped,
  6631. iaxs[x]->remote_rr.ooo,
  6632. iaxs[x]->remote_rr.packets/1000,
  6633. (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
  6634. first_message,
  6635. (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
  6636. last_message);
  6637. numchans++;
  6638. }
  6639. ast_mutex_unlock(&iaxsl[x]);
  6640. }
  6641. return numchans;
  6642. }
  6643. static char *handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  6644. {
  6645. int numchans = 0;
  6646. switch (cmd) {
  6647. case CLI_INIT:
  6648. e->command = "iax2 show netstats";
  6649. e->usage =
  6650. "Usage: iax2 show netstats\n"
  6651. " Lists network status for all currently active IAX channels.\n";
  6652. return NULL;
  6653. case CLI_GENERATE:
  6654. return NULL;
  6655. }
  6656. if (a->argc != 3)
  6657. return CLI_SHOWUSAGE;
  6658. ast_cli(a->fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
  6659. ast_cli(a->fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts FirstMsg LastMsg\n");
  6660. numchans = ast_cli_netstats(NULL, a->fd, 1);
  6661. ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
  6662. return CLI_SUCCESS;
  6663. }
  6664. static char *handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  6665. {
  6666. switch (cmd) {
  6667. case CLI_INIT:
  6668. e->command = "iax2 set debug {on|off|peer}";
  6669. e->usage =
  6670. "Usage: iax2 set debug {on|off|peer peername}\n"
  6671. " Enables/Disables dumping of IAX packets for debugging purposes.\n";
  6672. return NULL;
  6673. case CLI_GENERATE:
  6674. if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
  6675. return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
  6676. return NULL;
  6677. }
  6678. if (a->argc < e->args || a->argc > e->args + 1)
  6679. return CLI_SHOWUSAGE;
  6680. if (!strcasecmp(a->argv[3], "peer")) {
  6681. struct iax2_peer *peer;
  6682. struct sockaddr_in peer_addr;
  6683. if (a->argc != e->args + 1)
  6684. return CLI_SHOWUSAGE;
  6685. peer = find_peer(a->argv[4], 1);
  6686. if (!peer) {
  6687. ast_cli(a->fd, "IAX2 peer '%s' does not exist\n", a->argv[e->args-1]);
  6688. return CLI_FAILURE;
  6689. }
  6690. ast_sockaddr_to_sin(&peer->addr, &peer_addr);
  6691. debugaddr.sin_addr = peer_addr.sin_addr;
  6692. debugaddr.sin_port = peer_addr.sin_port;
  6693. ast_cli(a->fd, "IAX2 Debugging Enabled for IP: %s:%d\n",
  6694. ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
  6695. ao2_ref(peer, -1);
  6696. } else if (!strncasecmp(a->argv[3], "on", 2)) {
  6697. iaxdebug = 1;
  6698. ast_cli(a->fd, "IAX2 Debugging Enabled\n");
  6699. } else {
  6700. iaxdebug = 0;
  6701. memset(&debugaddr, 0, sizeof(debugaddr));
  6702. ast_cli(a->fd, "IAX2 Debugging Disabled\n");
  6703. }
  6704. return CLI_SUCCESS;
  6705. }
  6706. static char *handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  6707. {
  6708. switch (cmd) {
  6709. case CLI_INIT:
  6710. e->command = "iax2 set debug trunk {on|off}";
  6711. e->usage =
  6712. "Usage: iax2 set debug trunk {on|off}\n"
  6713. " Enables/Disables debugging of IAX trunking\n";
  6714. return NULL;
  6715. case CLI_GENERATE:
  6716. return NULL;
  6717. }
  6718. if (a->argc != e->args)
  6719. return CLI_SHOWUSAGE;
  6720. if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
  6721. iaxtrunkdebug = 1;
  6722. ast_cli(a->fd, "IAX2 Trunk Debugging Enabled\n");
  6723. } else {
  6724. iaxtrunkdebug = 0;
  6725. ast_cli(a->fd, "IAX2 Trunk Debugging Disabled\n");
  6726. }
  6727. return CLI_SUCCESS;
  6728. }
  6729. static char *handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  6730. {
  6731. switch (cmd) {
  6732. case CLI_INIT:
  6733. e->command = "iax2 set debug jb {on|off}";
  6734. e->usage =
  6735. "Usage: iax2 set debug jb {on|off}\n"
  6736. " Enables/Disables jitterbuffer debugging information\n";
  6737. return NULL;
  6738. case CLI_GENERATE:
  6739. return NULL;
  6740. }
  6741. if (a->argc != e->args)
  6742. return CLI_SHOWUSAGE;
  6743. if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
  6744. jb_setoutput(jb_error_output, jb_warning_output, jb_debug_output);
  6745. ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Enabled\n");
  6746. } else {
  6747. jb_setoutput(jb_error_output, jb_warning_output, NULL);
  6748. ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Disabled\n");
  6749. }
  6750. return CLI_SUCCESS;
  6751. }
  6752. static int iax2_write(struct ast_channel *c, struct ast_frame *f)
  6753. {
  6754. unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
  6755. int res = -1;
  6756. ast_mutex_lock(&iaxsl[callno]);
  6757. if (iaxs[callno]) {
  6758. /* If there's an outstanding error, return failure now */
  6759. if (!iaxs[callno]->error) {
  6760. if (ast_test_flag64(iaxs[callno], IAX_ALREADYGONE))
  6761. res = 0;
  6762. /* Don't waste bandwidth sending null frames */
  6763. else if (f->frametype == AST_FRAME_NULL)
  6764. res = 0;
  6765. else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag64(iaxs[callno], IAX_QUELCH))
  6766. res = 0;
  6767. else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
  6768. res = 0;
  6769. else
  6770. /* Simple, just queue for transmission */
  6771. res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
  6772. } else {
  6773. ast_debug(1, "Write error: %s\n", strerror(errno));
  6774. }
  6775. }
  6776. /* If it's already gone, just return */
  6777. ast_mutex_unlock(&iaxsl[callno]);
  6778. return res;
  6779. }
  6780. static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
  6781. int now, int transfer, int final)
  6782. {
  6783. struct ast_frame f = { 0, };
  6784. int res = 0;
  6785. f.frametype = type;
  6786. f.subclass.integer = command;
  6787. f.datalen = datalen;
  6788. f.src = __FUNCTION__;
  6789. f.data.ptr = (void *) data;
  6790. if ((res = queue_signalling(i, &f)) <= 0) {
  6791. return res;
  6792. }
  6793. return iax2_send(i, &f, ts, seqno, now, transfer, final);
  6794. }
  6795. static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
  6796. {
  6797. if (type == AST_FRAME_CONTROL && !iax2_is_control_frame_allowed(command)) {
  6798. /* Control frame should not go out on the wire. */
  6799. ast_debug(2, "Callno %d: Blocked sending control frame %d.\n",
  6800. i->callno, command);
  6801. return 0;
  6802. }
  6803. return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
  6804. }
  6805. static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
  6806. {
  6807. int res;
  6808. ast_mutex_lock(&iaxsl[callno]);
  6809. res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
  6810. ast_mutex_unlock(&iaxsl[callno]);
  6811. return res;
  6812. }
  6813. /*!
  6814. * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
  6815. * the pvt struct for the given call number may disappear during its
  6816. * execution.
  6817. */
  6818. static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
  6819. {
  6820. int call_num = i->callno;
  6821. /* It is assumed that the callno has already been locked */
  6822. iax2_predestroy(i->callno);
  6823. if (!iaxs[call_num])
  6824. return -1;
  6825. return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
  6826. }
  6827. static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
  6828. {
  6829. return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
  6830. }
  6831. static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
  6832. {
  6833. return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
  6834. }
  6835. static int apply_context(struct iax2_context *con, const char *context)
  6836. {
  6837. while(con) {
  6838. if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
  6839. return -1;
  6840. con = con->next;
  6841. }
  6842. return 0;
  6843. }
  6844. static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
  6845. {
  6846. /* Start pessimistic */
  6847. int res = -1;
  6848. int version = 2;
  6849. struct iax2_user *user = NULL, *best = NULL;
  6850. int bestscore = 0;
  6851. int gotcapability = 0;
  6852. struct ast_variable *v = NULL, *tmpvar = NULL;
  6853. struct ao2_iterator i;
  6854. struct ast_sockaddr addr;
  6855. if (!iaxs[callno])
  6856. return res;
  6857. if (ies->called_number)
  6858. ast_string_field_set(iaxs[callno], exten, ies->called_number);
  6859. if (ies->calling_number) {
  6860. if (ast_test_flag64(&globalflags, IAX_SHRINKCALLERID)) {
  6861. ast_shrink_phone_number(ies->calling_number);
  6862. }
  6863. ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
  6864. }
  6865. if (ies->calling_name)
  6866. ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
  6867. if (ies->calling_ani)
  6868. ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
  6869. if (ies->dnid)
  6870. ast_string_field_set(iaxs[callno], dnid, ies->dnid);
  6871. if (ies->rdnis)
  6872. ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
  6873. if (ies->called_context)
  6874. ast_string_field_set(iaxs[callno], context, ies->called_context);
  6875. if (ies->language)
  6876. ast_string_field_set(iaxs[callno], language, ies->language);
  6877. if (ies->username)
  6878. ast_string_field_set(iaxs[callno], username, ies->username);
  6879. if (ies->calling_ton > -1)
  6880. iaxs[callno]->calling_ton = ies->calling_ton;
  6881. if (ies->calling_tns > -1)
  6882. iaxs[callno]->calling_tns = ies->calling_tns;
  6883. if (ies->calling_pres > -1)
  6884. iaxs[callno]->calling_pres = ies->calling_pres;
  6885. if (ies->format)
  6886. iaxs[callno]->peerformat = ies->format;
  6887. if (ies->adsicpe)
  6888. iaxs[callno]->peeradsicpe = ies->adsicpe;
  6889. if (ies->capability) {
  6890. gotcapability = 1;
  6891. iaxs[callno]->peercapability = ies->capability;
  6892. }
  6893. if (ies->version)
  6894. version = ies->version;
  6895. /* Use provided preferences until told otherwise for actual preferences */
  6896. if (ies->codec_prefs) {
  6897. ast_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
  6898. ast_codec_pref_convert(&iaxs[callno]->prefs, ies->codec_prefs, 32, 0);
  6899. }
  6900. if (!gotcapability)
  6901. iaxs[callno]->peercapability = iaxs[callno]->peerformat;
  6902. if (version > IAX_PROTO_VERSION) {
  6903. ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
  6904. ast_inet_ntoa(sin->sin_addr), version);
  6905. return res;
  6906. }
  6907. /* Search the userlist for a compatible entry, and fill in the rest */
  6908. ast_sockaddr_from_sin(&addr, sin);
  6909. i = ao2_iterator_init(users, 0);
  6910. while ((user = ao2_iterator_next(&i))) {
  6911. if ((ast_strlen_zero(iaxs[callno]->username) || /* No username specified */
  6912. !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
  6913. && (ast_apply_acl(user->acl, &addr, "IAX2 user ACL: ") == AST_SENSE_ALLOW) /* Access is permitted from this IP */
  6914. && (ast_strlen_zero(iaxs[callno]->context) || /* No context specified */
  6915. apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
  6916. if (!ast_strlen_zero(iaxs[callno]->username)) {
  6917. /* Exact match, stop right now. */
  6918. if (best)
  6919. user_unref(best);
  6920. best = user;
  6921. break;
  6922. } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
  6923. /* No required authentication */
  6924. if (user->acl) {
  6925. /* There was host authentication and we passed, bonus! */
  6926. if (bestscore < 4) {
  6927. bestscore = 4;
  6928. if (best)
  6929. user_unref(best);
  6930. best = user;
  6931. continue;
  6932. }
  6933. } else {
  6934. /* No host access, but no secret, either, not bad */
  6935. if (bestscore < 3) {
  6936. bestscore = 3;
  6937. if (best)
  6938. user_unref(best);
  6939. best = user;
  6940. continue;
  6941. }
  6942. }
  6943. } else {
  6944. if (user->acl) {
  6945. /* Authentication, but host access too, eh, it's something.. */
  6946. if (bestscore < 2) {
  6947. bestscore = 2;
  6948. if (best)
  6949. user_unref(best);
  6950. best = user;
  6951. continue;
  6952. }
  6953. } else {
  6954. /* Authentication and no host access... This is our baseline */
  6955. if (bestscore < 1) {
  6956. bestscore = 1;
  6957. if (best)
  6958. user_unref(best);
  6959. best = user;
  6960. continue;
  6961. }
  6962. }
  6963. }
  6964. }
  6965. user_unref(user);
  6966. }
  6967. ao2_iterator_destroy(&i);
  6968. user = best;
  6969. if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
  6970. user = realtime_user(iaxs[callno]->username, sin);
  6971. if (user && (ast_apply_acl(user->acl, &addr, "IAX2 user ACL: ") == AST_SENSE_DENY /* Access is denied from this IP */
  6972. || (!ast_strlen_zero(iaxs[callno]->context) && /* No context specified */
  6973. !apply_context(user->contexts, iaxs[callno]->context)))) { /* Context is permitted */
  6974. user = user_unref(user);
  6975. }
  6976. }
  6977. if (user) {
  6978. /* We found our match (use the first) */
  6979. /* copy vars */
  6980. for (v = user->vars ; v ; v = v->next) {
  6981. if((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
  6982. tmpvar->next = iaxs[callno]->vars;
  6983. iaxs[callno]->vars = tmpvar;
  6984. }
  6985. }
  6986. /* If a max AUTHREQ restriction is in place, activate it */
  6987. if (user->maxauthreq > 0)
  6988. ast_set_flag64(iaxs[callno], IAX_MAXAUTHREQ);
  6989. iaxs[callno]->prefs = user->prefs;
  6990. ast_copy_flags64(iaxs[callno], user, IAX_CODEC_USER_FIRST | IAX_IMMEDIATE | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP | IAX_FORCE_ENCRYPT);
  6991. iaxs[callno]->encmethods = user->encmethods;
  6992. /* Store the requested username if not specified */
  6993. if (ast_strlen_zero(iaxs[callno]->username))
  6994. ast_string_field_set(iaxs[callno], username, user->name);
  6995. /* Store whether this is a trunked call, too, of course, and move if appropriate */
  6996. ast_copy_flags64(iaxs[callno], user, IAX_TRUNK);
  6997. iaxs[callno]->capability = user->capability;
  6998. /* And use the default context */
  6999. if (ast_strlen_zero(iaxs[callno]->context)) {
  7000. if (user->contexts)
  7001. ast_string_field_set(iaxs[callno], context, user->contexts->context);
  7002. else
  7003. ast_string_field_set(iaxs[callno], context, DEFAULT_CONTEXT);
  7004. }
  7005. /* And any input keys */
  7006. ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
  7007. /* And the permitted authentication methods */
  7008. iaxs[callno]->authmethods = user->authmethods;
  7009. iaxs[callno]->adsi = user->adsi;
  7010. /* If the user has callerid, override the remote caller id. */
  7011. if (ast_test_flag64(user, IAX_HASCALLERID)) {
  7012. iaxs[callno]->calling_tns = 0;
  7013. iaxs[callno]->calling_ton = 0;
  7014. ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
  7015. ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
  7016. ast_string_field_set(iaxs[callno], ani, user->cid_num);
  7017. iaxs[callno]->calling_pres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
  7018. } else if (ast_strlen_zero(iaxs[callno]->cid_num) && ast_strlen_zero(iaxs[callno]->cid_name)) {
  7019. iaxs[callno]->calling_pres = AST_PRES_NUMBER_NOT_AVAILABLE;
  7020. } /* else user is allowed to set their own CID settings */
  7021. if (!ast_strlen_zero(user->accountcode))
  7022. ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
  7023. if (!ast_strlen_zero(user->mohinterpret))
  7024. ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
  7025. if (!ast_strlen_zero(user->mohsuggest))
  7026. ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
  7027. if (!ast_strlen_zero(user->parkinglot))
  7028. ast_string_field_set(iaxs[callno], parkinglot, user->parkinglot);
  7029. if (user->amaflags)
  7030. iaxs[callno]->amaflags = user->amaflags;
  7031. if (!ast_strlen_zero(user->language))
  7032. ast_string_field_set(iaxs[callno], language, user->language);
  7033. ast_copy_flags64(iaxs[callno], user, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
  7034. /* Keep this check last */
  7035. if (!ast_strlen_zero(user->dbsecret)) {
  7036. char *family, *key=NULL;
  7037. char buf[80];
  7038. family = ast_strdupa(user->dbsecret);
  7039. key = strchr(family, '/');
  7040. if (key) {
  7041. *key = '\0';
  7042. key++;
  7043. }
  7044. if (!key || ast_db_get(family, key, buf, sizeof(buf)))
  7045. ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
  7046. else
  7047. ast_string_field_set(iaxs[callno], secret, buf);
  7048. } else
  7049. ast_string_field_set(iaxs[callno], secret, user->secret);
  7050. res = 0;
  7051. user = user_unref(user);
  7052. } else {
  7053. /* user was not found, but we should still fake an AUTHREQ.
  7054. * Set authmethods to the last known authmethod used by the system
  7055. * Set a fake secret, it's not looked at, just required to attempt authentication.
  7056. * Set authrej so the AUTHREP is rejected without even looking at its contents */
  7057. iaxs[callno]->authmethods = last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
  7058. ast_string_field_set(iaxs[callno], secret, "badsecret");
  7059. iaxs[callno]->authrej = 1;
  7060. if (!ast_strlen_zero(iaxs[callno]->username)) {
  7061. /* only send the AUTHREQ if a username was specified. */
  7062. res = 0;
  7063. }
  7064. }
  7065. ast_set2_flag64(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);
  7066. return res;
  7067. }
  7068. static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst, int sockfd)
  7069. {
  7070. struct ast_iax2_full_hdr fh;
  7071. fh.scallno = htons(src | IAX_FLAG_FULL);
  7072. fh.dcallno = htons(dst);
  7073. fh.ts = 0;
  7074. fh.oseqno = 0;
  7075. fh.iseqno = 0;
  7076. fh.type = AST_FRAME_IAX;
  7077. fh.csub = compress_subclass(IAX_COMMAND_INVAL);
  7078. iax_outputframe(NULL, &fh, 0, sin, 0);
  7079. ast_debug(1, "Raw Hangup %s:%d, src=%d, dst=%d\n",
  7080. ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
  7081. return sendto(sockfd, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
  7082. }
  7083. static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
  7084. {
  7085. /* Select exactly one common encryption if there are any */
  7086. p->encmethods &= enc;
  7087. if (p->encmethods) {
  7088. if (!(p->encmethods & IAX_ENCRYPT_KEYROTATE)){ /* if key rotation is not supported, turn off keyrotation. */
  7089. p->keyrotateid = -2;
  7090. }
  7091. if (p->encmethods & IAX_ENCRYPT_AES128)
  7092. p->encmethods = IAX_ENCRYPT_AES128;
  7093. else
  7094. p->encmethods = 0;
  7095. }
  7096. }
  7097. /*!
  7098. * \pre iaxsl[call_num] is locked
  7099. *
  7100. * \note Since this function calls send_command_final(), the pvt struct for the given
  7101. * call number may disappear while executing this function.
  7102. */
  7103. static int authenticate_request(int call_num)
  7104. {
  7105. struct iax_ie_data ied;
  7106. int res = -1, authreq_restrict = 0;
  7107. char challenge[10];
  7108. struct chan_iax2_pvt *p = iaxs[call_num];
  7109. memset(&ied, 0, sizeof(ied));
  7110. /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
  7111. if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
  7112. struct iax2_user *user;
  7113. user = ao2_find(users, p->username, OBJ_KEY);
  7114. if (user) {
  7115. if (user->curauthreq == user->maxauthreq)
  7116. authreq_restrict = 1;
  7117. else
  7118. user->curauthreq++;
  7119. user = user_unref(user);
  7120. }
  7121. }
  7122. /* If the AUTHREQ limit test failed, send back an error */
  7123. if (authreq_restrict) {
  7124. iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
  7125. iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_CALL_REJECTED);
  7126. send_command_final(p, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
  7127. return 0;
  7128. }
  7129. iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
  7130. if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
  7131. snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
  7132. ast_string_field_set(p, challenge, challenge);
  7133. /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
  7134. iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
  7135. }
  7136. if (p->encmethods)
  7137. iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, p->encmethods);
  7138. iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
  7139. res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
  7140. if (p->encmethods)
  7141. ast_set_flag64(p, IAX_ENCRYPTED);
  7142. return res;
  7143. }
  7144. static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
  7145. {
  7146. char requeststr[256];
  7147. char md5secret[256] = "";
  7148. char secret[256] = "";
  7149. char rsasecret[256] = "";
  7150. int res = -1;
  7151. int x;
  7152. struct iax2_user *user;
  7153. if (p->authrej) {
  7154. return res;
  7155. }
  7156. user = ao2_find(users, p->username, OBJ_KEY);
  7157. if (user) {
  7158. if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
  7159. ast_atomic_fetchadd_int(&user->curauthreq, -1);
  7160. ast_clear_flag64(p, IAX_MAXAUTHREQ);
  7161. }
  7162. ast_string_field_set(p, host, user->name);
  7163. user = user_unref(user);
  7164. }
  7165. if (ast_test_flag64(p, IAX_FORCE_ENCRYPT) && !p->encmethods) {
  7166. ast_log(LOG_NOTICE, "Call Terminated, Incoming call is unencrypted while force encrypt is enabled.\n");
  7167. return res;
  7168. }
  7169. if (!ast_test_flag(&p->state, IAX_STATE_AUTHENTICATED))
  7170. return res;
  7171. if (ies->password)
  7172. ast_copy_string(secret, ies->password, sizeof(secret));
  7173. if (ies->md5_result)
  7174. ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
  7175. if (ies->rsa_result)
  7176. ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
  7177. if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
  7178. struct ast_key *key;
  7179. char *keyn;
  7180. char tmpkey[256];
  7181. char *stringp=NULL;
  7182. ast_copy_string(tmpkey, p->inkeys, sizeof(tmpkey));
  7183. stringp=tmpkey;
  7184. keyn = strsep(&stringp, ":");
  7185. while(keyn) {
  7186. key = ast_key_get(keyn, AST_KEY_PUBLIC);
  7187. if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
  7188. res = 0;
  7189. break;
  7190. } else if (!key)
  7191. ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
  7192. keyn = strsep(&stringp, ":");
  7193. }
  7194. } else if (p->authmethods & IAX_AUTH_MD5) {
  7195. struct MD5Context md5;
  7196. unsigned char digest[16];
  7197. char *tmppw, *stringp;
  7198. tmppw = ast_strdupa(p->secret);
  7199. stringp = tmppw;
  7200. while((tmppw = strsep(&stringp, ";"))) {
  7201. MD5Init(&md5);
  7202. MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
  7203. MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
  7204. MD5Final(digest, &md5);
  7205. /* If they support md5, authenticate with it. */
  7206. for (x=0;x<16;x++)
  7207. sprintf(requeststr + (x << 1), "%02hhx", digest[x]); /* safe */
  7208. if (!strcasecmp(requeststr, md5secret)) {
  7209. res = 0;
  7210. break;
  7211. }
  7212. }
  7213. } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
  7214. if (!strcmp(secret, p->secret))
  7215. res = 0;
  7216. }
  7217. return res;
  7218. }
  7219. /*! \brief Verify inbound registration */
  7220. static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
  7221. {
  7222. char requeststr[256] = "";
  7223. char peer[256] = "";
  7224. char md5secret[256] = "";
  7225. char rsasecret[256] = "";
  7226. char secret[256] = "";
  7227. struct iax2_peer *p = NULL;
  7228. struct ast_key *key;
  7229. char *keyn;
  7230. int x;
  7231. int expire = 0;
  7232. int res = -1;
  7233. struct ast_sockaddr addr;
  7234. ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
  7235. /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
  7236. if (ies->username)
  7237. ast_copy_string(peer, ies->username, sizeof(peer));
  7238. if (ies->password)
  7239. ast_copy_string(secret, ies->password, sizeof(secret));
  7240. if (ies->md5_result)
  7241. ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
  7242. if (ies->rsa_result)
  7243. ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
  7244. if (ies->refresh)
  7245. expire = ies->refresh;
  7246. if (ast_strlen_zero(peer)) {
  7247. ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(sin->sin_addr));
  7248. return -1;
  7249. }
  7250. /* SLD: first call to lookup peer during registration */
  7251. ast_mutex_unlock(&iaxsl[callno]);
  7252. p = find_peer(peer, 1);
  7253. ast_mutex_lock(&iaxsl[callno]);
  7254. if (!p || !iaxs[callno]) {
  7255. if (iaxs[callno]) {
  7256. int plaintext = ((last_authmethod & IAX_AUTH_PLAINTEXT) | (iaxs[callno]->authmethods & IAX_AUTH_PLAINTEXT));
  7257. /* Anything, as long as it's non-blank */
  7258. ast_string_field_set(iaxs[callno], secret, "badsecret");
  7259. /* An AUTHREQ must be sent in response to a REGREQ of an invalid peer unless
  7260. * 1. A challenge already exists indicating a AUTHREQ was already sent out.
  7261. * 2. A plaintext secret is present in ie as result of a previous AUTHREQ requesting it.
  7262. * 3. A plaintext secret is present in the ie and the last_authmethod used by a peer happened
  7263. * to be plaintext, indicating it is an authmethod used by other peers on the system.
  7264. *
  7265. * If none of these cases exist, res will be returned as 0 without authentication indicating
  7266. * an AUTHREQ needs to be sent out. */
  7267. if (ast_strlen_zero(iaxs[callno]->challenge) &&
  7268. !(!ast_strlen_zero(secret) && plaintext)) {
  7269. /* by setting res to 0, an REGAUTH will be sent */
  7270. res = 0;
  7271. }
  7272. }
  7273. if (authdebug && !p)
  7274. ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
  7275. goto return_unref;
  7276. }
  7277. if (!ast_test_flag64(p, IAX_DYNAMIC)) {
  7278. if (authdebug)
  7279. ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
  7280. goto return_unref;
  7281. }
  7282. ast_sockaddr_from_sin(&addr, sin);
  7283. if (!ast_apply_acl(p->acl, &addr, "IAX2 Peer ACL: ")) {
  7284. if (authdebug)
  7285. ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
  7286. goto return_unref;
  7287. }
  7288. ast_string_field_set(iaxs[callno], secret, p->secret);
  7289. ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
  7290. /* Check secret against what we have on file */
  7291. if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
  7292. if (!ast_strlen_zero(p->inkeys)) {
  7293. char tmpkeys[256];
  7294. char *stringp=NULL;
  7295. ast_copy_string(tmpkeys, p->inkeys, sizeof(tmpkeys));
  7296. stringp=tmpkeys;
  7297. keyn = strsep(&stringp, ":");
  7298. while(keyn) {
  7299. key = ast_key_get(keyn, AST_KEY_PUBLIC);
  7300. if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
  7301. ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
  7302. break;
  7303. } else if (!key)
  7304. ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
  7305. keyn = strsep(&stringp, ":");
  7306. }
  7307. if (!keyn) {
  7308. if (authdebug)
  7309. ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
  7310. goto return_unref;
  7311. }
  7312. } else {
  7313. if (authdebug)
  7314. ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
  7315. goto return_unref;
  7316. }
  7317. } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
  7318. struct MD5Context md5;
  7319. unsigned char digest[16];
  7320. char *tmppw, *stringp;
  7321. tmppw = ast_strdupa(p->secret);
  7322. stringp = tmppw;
  7323. while((tmppw = strsep(&stringp, ";"))) {
  7324. MD5Init(&md5);
  7325. MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
  7326. MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
  7327. MD5Final(digest, &md5);
  7328. for (x=0;x<16;x++)
  7329. sprintf(requeststr + (x << 1), "%02hhx", digest[x]); /* safe */
  7330. if (!strcasecmp(requeststr, md5secret))
  7331. break;
  7332. }
  7333. if (tmppw) {
  7334. ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
  7335. } else {
  7336. if (authdebug)
  7337. ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
  7338. goto return_unref;
  7339. }
  7340. } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
  7341. /* They've provided a plain text password and we support that */
  7342. if (strcmp(secret, p->secret)) {
  7343. if (authdebug)
  7344. ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
  7345. goto return_unref;
  7346. } else
  7347. ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
  7348. } else if (!ast_strlen_zero(iaxs[callno]->challenge) && ast_strlen_zero(md5secret) && ast_strlen_zero(rsasecret)) {
  7349. /* if challenge has been sent, but no challenge response if given, reject. */
  7350. goto return_unref;
  7351. }
  7352. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
  7353. /* either Authentication has taken place, or a REGAUTH must be sent before verifying registration */
  7354. res = 0;
  7355. return_unref:
  7356. if (iaxs[callno]) {
  7357. ast_string_field_set(iaxs[callno], peer, peer);
  7358. /* Choose lowest expiry number */
  7359. if (expire && (expire < iaxs[callno]->expiry)) {
  7360. iaxs[callno]->expiry = expire;
  7361. }
  7362. }
  7363. if (p) {
  7364. peer_unref(p);
  7365. }
  7366. return res;
  7367. }
  7368. static int authenticate(const char *challenge, const char *secret, const char *keyn, int authmethods, struct iax_ie_data *ied, struct sockaddr_in *sin, struct chan_iax2_pvt *pvt)
  7369. {
  7370. int res = -1;
  7371. int x;
  7372. if (!ast_strlen_zero(keyn)) {
  7373. if (!(authmethods & IAX_AUTH_RSA)) {
  7374. if (ast_strlen_zero(secret))
  7375. ast_log(LOG_NOTICE, "Asked to authenticate to %s with an RSA key, but they don't allow RSA authentication\n", ast_inet_ntoa(sin->sin_addr));
  7376. } else if (ast_strlen_zero(challenge)) {
  7377. ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin->sin_addr));
  7378. } else {
  7379. char sig[256];
  7380. struct ast_key *key;
  7381. key = ast_key_get(keyn, AST_KEY_PRIVATE);
  7382. if (!key) {
  7383. ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
  7384. } else {
  7385. if (ast_sign(key, (char*)challenge, sig)) {
  7386. ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
  7387. res = -1;
  7388. } else {
  7389. iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
  7390. res = 0;
  7391. }
  7392. }
  7393. }
  7394. }
  7395. /* Fall back */
  7396. if (res && !ast_strlen_zero(secret)) {
  7397. if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
  7398. struct MD5Context md5;
  7399. unsigned char digest[16];
  7400. char digres[128];
  7401. MD5Init(&md5);
  7402. MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
  7403. MD5Update(&md5, (unsigned char *)secret, strlen(secret));
  7404. MD5Final(digest, &md5);
  7405. /* If they support md5, authenticate with it. */
  7406. for (x=0;x<16;x++)
  7407. sprintf(digres + (x << 1), "%02hhx", digest[x]); /* safe */
  7408. if (pvt) {
  7409. build_encryption_keys(digest, pvt);
  7410. }
  7411. iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
  7412. res = 0;
  7413. } else if (authmethods & IAX_AUTH_PLAINTEXT) {
  7414. iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
  7415. res = 0;
  7416. } else
  7417. ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin->sin_addr), authmethods);
  7418. }
  7419. return res;
  7420. }
  7421. /*!
  7422. * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
  7423. * so do not call this function with a pvt lock held.
  7424. */
  7425. static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, const char *override, const char *okey)
  7426. {
  7427. struct iax2_peer *peer = NULL;
  7428. /* Start pessimistic */
  7429. int res = -1;
  7430. int authmethods = 0;
  7431. struct iax_ie_data ied;
  7432. uint16_t callno = p->callno;
  7433. memset(&ied, 0, sizeof(ied));
  7434. if (ies->username)
  7435. ast_string_field_set(p, username, ies->username);
  7436. if (ies->challenge)
  7437. ast_string_field_set(p, challenge, ies->challenge);
  7438. if (ies->authmethods)
  7439. authmethods = ies->authmethods;
  7440. if (authmethods & IAX_AUTH_MD5)
  7441. merge_encryption(p, ies->encmethods);
  7442. else
  7443. p->encmethods = 0;
  7444. /* Check for override RSA authentication first */
  7445. if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
  7446. /* Normal password authentication */
  7447. res = authenticate(p->challenge, override, okey, authmethods, &ied, sin, p);
  7448. } else {
  7449. struct ao2_iterator i = ao2_iterator_init(peers, 0);
  7450. while ((peer = ao2_iterator_next(&i))) {
  7451. struct sockaddr_in peer_addr;
  7452. ast_sockaddr_to_sin(&peer->addr, &peer_addr);
  7453. if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
  7454. /* No peer specified at our end, or this is the peer */
  7455. && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
  7456. /* No username specified in peer rule, or this is the right username */
  7457. && (!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)))
  7458. /* No specified host, or this is our host */
  7459. ) {
  7460. res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin, p);
  7461. if (!res) {
  7462. peer_unref(peer);
  7463. break;
  7464. }
  7465. }
  7466. peer_unref(peer);
  7467. }
  7468. ao2_iterator_destroy(&i);
  7469. if (!peer) {
  7470. /* We checked our list and didn't find one. It's unlikely, but possible,
  7471. that we're trying to authenticate *to* a realtime peer */
  7472. const char *peer_name = ast_strdupa(p->peer);
  7473. ast_mutex_unlock(&iaxsl[callno]);
  7474. if ((peer = realtime_peer(peer_name, NULL))) {
  7475. ast_mutex_lock(&iaxsl[callno]);
  7476. if (!(p = iaxs[callno])) {
  7477. peer_unref(peer);
  7478. return -1;
  7479. }
  7480. res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, sin, p);
  7481. peer_unref(peer);
  7482. }
  7483. if (!peer) {
  7484. ast_mutex_lock(&iaxsl[callno]);
  7485. if (!(p = iaxs[callno]))
  7486. return -1;
  7487. }
  7488. }
  7489. }
  7490. if (ies->encmethods) {
  7491. ast_set_flag64(p, IAX_ENCRYPTED | IAX_KEYPOPULATED);
  7492. } else if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
  7493. ast_log(LOG_NOTICE, "Call initiated without encryption while forceencryption=yes option is set\n");
  7494. return -1; /* if force encryption is yes, and no encryption methods, then return -1 to hangup */
  7495. }
  7496. if (!res) {
  7497. struct ast_datastore *variablestore;
  7498. struct ast_variable *var, *prev = NULL;
  7499. AST_LIST_HEAD(, ast_var_t) *varlist;
  7500. varlist = ast_calloc(1, sizeof(*varlist));
  7501. variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
  7502. if (variablestore && varlist && p->owner) {
  7503. variablestore->data = varlist;
  7504. variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
  7505. AST_LIST_HEAD_INIT(varlist);
  7506. for (var = ies->vars; var; var = var->next) {
  7507. struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
  7508. if (prev)
  7509. ast_free(prev);
  7510. prev = var;
  7511. if (!newvar) {
  7512. /* Don't abort list traversal, as this would leave ies->vars in an inconsistent state. */
  7513. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  7514. } else {
  7515. AST_LIST_INSERT_TAIL(varlist, newvar, entries);
  7516. }
  7517. }
  7518. if (prev)
  7519. ast_free(prev);
  7520. ies->vars = NULL;
  7521. ast_channel_datastore_add(p->owner, variablestore);
  7522. } else {
  7523. if (p->owner)
  7524. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  7525. if (variablestore)
  7526. ast_datastore_free(variablestore);
  7527. if (varlist)
  7528. ast_free(varlist);
  7529. }
  7530. }
  7531. if (!res)
  7532. res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
  7533. return res;
  7534. }
  7535. static int iax2_do_register(struct iax2_registry *reg);
  7536. static void __iax2_do_register_s(const void *data)
  7537. {
  7538. struct iax2_registry *reg = (struct iax2_registry *)data;
  7539. if (ast_sockaddr_isnull(&reg->addr)) {
  7540. reg->addr.ss.ss_family = AST_AF_UNSPEC;
  7541. ast_dnsmgr_lookup(reg->hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL);
  7542. if (!ast_sockaddr_port(&reg->addr)) {
  7543. ast_sockaddr_set_port(&reg->addr, reg->port);
  7544. } else {
  7545. reg->port = ast_sockaddr_port(&reg->addr);
  7546. }
  7547. }
  7548. reg->expire = -1;
  7549. iax2_do_register(reg);
  7550. }
  7551. static int iax2_do_register_s(const void *data)
  7552. {
  7553. #ifdef SCHED_MULTITHREADED
  7554. if (schedule_action(__iax2_do_register_s, data))
  7555. #endif
  7556. __iax2_do_register_s(data);
  7557. return 0;
  7558. }
  7559. static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
  7560. {
  7561. int newcall = 0;
  7562. char newip[256];
  7563. struct iax_ie_data ied;
  7564. struct sockaddr_in new = { 0, };
  7565. memset(&ied, 0, sizeof(ied));
  7566. if (ies->apparent_addr)
  7567. memmove(&new, ies->apparent_addr, sizeof(new));
  7568. if (ies->callno)
  7569. newcall = ies->callno;
  7570. if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
  7571. ast_log(LOG_WARNING, "Invalid transfer request\n");
  7572. return -1;
  7573. }
  7574. pvt->transfercallno = newcall;
  7575. memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
  7576. inet_aton(newip, &pvt->transfer.sin_addr);
  7577. pvt->transfer.sin_family = AF_INET;
  7578. pvt->transferid = ies->transferid;
  7579. /* only store by transfercallno if this is a new transfer,
  7580. * just in case we get a duplicate TXREQ */
  7581. if (pvt->transferring == TRANSFER_NONE) {
  7582. store_by_transfercallno(pvt);
  7583. }
  7584. pvt->transferring = TRANSFER_BEGIN;
  7585. if (ies->transferid)
  7586. iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
  7587. send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
  7588. return 0;
  7589. }
  7590. static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
  7591. {
  7592. char exten[256] = "";
  7593. int status = CACHE_FLAG_UNKNOWN, expiry = iaxdefaultdpcache, x, matchmore = 0;
  7594. struct iax2_dpcache *dp = NULL;
  7595. if (ies->called_number)
  7596. ast_copy_string(exten, ies->called_number, sizeof(exten));
  7597. if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
  7598. status = CACHE_FLAG_EXISTS;
  7599. else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
  7600. status = CACHE_FLAG_CANEXIST;
  7601. else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
  7602. status = CACHE_FLAG_NONEXISTENT;
  7603. if (ies->refresh)
  7604. expiry = ies->refresh;
  7605. if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
  7606. matchmore = CACHE_FLAG_MATCHMORE;
  7607. AST_LIST_LOCK(&dpcache);
  7608. AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, peer_list) {
  7609. if (strcmp(dp->exten, exten))
  7610. continue;
  7611. AST_LIST_REMOVE_CURRENT(peer_list);
  7612. dp->callno = 0;
  7613. dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
  7614. if (dp->flags & CACHE_FLAG_PENDING) {
  7615. dp->flags &= ~CACHE_FLAG_PENDING;
  7616. dp->flags |= status;
  7617. dp->flags |= matchmore;
  7618. }
  7619. /* Wake up waiters */
  7620. for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
  7621. if (dp->waiters[x] > -1) {
  7622. if (write(dp->waiters[x], "asdf", 4) < 0) {
  7623. }
  7624. }
  7625. }
  7626. }
  7627. AST_LIST_TRAVERSE_SAFE_END;
  7628. AST_LIST_UNLOCK(&dpcache);
  7629. return 0;
  7630. }
  7631. static int complete_transfer(int callno, struct iax_ies *ies)
  7632. {
  7633. int peercallno = 0;
  7634. struct chan_iax2_pvt *pvt = iaxs[callno];
  7635. struct iax_frame *cur;
  7636. jb_frame frame;
  7637. if (ies->callno)
  7638. peercallno = ies->callno;
  7639. if (peercallno < 1) {
  7640. ast_log(LOG_WARNING, "Invalid transfer request\n");
  7641. return -1;
  7642. }
  7643. remove_by_transfercallno(pvt);
  7644. /* since a transfer has taken place, the address will change.
  7645. * This must be accounted for in the peercnts table. Remove
  7646. * the old address and add the new one */
  7647. peercnt_remove_by_addr(&pvt->addr);
  7648. peercnt_add(&pvt->transfer);
  7649. /* now copy over the new address */
  7650. memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
  7651. memset(&pvt->transfer, 0, sizeof(pvt->transfer));
  7652. /* Reset sequence numbers */
  7653. pvt->oseqno = 0;
  7654. pvt->rseqno = 0;
  7655. pvt->iseqno = 0;
  7656. pvt->aseqno = 0;
  7657. if (pvt->peercallno) {
  7658. remove_by_peercallno(pvt);
  7659. }
  7660. pvt->peercallno = peercallno;
  7661. /*this is where the transfering call swiches hash tables */
  7662. store_by_peercallno(pvt);
  7663. pvt->transferring = TRANSFER_NONE;
  7664. pvt->svoiceformat = -1;
  7665. pvt->voiceformat = 0;
  7666. pvt->svideoformat = -1;
  7667. pvt->videoformat = 0;
  7668. pvt->transfercallno = 0;
  7669. memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
  7670. memset(&pvt->offset, 0, sizeof(pvt->offset));
  7671. /* reset jitterbuffer */
  7672. while(jb_getall(pvt->jb,&frame) == JB_OK)
  7673. iax2_frame_free(frame.data);
  7674. jb_reset(pvt->jb);
  7675. pvt->lag = 0;
  7676. pvt->last = 0;
  7677. pvt->lastsent = 0;
  7678. pvt->nextpred = 0;
  7679. pvt->pingtime = DEFAULT_RETRY_TIME;
  7680. AST_LIST_TRAVERSE(&frame_queue[callno], cur, list) {
  7681. /* We must cancel any packets that would have been transmitted
  7682. because now we're talking to someone new. It's okay, they
  7683. were transmitted to someone that didn't care anyway. */
  7684. cur->retries = -1;
  7685. }
  7686. return 0;
  7687. }
  7688. /*! \brief Acknowledgment received for OUR registration */
  7689. static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
  7690. {
  7691. struct iax2_registry *reg;
  7692. /* Start pessimistic */
  7693. char peer[256] = "";
  7694. char msgstatus[60];
  7695. int refresh = 60;
  7696. char ourip[256] = "<Unspecified>";
  7697. struct sockaddr_in oldus;
  7698. struct sockaddr_in us;
  7699. int oldmsgs;
  7700. struct sockaddr_in reg_addr;
  7701. memset(&us, 0, sizeof(us));
  7702. if (ies->apparent_addr) {
  7703. memmove(&us, ies->apparent_addr, sizeof(us));
  7704. }
  7705. if (ies->username) {
  7706. ast_copy_string(peer, ies->username, sizeof(peer));
  7707. }
  7708. if (ies->refresh) {
  7709. refresh = ies->refresh;
  7710. }
  7711. if (ies->calling_number) {
  7712. /* We don't do anything with it really, but maybe we should */
  7713. }
  7714. reg = iaxs[callno]->reg;
  7715. if (!reg) {
  7716. ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
  7717. return -1;
  7718. }
  7719. memcpy(&oldus, &reg->us, sizeof(oldus));
  7720. oldmsgs = reg->messages;
  7721. ast_sockaddr_to_sin(&reg->addr, &reg_addr);
  7722. if (inaddrcmp(&reg_addr, sin)) {
  7723. ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin->sin_addr));
  7724. return -1;
  7725. }
  7726. memcpy(&reg->us, &us, sizeof(reg->us));
  7727. if (ies->msgcount >= 0) {
  7728. reg->messages = ies->msgcount & 0xffff; /* only low 16 bits are used in the transmission of the IE */
  7729. }
  7730. /* always refresh the registration at the interval requested by the server
  7731. we are registering to
  7732. */
  7733. reg->refresh = refresh;
  7734. reg->expire = iax2_sched_replace(reg->expire, sched,
  7735. (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
  7736. if (inaddrcmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) {
  7737. if (reg->messages > 255) {
  7738. snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
  7739. } else if (reg->messages > 1) {
  7740. snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting", reg->messages);
  7741. } else if (reg->messages > 0) {
  7742. ast_copy_string(msgstatus, " with 1 new message waiting", sizeof(msgstatus));
  7743. } else {
  7744. ast_copy_string(msgstatus, " with no messages waiting", sizeof(msgstatus));
  7745. }
  7746. snprintf(ourip, sizeof(ourip), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
  7747. ast_verb(3, "Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin->sin_addr), ourip, msgstatus);
  7748. manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin->sin_addr));
  7749. }
  7750. reg->regstate = REG_STATE_REGISTERED;
  7751. return 0;
  7752. }
  7753. static int iax2_append_register(const char *hostname, const char *username,
  7754. const char *secret, const char *porta)
  7755. {
  7756. struct iax2_registry *reg;
  7757. if (!(reg = ast_calloc(1, sizeof(*reg) + strlen(hostname) + 1))) {
  7758. return -1;
  7759. }
  7760. reg->addr.ss.ss_family = AF_INET;
  7761. if (ast_dnsmgr_lookup(hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL) < 0) {
  7762. ast_free(reg);
  7763. return -1;
  7764. }
  7765. ast_copy_string(reg->username, username, sizeof(reg->username));
  7766. strcpy(reg->hostname, hostname); /* Note: This is safe */
  7767. if (secret) {
  7768. ast_copy_string(reg->secret, secret, sizeof(reg->secret));
  7769. }
  7770. reg->expire = -1;
  7771. reg->refresh = IAX_DEFAULT_REG_EXPIRE;
  7772. reg->port = ast_sockaddr_port(&reg->addr);
  7773. if (!porta && !reg->port) {
  7774. reg->port = IAX_DEFAULT_PORTNO;
  7775. } else if (porta) {
  7776. sscanf(porta, "%5d", &reg->port);
  7777. }
  7778. ast_sockaddr_set_port(&reg->addr, reg->port);
  7779. AST_LIST_LOCK(&registrations);
  7780. AST_LIST_INSERT_HEAD(&registrations, reg, entry);
  7781. AST_LIST_UNLOCK(&registrations);
  7782. return 0;
  7783. }
  7784. static int iax2_register(const char *value, int lineno)
  7785. {
  7786. char copy[256];
  7787. char *username, *hostname, *secret;
  7788. char *porta;
  7789. char *stringp=NULL;
  7790. if (!value)
  7791. return -1;
  7792. ast_copy_string(copy, value, sizeof(copy));
  7793. stringp = copy;
  7794. username = strsep(&stringp, "@");
  7795. hostname = strsep(&stringp, "@");
  7796. if (!hostname) {
  7797. ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
  7798. return -1;
  7799. }
  7800. stringp = username;
  7801. username = strsep(&stringp, ":");
  7802. secret = strsep(&stringp, ":");
  7803. stringp = hostname;
  7804. hostname = strsep(&stringp, ":");
  7805. porta = strsep(&stringp, ":");
  7806. if (porta && !atoi(porta)) {
  7807. ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
  7808. return -1;
  7809. }
  7810. return iax2_append_register(hostname, username, secret, porta);
  7811. }
  7812. static void register_peer_exten(struct iax2_peer *peer, int onoff)
  7813. {
  7814. char multi[256];
  7815. char *stringp, *ext;
  7816. if (!ast_strlen_zero(regcontext)) {
  7817. ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
  7818. stringp = multi;
  7819. while((ext = strsep(&stringp, "&"))) {
  7820. if (onoff) {
  7821. if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
  7822. ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
  7823. "Noop", ast_strdup(peer->name), ast_free_ptr, "IAX2");
  7824. } else
  7825. ast_context_remove_extension(regcontext, ext, 1, NULL);
  7826. }
  7827. }
  7828. }
  7829. static void prune_peers(void);
  7830. static void unlink_peer(struct iax2_peer *peer)
  7831. {
  7832. if (peer->expire > -1) {
  7833. if (!AST_SCHED_DEL(sched, peer->expire)) {
  7834. peer->expire = -1;
  7835. peer_unref(peer);
  7836. }
  7837. }
  7838. if (peer->pokeexpire > -1) {
  7839. if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
  7840. peer->pokeexpire = -1;
  7841. peer_unref(peer);
  7842. }
  7843. }
  7844. ao2_unlink(peers, peer);
  7845. }
  7846. static void __expire_registry(const void *data)
  7847. {
  7848. struct iax2_peer *peer = (struct iax2_peer *) data;
  7849. if (!peer)
  7850. return;
  7851. if (peer->expire == -1) {
  7852. /* Removed already (possibly through CLI), ignore */
  7853. return;
  7854. }
  7855. peer->expire = -1;
  7856. ast_debug(1, "Expiring registration for peer '%s'\n", peer->name);
  7857. if (ast_test_flag64((&globalflags), IAX_RTUPDATE) && (ast_test_flag64(peer, IAX_TEMPONLY|IAX_RTCACHEFRIENDS)))
  7858. realtime_update_peer(peer->name, &peer->addr, 0);
  7859. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
  7860. /* modify entry in peercnts table as _not_ registered */
  7861. peercnt_modify((unsigned char) 0, 0, &peer->addr);
  7862. /* Reset the address */
  7863. memset(&peer->addr, 0, sizeof(peer->addr));
  7864. /* Reset expiry value */
  7865. peer->expiry = min_reg_expire;
  7866. if (!ast_test_flag64(peer, IAX_TEMPONLY))
  7867. ast_db_del("IAX/Registry", peer->name);
  7868. register_peer_exten(peer, 0);
  7869. ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
  7870. if (iax2_regfunk)
  7871. iax2_regfunk(peer->name, 0);
  7872. if (ast_test_flag64(peer, IAX_RTAUTOCLEAR))
  7873. unlink_peer(peer);
  7874. peer_unref(peer);
  7875. }
  7876. static int expire_registry(const void *data)
  7877. {
  7878. #ifdef SCHED_MULTITHREADED
  7879. if (schedule_action(__expire_registry, data))
  7880. #endif
  7881. __expire_registry(data);
  7882. return 0;
  7883. }
  7884. static void reg_source_db(struct iax2_peer *p)
  7885. {
  7886. char data[80];
  7887. char *expiry;
  7888. if (ast_test_flag64(p, IAX_TEMPONLY) || ast_db_get("IAX/Registry", p->name, data, sizeof(data))) {
  7889. return;
  7890. }
  7891. expiry = strrchr(data, ':');
  7892. if (!expiry) {
  7893. ast_log(LOG_NOTICE, "IAX/Registry astdb entry missing expiry: '%s'\n", data);
  7894. return;
  7895. }
  7896. *expiry++ = '\0';
  7897. if (!ast_sockaddr_parse(&p->addr, data, PARSE_PORT_REQUIRE)) {
  7898. ast_log(LOG_NOTICE, "IAX/Registry astdb host:port invalid - '%s'\n", data);
  7899. return;
  7900. }
  7901. p->expiry = atoi(expiry);
  7902. ast_verb(3, "Seeding '%s' at %s for %d\n", p->name,
  7903. ast_sockaddr_stringify(&p->addr), p->expiry);
  7904. iax2_poke_peer(p, 0);
  7905. if (p->expire > -1) {
  7906. if (!AST_SCHED_DEL(sched, p->expire)) {
  7907. p->expire = -1;
  7908. peer_unref(p);
  7909. }
  7910. }
  7911. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
  7912. p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
  7913. if (p->expire == -1) {
  7914. peer_unref(p);
  7915. }
  7916. if (iax2_regfunk) {
  7917. iax2_regfunk(p->name, 1);
  7918. }
  7919. register_peer_exten(p, 1);
  7920. }
  7921. /*!
  7922. * \pre iaxsl[callno] is locked
  7923. *
  7924. * \note Since this function calls send_command_final(), the pvt struct for
  7925. * the given call number may disappear while executing this function.
  7926. */
  7927. static int update_registry(struct sockaddr_in *sin, int callno, char *devtype, int fd, unsigned short refresh)
  7928. {
  7929. /* Called from IAX thread only, with proper iaxsl lock */
  7930. struct iax_ie_data ied = {
  7931. .pos = 0,
  7932. };
  7933. struct iax2_peer *p;
  7934. int msgcount;
  7935. char data[80];
  7936. int version;
  7937. const char *peer_name;
  7938. int res = -1;
  7939. struct ast_sockaddr sockaddr;
  7940. ast_sockaddr_from_sin(&sockaddr, sin);
  7941. peer_name = ast_strdupa(iaxs[callno]->peer);
  7942. /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
  7943. ast_mutex_unlock(&iaxsl[callno]);
  7944. if (!(p = find_peer(peer_name, 1))) {
  7945. ast_mutex_lock(&iaxsl[callno]);
  7946. ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
  7947. return -1;
  7948. }
  7949. ast_mutex_lock(&iaxsl[callno]);
  7950. if (!iaxs[callno])
  7951. goto return_unref;
  7952. if (ast_test_flag64((&globalflags), IAX_RTUPDATE) && (ast_test_flag64(p, IAX_TEMPONLY|IAX_RTCACHEFRIENDS))) {
  7953. if (sin->sin_addr.s_addr) {
  7954. time_t nowtime;
  7955. time(&nowtime);
  7956. realtime_update_peer(peer_name, &sockaddr, nowtime);
  7957. } else {
  7958. realtime_update_peer(peer_name, &sockaddr, 0);
  7959. }
  7960. }
  7961. /* treat an unspecified refresh interval as the minimum */
  7962. if (!refresh) {
  7963. refresh = min_reg_expire;
  7964. }
  7965. if (refresh > max_reg_expire) {
  7966. ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
  7967. p->name, max_reg_expire, refresh);
  7968. p->expiry = max_reg_expire;
  7969. } else if (refresh < min_reg_expire) {
  7970. ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
  7971. p->name, min_reg_expire, refresh);
  7972. p->expiry = min_reg_expire;
  7973. } else {
  7974. p->expiry = refresh;
  7975. }
  7976. if (ast_sockaddr_cmp(&p->addr, &sockaddr)) {
  7977. if (iax2_regfunk) {
  7978. iax2_regfunk(p->name, 1);
  7979. }
  7980. /* modify entry in peercnts table as _not_ registered */
  7981. peercnt_modify((unsigned char) 0, 0, &p->addr);
  7982. /* Stash the IP address from which they registered */
  7983. ast_sockaddr_from_sin(&p->addr, sin);
  7984. snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p->expiry);
  7985. if (!ast_test_flag64(p, IAX_TEMPONLY) && sin->sin_addr.s_addr) {
  7986. ast_db_put("IAX/Registry", p->name, data);
  7987. ast_verb(3, "Registered IAX2 '%s' (%s) at %s:%d\n", p->name,
  7988. ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
  7989. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\nPort: %d\r\n", p->name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
  7990. register_peer_exten(p, 1);
  7991. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
  7992. } else if (!ast_test_flag64(p, IAX_TEMPONLY)) {
  7993. ast_verb(3, "Unregistered IAX2 '%s' (%s)\n", p->name,
  7994. ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
  7995. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p->name);
  7996. register_peer_exten(p, 0);
  7997. ast_db_del("IAX/Registry", p->name);
  7998. ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
  7999. }
  8000. /* Update the host */
  8001. /* Verify that the host is really there */
  8002. iax2_poke_peer(p, callno);
  8003. }
  8004. /* modify entry in peercnts table as registered */
  8005. if (p->maxcallno) {
  8006. peercnt_modify((unsigned char) 1, p->maxcallno, &p->addr);
  8007. }
  8008. /* Make sure our call still exists, an INVAL at the right point may make it go away */
  8009. if (!iaxs[callno]) {
  8010. res = -1;
  8011. goto return_unref;
  8012. }
  8013. /* Store socket fd */
  8014. p->sockfd = fd;
  8015. /* Setup the expiry */
  8016. if (p->expire > -1) {
  8017. if (!AST_SCHED_DEL(sched, p->expire)) {
  8018. p->expire = -1;
  8019. peer_unref(p);
  8020. }
  8021. }
  8022. if (p->expiry && sin->sin_addr.s_addr) {
  8023. p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
  8024. if (p->expire == -1)
  8025. peer_unref(p);
  8026. }
  8027. iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
  8028. iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(p->zonetag));
  8029. if (sin->sin_addr.s_addr) {
  8030. struct sockaddr_in peer_addr;
  8031. ast_sockaddr_to_sin(&p->addr, &peer_addr);
  8032. iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expiry);
  8033. iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &peer_addr);
  8034. if (!ast_strlen_zero(p->mailbox)) {
  8035. struct ast_event *event;
  8036. int new, old;
  8037. char *mailbox, *context;
  8038. context = mailbox = ast_strdupa(p->mailbox);
  8039. strsep(&context, "@");
  8040. if (ast_strlen_zero(context))
  8041. context = "default";
  8042. event = ast_event_get_cached(AST_EVENT_MWI,
  8043. AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
  8044. AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
  8045. AST_EVENT_IE_END);
  8046. if (event) {
  8047. new = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
  8048. old = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
  8049. ast_event_destroy(event);
  8050. } else { /* Fall back on checking the mailbox directly */
  8051. ast_app_inboxcount(p->mailbox, &new, &old);
  8052. }
  8053. if (new > 255) {
  8054. new = 255;
  8055. }
  8056. if (old > 255) {
  8057. old = 255;
  8058. }
  8059. msgcount = (old << 8) | new;
  8060. iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
  8061. }
  8062. if (ast_test_flag64(p, IAX_HASCALLERID)) {
  8063. iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, p->cid_num);
  8064. iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->cid_name);
  8065. }
  8066. }
  8067. version = iax_check_version(devtype);
  8068. if (version)
  8069. iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
  8070. res = 0;
  8071. return_unref:
  8072. peer_unref(p);
  8073. return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
  8074. }
  8075. static int registry_authrequest(int callno)
  8076. {
  8077. struct iax_ie_data ied;
  8078. struct iax2_peer *p;
  8079. char challenge[10];
  8080. const char *peer_name;
  8081. int sentauthmethod;
  8082. peer_name = ast_strdupa(iaxs[callno]->peer);
  8083. /* SLD: third call to find_peer in registration */
  8084. ast_mutex_unlock(&iaxsl[callno]);
  8085. if ((p = find_peer(peer_name, 1))) {
  8086. last_authmethod = p->authmethods;
  8087. }
  8088. ast_mutex_lock(&iaxsl[callno]);
  8089. if (!iaxs[callno])
  8090. goto return_unref;
  8091. memset(&ied, 0, sizeof(ied));
  8092. /* The selection of which delayed reject is sent may leak information,
  8093. * if it sets a static response. For example, if a host is known to only
  8094. * use MD5 authentication, then an RSA response would indicate that the
  8095. * peer does not exist, and vice-versa.
  8096. * Therefore, we use whatever the last peer used (which may vary over the
  8097. * course of a server, which should leak minimal information). */
  8098. sentauthmethod = p ? p->authmethods : last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
  8099. if (!p) {
  8100. iaxs[callno]->authmethods = sentauthmethod;
  8101. }
  8102. iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, sentauthmethod);
  8103. if (sentauthmethod & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
  8104. /* Build the challenge */
  8105. snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
  8106. ast_string_field_set(iaxs[callno], challenge, challenge);
  8107. iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
  8108. }
  8109. iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
  8110. return_unref:
  8111. if (p) {
  8112. peer_unref(p);
  8113. }
  8114. return iaxs[callno] ? send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1) : -1;
  8115. }
  8116. static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
  8117. {
  8118. struct iax2_registry *reg;
  8119. /* Start pessimistic */
  8120. struct iax_ie_data ied;
  8121. char peer[256] = "";
  8122. char challenge[256] = "";
  8123. int res;
  8124. int authmethods = 0;
  8125. if (ies->authmethods)
  8126. authmethods = ies->authmethods;
  8127. if (ies->username)
  8128. ast_copy_string(peer, ies->username, sizeof(peer));
  8129. if (ies->challenge)
  8130. ast_copy_string(challenge, ies->challenge, sizeof(challenge));
  8131. memset(&ied, 0, sizeof(ied));
  8132. reg = iaxs[callno]->reg;
  8133. if (reg) {
  8134. struct sockaddr_in reg_addr;
  8135. ast_sockaddr_to_sin(&reg->addr, &reg_addr);
  8136. if (inaddrcmp(&reg_addr, sin)) {
  8137. ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin->sin_addr));
  8138. return -1;
  8139. }
  8140. if (ast_strlen_zero(reg->secret)) {
  8141. ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
  8142. reg->regstate = REG_STATE_NOAUTH;
  8143. return -1;
  8144. }
  8145. iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
  8146. iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
  8147. if (reg->secret[0] == '[') {
  8148. char tmpkey[256];
  8149. ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
  8150. tmpkey[strlen(tmpkey) - 1] = '\0';
  8151. res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin, NULL);
  8152. } else
  8153. res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin, NULL);
  8154. if (!res) {
  8155. reg->regstate = REG_STATE_AUTHSENT;
  8156. add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
  8157. return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
  8158. } else
  8159. return -1;
  8160. ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
  8161. } else
  8162. ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
  8163. return -1;
  8164. }
  8165. static void stop_stuff(int callno)
  8166. {
  8167. iax2_destroy_helper(iaxs[callno]);
  8168. }
  8169. static void __auth_reject(const void *nothing)
  8170. {
  8171. /* Called from IAX thread only, without iaxs lock */
  8172. int callno = (int)(long)(nothing);
  8173. struct iax_ie_data ied;
  8174. ast_mutex_lock(&iaxsl[callno]);
  8175. if (iaxs[callno]) {
  8176. memset(&ied, 0, sizeof(ied));
  8177. if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
  8178. iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
  8179. iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_REJECTED);
  8180. } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
  8181. iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
  8182. iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
  8183. }
  8184. send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
  8185. }
  8186. ast_mutex_unlock(&iaxsl[callno]);
  8187. }
  8188. static int auth_reject(const void *data)
  8189. {
  8190. int callno = (int)(long)(data);
  8191. ast_mutex_lock(&iaxsl[callno]);
  8192. if (iaxs[callno])
  8193. iaxs[callno]->authid = -1;
  8194. ast_mutex_unlock(&iaxsl[callno]);
  8195. #ifdef SCHED_MULTITHREADED
  8196. if (schedule_action(__auth_reject, data))
  8197. #endif
  8198. __auth_reject(data);
  8199. return 0;
  8200. }
  8201. static int auth_fail(int callno, int failcode)
  8202. {
  8203. /* Schedule sending the authentication failure in one second, to prevent
  8204. guessing */
  8205. if (iaxs[callno]) {
  8206. iaxs[callno]->authfail = failcode;
  8207. if (delayreject) {
  8208. iaxs[callno]->authid = iax2_sched_replace(iaxs[callno]->authid,
  8209. sched, 1000, auth_reject, (void *)(long)callno);
  8210. } else
  8211. auth_reject((void *)(long)callno);
  8212. }
  8213. return 0;
  8214. }
  8215. static void __auto_hangup(const void *nothing)
  8216. {
  8217. /* Called from IAX thread only, without iaxs lock */
  8218. int callno = (int)(long)(nothing);
  8219. struct iax_ie_data ied;
  8220. ast_mutex_lock(&iaxsl[callno]);
  8221. if (iaxs[callno]) {
  8222. memset(&ied, 0, sizeof(ied));
  8223. iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
  8224. iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_NO_USER_RESPONSE);
  8225. send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
  8226. }
  8227. ast_mutex_unlock(&iaxsl[callno]);
  8228. }
  8229. static int auto_hangup(const void *data)
  8230. {
  8231. int callno = (int)(long)(data);
  8232. ast_mutex_lock(&iaxsl[callno]);
  8233. if (iaxs[callno]) {
  8234. iaxs[callno]->autoid = -1;
  8235. }
  8236. ast_mutex_unlock(&iaxsl[callno]);
  8237. #ifdef SCHED_MULTITHREADED
  8238. if (schedule_action(__auto_hangup, data))
  8239. #endif
  8240. __auto_hangup(data);
  8241. return 0;
  8242. }
  8243. static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
  8244. {
  8245. struct iax_ie_data ied;
  8246. /* Auto-hangup with 30 seconds of inactivity */
  8247. iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
  8248. sched, 30000, auto_hangup, (void *)(long)callno);
  8249. memset(&ied, 0, sizeof(ied));
  8250. iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
  8251. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
  8252. dp->flags |= CACHE_FLAG_TRANSMITTED;
  8253. }
  8254. static int iax2_vnak(int callno)
  8255. {
  8256. return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
  8257. }
  8258. static void vnak_retransmit(int callno, int last)
  8259. {
  8260. struct iax_frame *f;
  8261. AST_LIST_TRAVERSE(&frame_queue[callno], f, list) {
  8262. /* Send a copy immediately */
  8263. if (((unsigned char) (f->oseqno - last) < 128) &&
  8264. (f->retries >= 0)) {
  8265. send_packet(f);
  8266. }
  8267. }
  8268. }
  8269. static void __iax2_poke_peer_s(const void *data)
  8270. {
  8271. struct iax2_peer *peer = (struct iax2_peer *)data;
  8272. iax2_poke_peer(peer, 0);
  8273. peer_unref(peer);
  8274. }
  8275. static int iax2_poke_peer_s(const void *data)
  8276. {
  8277. struct iax2_peer *peer = (struct iax2_peer *)data;
  8278. peer->pokeexpire = -1;
  8279. #ifdef SCHED_MULTITHREADED
  8280. if (schedule_action(__iax2_poke_peer_s, data))
  8281. #endif
  8282. __iax2_poke_peer_s(data);
  8283. return 0;
  8284. }
  8285. static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
  8286. {
  8287. int res = 0;
  8288. struct iax_frame *fr;
  8289. struct ast_iax2_meta_hdr *meta;
  8290. struct ast_iax2_meta_trunk_hdr *mth;
  8291. int calls = 0;
  8292. /* Point to frame */
  8293. fr = (struct iax_frame *)tpeer->trunkdata;
  8294. /* Point to meta data */
  8295. meta = (struct ast_iax2_meta_hdr *)fr->afdata;
  8296. mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
  8297. if (tpeer->trunkdatalen) {
  8298. /* We're actually sending a frame, so fill the meta trunk header and meta header */
  8299. meta->zeros = 0;
  8300. meta->metacmd = IAX_META_TRUNK;
  8301. if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS))
  8302. meta->cmddata = IAX_META_TRUNK_MINI;
  8303. else
  8304. meta->cmddata = IAX_META_TRUNK_SUPERMINI;
  8305. mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
  8306. /* And the rest of the ast_iax2 header */
  8307. fr->direction = DIRECTION_OUTGRESS;
  8308. fr->retrans = -1;
  8309. fr->transfer = 0;
  8310. /* Any appropriate call will do */
  8311. fr->data = fr->afdata;
  8312. fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
  8313. res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
  8314. calls = tpeer->calls;
  8315. #if 0
  8316. ast_debug(1, "Trunking %d call chunks in %d bytes to %s:%d, ts=%d\n", calls, fr->datalen, ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), ntohl(mth->ts));
  8317. #endif
  8318. /* Reset transmit trunk side data */
  8319. tpeer->trunkdatalen = 0;
  8320. tpeer->calls = 0;
  8321. }
  8322. if (res < 0)
  8323. return res;
  8324. return calls;
  8325. }
  8326. static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
  8327. {
  8328. /* Drop when trunk is about 5 seconds idle */
  8329. if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
  8330. return 1;
  8331. return 0;
  8332. }
  8333. static int timing_read(int *id, int fd, short events, void *cbdata)
  8334. {
  8335. int res, processed = 0, totalcalls = 0;
  8336. struct iax2_trunk_peer *tpeer = NULL, *drop = NULL;
  8337. struct timeval now = ast_tvnow();
  8338. if (iaxtrunkdebug)
  8339. ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", trunkmaxsize);
  8340. if (timer) {
  8341. if (ast_timer_ack(timer, 1) < 0) {
  8342. ast_log(LOG_ERROR, "Timer failed acknowledge\n");
  8343. return 0;
  8344. }
  8345. }
  8346. /* For each peer that supports trunking... */
  8347. AST_LIST_LOCK(&tpeers);
  8348. AST_LIST_TRAVERSE_SAFE_BEGIN(&tpeers, tpeer, list) {
  8349. processed++;
  8350. res = 0;
  8351. ast_mutex_lock(&tpeer->lock);
  8352. /* We can drop a single tpeer per pass. That makes all this logic
  8353. substantially easier */
  8354. if (!drop && iax2_trunk_expired(tpeer, &now)) {
  8355. /* Take it out of the list, but don't free it yet, because it
  8356. could be in use */
  8357. AST_LIST_REMOVE_CURRENT(list);
  8358. drop = tpeer;
  8359. } else {
  8360. res = send_trunk(tpeer, &now);
  8361. trunk_timed++;
  8362. if (iaxtrunkdebug)
  8363. ast_verbose(" - Trunk peer (%s:%d) has %d call chunk%s in transit, %u bytes backloged and has hit a high water mark of %u bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), res, (res != 1) ? "s" : "", tpeer->trunkdatalen, tpeer->trunkdataalloc);
  8364. }
  8365. totalcalls += res;
  8366. res = 0;
  8367. ast_mutex_unlock(&tpeer->lock);
  8368. }
  8369. AST_LIST_TRAVERSE_SAFE_END;
  8370. AST_LIST_UNLOCK(&tpeers);
  8371. if (drop) {
  8372. ast_mutex_lock(&drop->lock);
  8373. /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
  8374. because by the time they could get tpeerlock, we've already grabbed it */
  8375. ast_debug(1, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop->addr.sin_addr), ntohs(drop->addr.sin_port));
  8376. if (drop->trunkdata) {
  8377. ast_free(drop->trunkdata);
  8378. drop->trunkdata = NULL;
  8379. }
  8380. ast_mutex_unlock(&drop->lock);
  8381. ast_mutex_destroy(&drop->lock);
  8382. ast_free(drop);
  8383. }
  8384. if (iaxtrunkdebug)
  8385. ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
  8386. iaxtrunkdebug = 0;
  8387. return 1;
  8388. }
  8389. struct dpreq_data {
  8390. int callno;
  8391. char context[AST_MAX_EXTENSION];
  8392. char callednum[AST_MAX_EXTENSION];
  8393. char *callerid;
  8394. };
  8395. static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
  8396. {
  8397. unsigned short dpstatus = 0;
  8398. struct iax_ie_data ied1;
  8399. int mm;
  8400. memset(&ied1, 0, sizeof(ied1));
  8401. mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
  8402. /* Must be started */
  8403. if (ast_parking_ext_valid(callednum, NULL, context) || ast_exists_extension(NULL, context, callednum, 1, callerid)) {
  8404. dpstatus = IAX_DPSTATUS_EXISTS;
  8405. } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
  8406. dpstatus = IAX_DPSTATUS_CANEXIST;
  8407. } else {
  8408. dpstatus = IAX_DPSTATUS_NONEXISTENT;
  8409. }
  8410. if (ast_ignore_pattern(context, callednum))
  8411. dpstatus |= IAX_DPSTATUS_IGNOREPAT;
  8412. if (mm)
  8413. dpstatus |= IAX_DPSTATUS_MATCHMORE;
  8414. if (!skiplock)
  8415. ast_mutex_lock(&iaxsl[callno]);
  8416. if (iaxs[callno]) {
  8417. iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
  8418. iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
  8419. iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
  8420. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
  8421. }
  8422. if (!skiplock)
  8423. ast_mutex_unlock(&iaxsl[callno]);
  8424. }
  8425. static void *dp_lookup_thread(void *data)
  8426. {
  8427. /* Look up for dpreq */
  8428. struct dpreq_data *dpr = data;
  8429. dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
  8430. if (dpr->callerid)
  8431. ast_free(dpr->callerid);
  8432. ast_free(dpr);
  8433. return NULL;
  8434. }
  8435. static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
  8436. {
  8437. pthread_t newthread;
  8438. struct dpreq_data *dpr;
  8439. if (!(dpr = ast_calloc(1, sizeof(*dpr))))
  8440. return;
  8441. dpr->callno = callno;
  8442. ast_copy_string(dpr->context, context, sizeof(dpr->context));
  8443. ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
  8444. if (callerid)
  8445. dpr->callerid = ast_strdup(callerid);
  8446. if (ast_pthread_create_detached(&newthread, NULL, dp_lookup_thread, dpr)) {
  8447. ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
  8448. }
  8449. }
  8450. struct iax_dual {
  8451. struct ast_channel *chan1;
  8452. struct ast_channel *chan2;
  8453. char *park_exten;
  8454. char *park_context;
  8455. };
  8456. static void *iax_park_thread(void *stuff)
  8457. {
  8458. struct iax_dual *d;
  8459. int res;
  8460. int ext = 0;
  8461. d = stuff;
  8462. ast_debug(4, "IAX Park: Transferer channel %s, Transferee %s\n",
  8463. ast_channel_name(d->chan2), ast_channel_name(d->chan1));
  8464. res = ast_park_call_exten(d->chan1, d->chan2, d->park_exten, d->park_context, 0, &ext);
  8465. if (res) {
  8466. /* Parking failed. */
  8467. ast_hangup(d->chan1);
  8468. } else {
  8469. ast_log(LOG_NOTICE, "Parked on extension '%d'\n", ext);
  8470. }
  8471. ast_hangup(d->chan2);
  8472. ast_free(d->park_exten);
  8473. ast_free(d->park_context);
  8474. ast_free(d);
  8475. return NULL;
  8476. }
  8477. /*! DO NOT hold any locks while calling iax_park */
  8478. static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2, const char *park_exten, const char *park_context)
  8479. {
  8480. struct iax_dual *d;
  8481. struct ast_channel *chan1m, *chan2m;/* Chan2m: The transferer, chan1m: The transferee */
  8482. pthread_t th;
  8483. chan1m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, ast_channel_accountcode(chan2), ast_channel_exten(chan1), ast_channel_context(chan1), ast_channel_linkedid(chan1), ast_channel_amaflags(chan1), "Parking/%s", ast_channel_name(chan1));
  8484. chan2m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, ast_channel_accountcode(chan2), ast_channel_exten(chan2), ast_channel_context(chan2), ast_channel_linkedid(chan2), ast_channel_amaflags(chan2), "IAXPeer/%s", ast_channel_name(chan2));
  8485. d = ast_calloc(1, sizeof(*d));
  8486. if (!chan1m || !chan2m || !d) {
  8487. if (chan1m) {
  8488. ast_hangup(chan1m);
  8489. }
  8490. if (chan2m) {
  8491. ast_hangup(chan2m);
  8492. }
  8493. ast_free(d);
  8494. return -1;
  8495. }
  8496. d->park_exten = ast_strdup(park_exten);
  8497. d->park_context = ast_strdup(park_context);
  8498. if (!d->park_exten || !d->park_context) {
  8499. ast_hangup(chan1m);
  8500. ast_hangup(chan2m);
  8501. ast_free(d->park_exten);
  8502. ast_free(d->park_context);
  8503. ast_free(d);
  8504. return -1;
  8505. }
  8506. /* Make formats okay */
  8507. ast_format_copy(ast_channel_readformat(chan1m), ast_channel_readformat(chan1));
  8508. ast_format_copy(ast_channel_writeformat(chan1m), ast_channel_writeformat(chan1));
  8509. /* Prepare for taking over the channel */
  8510. if (ast_channel_masquerade(chan1m, chan1)) {
  8511. ast_hangup(chan1m);
  8512. ast_hangup(chan2m);
  8513. ast_free(d->park_exten);
  8514. ast_free(d->park_context);
  8515. ast_free(d);
  8516. return -1;
  8517. }
  8518. /* Setup the extensions and such */
  8519. ast_channel_context_set(chan1m, ast_channel_context(chan1));
  8520. ast_channel_exten_set(chan1m, ast_channel_exten(chan1));
  8521. ast_channel_priority_set(chan1m, ast_channel_priority(chan1));
  8522. ast_do_masquerade(chan1m);
  8523. /* We make a clone of the peer channel too, so we can play
  8524. back the announcement */
  8525. /* Make formats okay */
  8526. ast_format_copy(ast_channel_readformat(chan2m), ast_channel_readformat(chan2));
  8527. ast_format_copy(ast_channel_writeformat(chan2m), ast_channel_writeformat(chan2));
  8528. ast_channel_parkinglot_set(chan2m, ast_channel_parkinglot(chan2));
  8529. /* Prepare for taking over the channel */
  8530. if (ast_channel_masquerade(chan2m, chan2)) {
  8531. ast_hangup(chan1m);
  8532. ast_hangup(chan2m);
  8533. ast_free(d->park_exten);
  8534. ast_free(d->park_context);
  8535. ast_free(d);
  8536. return -1;
  8537. }
  8538. /* Setup the extensions and such */
  8539. ast_channel_context_set(chan2m, ast_channel_context(chan2));
  8540. ast_channel_exten_set(chan2m, ast_channel_exten(chan2));
  8541. ast_channel_priority_set(chan2m, ast_channel_priority(chan2));
  8542. ast_do_masquerade(chan2m);
  8543. d->chan1 = chan1m; /* Transferee */
  8544. d->chan2 = chan2m; /* Transferer */
  8545. if (ast_pthread_create_detached_background(&th, NULL, iax_park_thread, d) < 0) {
  8546. /* Could not start thread */
  8547. ast_hangup(chan1m);
  8548. ast_hangup(chan2m);
  8549. ast_free(d->park_exten);
  8550. ast_free(d->park_context);
  8551. ast_free(d);
  8552. return -1;
  8553. }
  8554. return 0;
  8555. }
  8556. static int check_provisioning(struct sockaddr_in *sin, int sockfd, char *si, unsigned int ver)
  8557. {
  8558. unsigned int ourver;
  8559. char rsi[80];
  8560. snprintf(rsi, sizeof(rsi), "si-%s", si);
  8561. if (iax_provision_version(&ourver, rsi, 1))
  8562. return 0;
  8563. ast_debug(1, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
  8564. if (ourver != ver)
  8565. iax2_provision(sin, sockfd, NULL, rsi, 1);
  8566. return 0;
  8567. }
  8568. static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
  8569. {
  8570. jb_info stats;
  8571. jb_getinfo(pvt->jb, &stats);
  8572. memset(iep, 0, sizeof(*iep));
  8573. iax_ie_append_int(iep,IAX_IE_RR_JITTER, stats.jitter);
  8574. if(stats.frames_in == 0) stats.frames_in = 1;
  8575. iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
  8576. iax_ie_append_int(iep,IAX_IE_RR_PKTS, stats.frames_in);
  8577. iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
  8578. iax_ie_append_int(iep,IAX_IE_RR_DROPPED, stats.frames_dropped);
  8579. iax_ie_append_int(iep,IAX_IE_RR_OOO, stats.frames_ooo);
  8580. }
  8581. static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
  8582. {
  8583. iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
  8584. iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
  8585. iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
  8586. iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
  8587. iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
  8588. iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
  8589. iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
  8590. }
  8591. static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
  8592. {
  8593. int i;
  8594. unsigned int length, offset = 0;
  8595. char full_osptoken[IAX_MAX_OSPBUFF_SIZE];
  8596. for (i = 0; i < IAX_MAX_OSPBLOCK_NUM; i++) {
  8597. length = ies->ospblocklength[i];
  8598. if (length != 0) {
  8599. if (length > IAX_MAX_OSPBLOCK_SIZE) {
  8600. /* OSP token block length wrong, clear buffer */
  8601. offset = 0;
  8602. break;
  8603. } else {
  8604. memcpy(full_osptoken + offset, ies->osptokenblock[i], length);
  8605. offset += length;
  8606. }
  8607. } else {
  8608. break;
  8609. }
  8610. }
  8611. *(full_osptoken + offset) = '\0';
  8612. if (strlen(full_osptoken) != offset) {
  8613. /* OSP token length wrong, clear buffer */
  8614. *full_osptoken = '\0';
  8615. }
  8616. ast_string_field_set(iaxs[fr->callno], osptoken, full_osptoken);
  8617. }
  8618. static void log_jitterstats(unsigned short callno)
  8619. {
  8620. int localjitter = -1, localdelay = 0, locallost = -1, locallosspct = -1, localdropped = 0, localooo = -1, localpackets = -1;
  8621. jb_info jbinfo;
  8622. ast_mutex_lock(&iaxsl[callno]);
  8623. if (iaxs[callno] && iaxs[callno]->owner && ast_channel_name(iaxs[callno]->owner)) {
  8624. if(ast_test_flag64(iaxs[callno], IAX_USEJITTERBUF)) {
  8625. jb_getinfo(iaxs[callno]->jb, &jbinfo);
  8626. localjitter = jbinfo.jitter;
  8627. localdelay = jbinfo.current - jbinfo.min;
  8628. locallost = jbinfo.frames_lost;
  8629. locallosspct = jbinfo.losspct/1000;
  8630. localdropped = jbinfo.frames_dropped;
  8631. localooo = jbinfo.frames_ooo;
  8632. localpackets = jbinfo.frames_in;
  8633. }
  8634. ast_debug(3, "JB STATS:%s ping=%u ljitterms=%d ljbdelayms=%d ltotlost=%d lrecentlosspct=%d ldropped=%d looo=%d lrecvd=%d rjitterms=%d rjbdelayms=%d rtotlost=%d rrecentlosspct=%d rdropped=%d rooo=%d rrecvd=%d\n",
  8635. ast_channel_name(iaxs[callno]->owner),
  8636. iaxs[callno]->pingtime,
  8637. localjitter,
  8638. localdelay,
  8639. locallost,
  8640. locallosspct,
  8641. localdropped,
  8642. localooo,
  8643. localpackets,
  8644. iaxs[callno]->remote_rr.jitter,
  8645. iaxs[callno]->remote_rr.delay,
  8646. iaxs[callno]->remote_rr.losscnt,
  8647. iaxs[callno]->remote_rr.losspct/1000,
  8648. iaxs[callno]->remote_rr.dropped,
  8649. iaxs[callno]->remote_rr.ooo,
  8650. iaxs[callno]->remote_rr.packets);
  8651. manager_event(EVENT_FLAG_REPORTING, "JitterBufStats", "Owner: %s\r\nPing: %u\r\nLocalJitter: %d\r\nLocalJBDelay: %d\r\nLocalTotalLost: %d\r\nLocalLossPercent: %d\r\nLocalDropped: %d\r\nLocalooo: %d\r\nLocalReceived: %d\r\nRemoteJitter: %d\r\nRemoteJBDelay: %d\r\nRemoteTotalLost: %d\r\nRemoteLossPercent: %d\r\nRemoteDropped: %d\r\nRemoteooo: %d\r\nRemoteReceived: %d\r\n",
  8652. ast_channel_name(iaxs[callno]->owner),
  8653. iaxs[callno]->pingtime,
  8654. localjitter,
  8655. localdelay,
  8656. locallost,
  8657. locallosspct,
  8658. localdropped,
  8659. localooo,
  8660. localpackets,
  8661. iaxs[callno]->remote_rr.jitter,
  8662. iaxs[callno]->remote_rr.delay,
  8663. iaxs[callno]->remote_rr.losscnt,
  8664. iaxs[callno]->remote_rr.losspct/1000,
  8665. iaxs[callno]->remote_rr.dropped,
  8666. iaxs[callno]->remote_rr.ooo,
  8667. iaxs[callno]->remote_rr.packets);
  8668. }
  8669. ast_mutex_unlock(&iaxsl[callno]);
  8670. }
  8671. static int socket_process(struct iax2_thread *thread);
  8672. /*!
  8673. * \brief Handle any deferred full frames for this thread
  8674. */
  8675. static void handle_deferred_full_frames(struct iax2_thread *thread)
  8676. {
  8677. struct iax2_pkt_buf *pkt_buf;
  8678. ast_mutex_lock(&thread->lock);
  8679. while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
  8680. ast_mutex_unlock(&thread->lock);
  8681. thread->buf = pkt_buf->buf;
  8682. thread->buf_len = pkt_buf->len;
  8683. thread->buf_size = pkt_buf->len + 1;
  8684. socket_process(thread);
  8685. thread->buf = NULL;
  8686. ast_free(pkt_buf);
  8687. ast_mutex_lock(&thread->lock);
  8688. }
  8689. ast_mutex_unlock(&thread->lock);
  8690. }
  8691. /*!
  8692. * \brief Queue the last read full frame for processing by a certain thread
  8693. *
  8694. * If there are already any full frames queued, they are sorted
  8695. * by sequence number.
  8696. */
  8697. static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
  8698. {
  8699. struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
  8700. struct ast_iax2_full_hdr *fh, *cur_fh;
  8701. if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
  8702. return;
  8703. pkt_buf->len = from_here->buf_len;
  8704. memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
  8705. fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
  8706. ast_mutex_lock(&to_here->lock);
  8707. AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
  8708. cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
  8709. if (fh->oseqno < cur_fh->oseqno) {
  8710. AST_LIST_INSERT_BEFORE_CURRENT(pkt_buf, entry);
  8711. break;
  8712. }
  8713. }
  8714. AST_LIST_TRAVERSE_SAFE_END
  8715. if (!cur_pkt_buf)
  8716. AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
  8717. to_here->iostate = IAX_IOSTATE_READY;
  8718. ast_cond_signal(&to_here->cond);
  8719. ast_mutex_unlock(&to_here->lock);
  8720. }
  8721. static int socket_read(int *id, int fd, short events, void *cbdata)
  8722. {
  8723. struct iax2_thread *thread;
  8724. socklen_t len;
  8725. time_t t;
  8726. static time_t last_errtime = 0;
  8727. struct ast_iax2_full_hdr *fh;
  8728. if (!(thread = find_idle_thread())) {
  8729. time(&t);
  8730. if (t != last_errtime) {
  8731. last_errtime = t;
  8732. ast_debug(1, "Out of idle IAX2 threads for I/O, pausing!\n");
  8733. }
  8734. usleep(1);
  8735. return 1;
  8736. }
  8737. len = sizeof(thread->iosin);
  8738. thread->iofd = fd;
  8739. thread->buf_len = recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, (struct sockaddr *) &thread->iosin, &len);
  8740. thread->buf_size = sizeof(thread->readbuf);
  8741. thread->buf = thread->readbuf;
  8742. if (thread->buf_len < 0) {
  8743. if (errno != ECONNREFUSED && errno != EAGAIN)
  8744. ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
  8745. handle_error();
  8746. thread->iostate = IAX_IOSTATE_IDLE;
  8747. signal_condition(&thread->lock, &thread->cond);
  8748. return 1;
  8749. }
  8750. if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) { /* simulate random loss condition */
  8751. thread->iostate = IAX_IOSTATE_IDLE;
  8752. signal_condition(&thread->lock, &thread->cond);
  8753. return 1;
  8754. }
  8755. /* Determine if this frame is a full frame; if so, and any thread is currently
  8756. processing a full frame for the same callno from this peer, then drop this
  8757. frame (and the peer will retransmit it) */
  8758. fh = (struct ast_iax2_full_hdr *) thread->buf;
  8759. if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
  8760. struct iax2_thread *cur = NULL;
  8761. uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
  8762. AST_LIST_LOCK(&active_list);
  8763. AST_LIST_TRAVERSE(&active_list, cur, list) {
  8764. if ((cur->ffinfo.callno == callno) &&
  8765. !inaddrcmp(&cur->ffinfo.sin, &thread->iosin))
  8766. break;
  8767. }
  8768. if (cur) {
  8769. /* we found another thread processing a full frame for this call,
  8770. so queue it up for processing later. */
  8771. defer_full_frame(thread, cur);
  8772. AST_LIST_UNLOCK(&active_list);
  8773. thread->iostate = IAX_IOSTATE_IDLE;
  8774. signal_condition(&thread->lock, &thread->cond);
  8775. return 1;
  8776. } else {
  8777. /* this thread is going to process this frame, so mark it */
  8778. thread->ffinfo.callno = callno;
  8779. memcpy(&thread->ffinfo.sin, &thread->iosin, sizeof(thread->ffinfo.sin));
  8780. thread->ffinfo.type = fh->type;
  8781. thread->ffinfo.csub = fh->csub;
  8782. AST_LIST_INSERT_HEAD(&active_list, thread, list);
  8783. }
  8784. AST_LIST_UNLOCK(&active_list);
  8785. }
  8786. /* Mark as ready and send on its way */
  8787. thread->iostate = IAX_IOSTATE_READY;
  8788. #ifdef DEBUG_SCHED_MULTITHREAD
  8789. ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
  8790. #endif
  8791. signal_condition(&thread->lock, &thread->cond);
  8792. return 1;
  8793. }
  8794. static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct sockaddr_in *sin, int sockfd,
  8795. struct iax_frame *fr)
  8796. {
  8797. unsigned char metatype;
  8798. struct ast_iax2_meta_trunk_mini *mtm;
  8799. struct ast_iax2_meta_trunk_hdr *mth;
  8800. struct ast_iax2_meta_trunk_entry *mte;
  8801. struct iax2_trunk_peer *tpeer;
  8802. unsigned int ts;
  8803. void *ptr;
  8804. struct timeval rxtrunktime;
  8805. struct ast_frame f = { 0, };
  8806. if (packet_len < sizeof(*meta)) {
  8807. ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a meta frame but is too short\n",
  8808. ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
  8809. return 1;
  8810. }
  8811. if (meta->metacmd != IAX_META_TRUNK)
  8812. return 1;
  8813. if (packet_len < (sizeof(*meta) + sizeof(*mth))) {
  8814. ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %d min)\n", packet_len,
  8815. (int) (sizeof(*meta) + sizeof(*mth)));
  8816. return 1;
  8817. }
  8818. mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
  8819. ts = ntohl(mth->ts);
  8820. metatype = meta->cmddata;
  8821. packet_len -= (sizeof(*meta) + sizeof(*mth));
  8822. ptr = mth->data;
  8823. tpeer = find_tpeer(sin, sockfd);
  8824. if (!tpeer) {
  8825. ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s:%d': No matching peer\n",
  8826. ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
  8827. return 1;
  8828. }
  8829. tpeer->trunkact = ast_tvnow();
  8830. if (!ts || ast_tvzero(tpeer->rxtrunktime))
  8831. tpeer->rxtrunktime = tpeer->trunkact;
  8832. rxtrunktime = tpeer->rxtrunktime;
  8833. ast_mutex_unlock(&tpeer->lock);
  8834. while (packet_len >= sizeof(*mte)) {
  8835. /* Process channels */
  8836. unsigned short callno, trunked_ts, len;
  8837. if (metatype == IAX_META_TRUNK_MINI) {
  8838. mtm = (struct ast_iax2_meta_trunk_mini *) ptr;
  8839. ptr += sizeof(*mtm);
  8840. packet_len -= sizeof(*mtm);
  8841. len = ntohs(mtm->len);
  8842. callno = ntohs(mtm->mini.callno);
  8843. trunked_ts = ntohs(mtm->mini.ts);
  8844. } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
  8845. mte = (struct ast_iax2_meta_trunk_entry *)ptr;
  8846. ptr += sizeof(*mte);
  8847. packet_len -= sizeof(*mte);
  8848. len = ntohs(mte->len);
  8849. callno = ntohs(mte->callno);
  8850. trunked_ts = 0;
  8851. } else {
  8852. ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
  8853. break;
  8854. }
  8855. /* Stop if we don't have enough data */
  8856. if (len > packet_len)
  8857. break;
  8858. fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, sin, NEW_PREVENT, sockfd, 0);
  8859. if (!fr->callno)
  8860. continue;
  8861. /* If it's a valid call, deliver the contents. If not, we
  8862. drop it, since we don't have a scallno to use for an INVAL */
  8863. /* Process as a mini frame */
  8864. memset(&f, 0, sizeof(f));
  8865. f.frametype = AST_FRAME_VOICE;
  8866. if (!iaxs[fr->callno]) {
  8867. /* drop it */
  8868. } else if (iaxs[fr->callno]->voiceformat == 0) {
  8869. ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n");
  8870. iax2_vnak(fr->callno);
  8871. } else {
  8872. ast_format_from_old_bitfield(&f.subclass.format, iaxs[fr->callno]->voiceformat);
  8873. f.datalen = len;
  8874. if (f.datalen >= 0) {
  8875. if (f.datalen)
  8876. f.data.ptr = ptr;
  8877. else
  8878. f.data.ptr = NULL;
  8879. if (trunked_ts)
  8880. fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
  8881. else
  8882. fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
  8883. /* Don't pass any packets until we're started */
  8884. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
  8885. struct iax_frame *duped_fr;
  8886. /* Common things */
  8887. f.src = "IAX2";
  8888. f.mallocd = 0;
  8889. f.offset = 0;
  8890. if (f.datalen && (f.frametype == AST_FRAME_VOICE))
  8891. f.samples = ast_codec_get_samples(&f);
  8892. else
  8893. f.samples = 0;
  8894. fr->outoforder = 0;
  8895. iax_frame_wrap(fr, &f);
  8896. duped_fr = iaxfrdup2(fr);
  8897. if (duped_fr)
  8898. schedule_delivery(duped_fr, 1, 1, &fr->ts);
  8899. if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts)
  8900. iaxs[fr->callno]->last = fr->ts;
  8901. }
  8902. } else {
  8903. ast_log(LOG_WARNING, "Datalen < 0?\n");
  8904. }
  8905. }
  8906. ast_mutex_unlock(&iaxsl[fr->callno]);
  8907. ptr += len;
  8908. packet_len -= len;
  8909. }
  8910. return 1;
  8911. }
  8912. static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  8913. {
  8914. struct ast_datastore *variablestore;
  8915. AST_LIST_HEAD(, ast_var_t) *varlist;
  8916. struct ast_var_t *var;
  8917. if (!chan) {
  8918. ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
  8919. return -1;
  8920. }
  8921. variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
  8922. if (!variablestore) {
  8923. *buf = '\0';
  8924. return 0;
  8925. }
  8926. varlist = variablestore->data;
  8927. AST_LIST_LOCK(varlist);
  8928. AST_LIST_TRAVERSE(varlist, var, entries) {
  8929. if (strcmp(var->name, data) == 0) {
  8930. ast_copy_string(buf, var->value, len);
  8931. break;
  8932. }
  8933. }
  8934. AST_LIST_UNLOCK(varlist);
  8935. return 0;
  8936. }
  8937. static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
  8938. {
  8939. struct ast_datastore *variablestore;
  8940. AST_LIST_HEAD(, ast_var_t) *varlist;
  8941. struct ast_var_t *var;
  8942. if (!chan) {
  8943. ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
  8944. return -1;
  8945. }
  8946. variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
  8947. if (!variablestore) {
  8948. variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
  8949. if (!variablestore) {
  8950. ast_log(LOG_ERROR, "Memory allocation error\n");
  8951. return -1;
  8952. }
  8953. varlist = ast_calloc(1, sizeof(*varlist));
  8954. if (!varlist) {
  8955. ast_datastore_free(variablestore);
  8956. ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
  8957. return -1;
  8958. }
  8959. AST_LIST_HEAD_INIT(varlist);
  8960. variablestore->data = varlist;
  8961. variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
  8962. ast_channel_datastore_add(chan, variablestore);
  8963. } else
  8964. varlist = variablestore->data;
  8965. AST_LIST_LOCK(varlist);
  8966. AST_LIST_TRAVERSE_SAFE_BEGIN(varlist, var, entries) {
  8967. if (strcmp(var->name, data) == 0) {
  8968. AST_LIST_REMOVE_CURRENT(entries);
  8969. ast_var_delete(var);
  8970. break;
  8971. }
  8972. }
  8973. AST_LIST_TRAVERSE_SAFE_END;
  8974. var = ast_var_assign(data, value);
  8975. if (var)
  8976. AST_LIST_INSERT_TAIL(varlist, var, entries);
  8977. else
  8978. ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
  8979. AST_LIST_UNLOCK(varlist);
  8980. return 0;
  8981. }
  8982. static struct ast_custom_function iaxvar_function = {
  8983. .name = "IAXVAR",
  8984. .read = acf_iaxvar_read,
  8985. .write = acf_iaxvar_write,
  8986. };
  8987. static void set_hangup_source_and_cause(int callno, unsigned char causecode)
  8988. {
  8989. iax2_lock_owner(callno);
  8990. if (iaxs[callno] && iaxs[callno]->owner) {
  8991. struct ast_channel *owner;
  8992. const char *name;
  8993. owner = iaxs[callno]->owner;
  8994. if (causecode) {
  8995. ast_channel_hangupcause_set(owner, causecode);
  8996. }
  8997. name = ast_strdupa(ast_channel_name(owner));
  8998. ast_channel_ref(owner);
  8999. ast_channel_unlock(owner);
  9000. ast_mutex_unlock(&iaxsl[callno]);
  9001. ast_set_hangupsource(owner, name, 0);
  9002. ast_channel_unref(owner);
  9003. ast_mutex_lock(&iaxsl[callno]);
  9004. }
  9005. }
  9006. static int socket_process_helper(struct iax2_thread *thread)
  9007. {
  9008. struct sockaddr_in sin;
  9009. int res;
  9010. int updatehistory=1;
  9011. int new = NEW_PREVENT;
  9012. int dcallno = 0;
  9013. char decrypted = 0;
  9014. struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
  9015. struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
  9016. struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
  9017. struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
  9018. struct iax_frame *fr;
  9019. struct iax_frame *cur;
  9020. struct ast_frame f = { 0, };
  9021. struct ast_channel *c = NULL;
  9022. struct iax2_dpcache *dp;
  9023. struct iax2_peer *peer;
  9024. struct iax_ies ies;
  9025. struct iax_ie_data ied0, ied1;
  9026. iax2_format format;
  9027. int fd;
  9028. int exists;
  9029. int minivid = 0;
  9030. char empty[32]=""; /* Safety measure */
  9031. struct iax_frame *duped_fr;
  9032. char host_pref_buf[128];
  9033. char caller_pref_buf[128];
  9034. struct ast_codec_pref pref;
  9035. char *using_prefs = "mine";
  9036. /* allocate an iax_frame with 4096 bytes of data buffer */
  9037. fr = ast_alloca(sizeof(*fr) + 4096);
  9038. memset(fr, 0, sizeof(*fr));
  9039. fr->afdatalen = 4096; /* From ast_alloca() above */
  9040. /* Copy frequently used parameters to the stack */
  9041. res = thread->buf_len;
  9042. fd = thread->iofd;
  9043. memcpy(&sin, &thread->iosin, sizeof(sin));
  9044. if (res < sizeof(*mh)) {
  9045. ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int) sizeof(*mh));
  9046. return 1;
  9047. }
  9048. if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
  9049. if (res < sizeof(*vh)) {
  9050. ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a video frame but is too short\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
  9051. return 1;
  9052. }
  9053. /* This is a video frame, get call number */
  9054. fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, fd, 0);
  9055. minivid = 1;
  9056. } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000))
  9057. return socket_process_meta(res, meta, &sin, fd, fr);
  9058. #ifdef DEBUG_SUPPORT
  9059. if (res >= sizeof(*fh))
  9060. iax_outputframe(NULL, fh, 1, &sin, res - sizeof(*fh));
  9061. #endif
  9062. if (ntohs(mh->callno) & IAX_FLAG_FULL) {
  9063. if (res < sizeof(*fh)) {
  9064. ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a full frame but is too short\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
  9065. return 1;
  9066. }
  9067. /* Get the destination call number */
  9068. dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
  9069. /* check to make sure this full frame isn't encrypted before we attempt
  9070. * to look inside of it. If it is encrypted, decrypt it first. Its ok if the
  9071. * callno is not found here, that just means one hasn't been allocated for
  9072. * this connection yet. */
  9073. if ((dcallno != 1) && (fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, NEW_PREVENT, fd, 1))) {
  9074. ast_mutex_lock(&iaxsl[fr->callno]);
  9075. if (iaxs[fr->callno] && ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED)) {
  9076. if (decrypt_frame(fr->callno, fh, &f, &res)) {
  9077. ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
  9078. ast_mutex_unlock(&iaxsl[fr->callno]);
  9079. return 1;
  9080. }
  9081. decrypted = 1;
  9082. }
  9083. ast_mutex_unlock(&iaxsl[fr->callno]);
  9084. }
  9085. /* Retrieve the type and subclass */
  9086. f.frametype = fh->type;
  9087. if (f.frametype == AST_FRAME_VIDEO) {
  9088. ast_format_from_old_bitfield(&f.subclass.format, (uncompress_subclass(fh->csub & ~0x40)));
  9089. if ((fh->csub >> 6) & 0x1) {
  9090. ast_format_set_video_mark(&f.subclass.format);
  9091. }
  9092. } else if (f.frametype == AST_FRAME_VOICE) {
  9093. ast_format_from_old_bitfield(&f.subclass.format, uncompress_subclass(fh->csub));
  9094. } else {
  9095. f.subclass.integer = uncompress_subclass(fh->csub);
  9096. }
  9097. /* Deal with POKE/PONG without allocating a callno */
  9098. if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_POKE) {
  9099. /* Reply back with a PONG, but don't care about the result. */
  9100. send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_PONG, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
  9101. return 1;
  9102. } else if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_ACK && dcallno == 1) {
  9103. /* Ignore */
  9104. return 1;
  9105. }
  9106. f.datalen = res - sizeof(*fh);
  9107. if (f.datalen) {
  9108. if (f.frametype == AST_FRAME_IAX) {
  9109. if (iax_parse_ies(&ies, thread->buf + sizeof(struct ast_iax2_full_hdr), f.datalen)) {
  9110. ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin.sin_addr));
  9111. ast_variables_destroy(ies.vars);
  9112. return 1;
  9113. }
  9114. f.data.ptr = NULL;
  9115. f.datalen = 0;
  9116. } else {
  9117. f.data.ptr = thread->buf + sizeof(struct ast_iax2_full_hdr);
  9118. memset(&ies, 0, sizeof(ies));
  9119. }
  9120. } else {
  9121. if (f.frametype == AST_FRAME_IAX)
  9122. f.data.ptr = NULL;
  9123. else
  9124. f.data.ptr = empty;
  9125. memset(&ies, 0, sizeof(ies));
  9126. }
  9127. if (!dcallno && iax2_allow_new(f.frametype, f.subclass.integer, 1)) {
  9128. /* only set NEW_ALLOW if calltoken checks out */
  9129. if (handle_call_token(fh, &ies, &sin, fd)) {
  9130. ast_variables_destroy(ies.vars);
  9131. return 1;
  9132. }
  9133. if (ies.calltoken && ies.calltokendata) {
  9134. /* if we've gotten this far, and the calltoken ie data exists,
  9135. * then calltoken validation _MUST_ have taken place. If calltoken
  9136. * data is provided, it is always validated reguardless of any
  9137. * calltokenoptional or requirecalltoken options */
  9138. new = NEW_ALLOW_CALLTOKEN_VALIDATED;
  9139. } else {
  9140. new = NEW_ALLOW;
  9141. }
  9142. }
  9143. } else {
  9144. /* Don't know anything about it yet */
  9145. f.frametype = AST_FRAME_NULL;
  9146. f.subclass.integer = 0;
  9147. memset(&ies, 0, sizeof(ies));
  9148. }
  9149. if (!fr->callno) {
  9150. int check_dcallno = 0;
  9151. /*
  9152. * We enforce accurate destination call numbers for ACKs. This forces the other
  9153. * end to know the destination call number before call setup can complete.
  9154. *
  9155. * Discussed in the following thread:
  9156. * http://lists.digium.com/pipermail/asterisk-dev/2008-May/033217.html
  9157. */
  9158. if ((ntohs(mh->callno) & IAX_FLAG_FULL) && ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer == IAX_COMMAND_ACK))) {
  9159. check_dcallno = 1;
  9160. }
  9161. if (!(fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, new, fd, check_dcallno))) {
  9162. if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_NEW) {
  9163. send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
  9164. } else if (f.frametype == AST_FRAME_IAX && (f.subclass.integer == IAX_COMMAND_REGREQ || f.subclass.integer == IAX_COMMAND_REGREL)) {
  9165. send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
  9166. }
  9167. ast_variables_destroy(ies.vars);
  9168. return 1;
  9169. }
  9170. }
  9171. if (fr->callno > 0) {
  9172. struct ast_callid *mount_callid;
  9173. ast_mutex_lock(&iaxsl[fr->callno]);
  9174. if (iaxs[fr->callno] && ((mount_callid = iax_pvt_callid_get(fr->callno)))) {
  9175. /* Bind to thread */
  9176. ast_callid_threadassoc_add(mount_callid);
  9177. ast_callid_unref(mount_callid);
  9178. }
  9179. }
  9180. if (!fr->callno || !iaxs[fr->callno]) {
  9181. /* A call arrived for a nonexistent destination. Unless it's an "inval"
  9182. frame, reply with an inval */
  9183. if (ntohs(mh->callno) & IAX_FLAG_FULL) {
  9184. /* We can only raw hangup control frames */
  9185. if (((f.subclass.integer != IAX_COMMAND_INVAL) &&
  9186. (f.subclass.integer != IAX_COMMAND_TXCNT) &&
  9187. (f.subclass.integer != IAX_COMMAND_TXACC) &&
  9188. (f.subclass.integer != IAX_COMMAND_FWDOWNL))||
  9189. (f.frametype != AST_FRAME_IAX))
  9190. raw_hangup(&sin, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
  9191. fd);
  9192. }
  9193. if (fr->callno > 0)
  9194. ast_mutex_unlock(&iaxsl[fr->callno]);
  9195. ast_variables_destroy(ies.vars);
  9196. return 1;
  9197. }
  9198. if (ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED) && !decrypted) {
  9199. if (decrypt_frame(fr->callno, fh, &f, &res)) {
  9200. ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
  9201. ast_variables_destroy(ies.vars);
  9202. ast_mutex_unlock(&iaxsl[fr->callno]);
  9203. return 1;
  9204. }
  9205. decrypted = 1;
  9206. }
  9207. #ifdef DEBUG_SUPPORT
  9208. if (decrypted) {
  9209. iax_outputframe(NULL, fh, 3, &sin, res - sizeof(*fh));
  9210. }
  9211. #endif
  9212. if (iaxs[fr->callno]->owner && fh->type == AST_FRAME_IAX &&
  9213. (fh->csub == IAX_COMMAND_HANGUP
  9214. || fh->csub == IAX_COMMAND_REJECT
  9215. || fh->csub == IAX_COMMAND_REGREJ
  9216. || fh->csub == IAX_COMMAND_TXREJ)) {
  9217. struct ast_control_pvt_cause_code *cause_code;
  9218. int data_size = sizeof(*cause_code);
  9219. char subclass[40] = "";
  9220. /* get subclass text */
  9221. iax_frame_subclass2str(fh->csub, subclass, sizeof(subclass));
  9222. /* add length of "IAX2 " */
  9223. data_size += 5;
  9224. /* for IAX hangup frames, add length of () and number */
  9225. data_size += 3;
  9226. if (ies.causecode > 9) {
  9227. data_size++;
  9228. }
  9229. if (ies.causecode > 99) {
  9230. data_size++;
  9231. }
  9232. /* add length of subclass */
  9233. data_size += strlen(subclass);
  9234. cause_code = ast_alloca(data_size);
  9235. memset(cause_code, 0, data_size);
  9236. ast_copy_string(cause_code->chan_name, ast_channel_name(iaxs[fr->callno]->owner), AST_CHANNEL_NAME);
  9237. cause_code->ast_cause = ies.causecode;
  9238. snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "IAX2 %s(%d)", subclass, ies.causecode);
  9239. iax2_lock_owner(fr->callno);
  9240. if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
  9241. ast_queue_control_data(iaxs[fr->callno]->owner, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
  9242. ast_channel_hangupcause_hash_set(iaxs[fr->callno]->owner, cause_code, data_size);
  9243. ast_channel_unlock(iaxs[fr->callno]->owner);
  9244. }
  9245. if (!iaxs[fr->callno]) {
  9246. ast_variables_destroy(ies.vars);
  9247. ast_mutex_unlock(&iaxsl[fr->callno]);
  9248. return 1;
  9249. }
  9250. }
  9251. /* count this frame */
  9252. iaxs[fr->callno]->frames_received++;
  9253. if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && !minivid &&
  9254. f.subclass.integer != IAX_COMMAND_TXCNT && /* for attended transfer */
  9255. f.subclass.integer != IAX_COMMAND_TXACC) { /* for attended transfer */
  9256. unsigned short new_peercallno;
  9257. new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
  9258. if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
  9259. if (iaxs[fr->callno]->peercallno) {
  9260. remove_by_peercallno(iaxs[fr->callno]);
  9261. }
  9262. iaxs[fr->callno]->peercallno = new_peercallno;
  9263. store_by_peercallno(iaxs[fr->callno]);
  9264. }
  9265. }
  9266. if (ntohs(mh->callno) & IAX_FLAG_FULL) {
  9267. if (iaxdebug)
  9268. ast_debug(1, "Received packet %d, (%u, %d)\n", fh->oseqno, f.frametype, f.subclass.integer);
  9269. /* Check if it's out of order (and not an ACK or INVAL) */
  9270. fr->oseqno = fh->oseqno;
  9271. fr->iseqno = fh->iseqno;
  9272. fr->ts = ntohl(fh->ts);
  9273. #ifdef IAXTESTS
  9274. if (test_resync) {
  9275. ast_debug(1, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
  9276. fr->ts += test_resync;
  9277. }
  9278. #endif /* IAXTESTS */
  9279. #if 0
  9280. if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
  9281. ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
  9282. (f.subclass == IAX_COMMAND_NEW ||
  9283. f.subclass == IAX_COMMAND_AUTHREQ ||
  9284. f.subclass == IAX_COMMAND_ACCEPT ||
  9285. f.subclass == IAX_COMMAND_REJECT)) ) )
  9286. #endif
  9287. if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
  9288. updatehistory = 0;
  9289. if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
  9290. (iaxs[fr->callno]->iseqno ||
  9291. ((f.subclass.integer != IAX_COMMAND_TXCNT) &&
  9292. (f.subclass.integer != IAX_COMMAND_TXREADY) && /* for attended transfer */
  9293. (f.subclass.integer != IAX_COMMAND_TXREL) && /* for attended transfer */
  9294. (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
  9295. (f.subclass.integer != IAX_COMMAND_TXACC)) ||
  9296. (f.frametype != AST_FRAME_IAX))) {
  9297. if (
  9298. ((f.subclass.integer != IAX_COMMAND_ACK) &&
  9299. (f.subclass.integer != IAX_COMMAND_INVAL) &&
  9300. (f.subclass.integer != IAX_COMMAND_TXCNT) &&
  9301. (f.subclass.integer != IAX_COMMAND_TXREADY) && /* for attended transfer */
  9302. (f.subclass.integer != IAX_COMMAND_TXREL) && /* for attended transfer */
  9303. (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
  9304. (f.subclass.integer != IAX_COMMAND_TXACC) &&
  9305. (f.subclass.integer != IAX_COMMAND_VNAK)) ||
  9306. (f.frametype != AST_FRAME_IAX)) {
  9307. /* If it's not an ACK packet, it's out of order. */
  9308. ast_debug(1, "Packet arrived out of order (expecting %d, got %d) (frametype = %u, subclass = %d)\n",
  9309. iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass.integer);
  9310. /* Check to see if we need to request retransmission,
  9311. * and take sequence number wraparound into account */
  9312. if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
  9313. /* If we've already seen it, ack it XXX There's a border condition here XXX */
  9314. if ((f.frametype != AST_FRAME_IAX) ||
  9315. ((f.subclass.integer != IAX_COMMAND_ACK) && (f.subclass.integer != IAX_COMMAND_INVAL))) {
  9316. ast_debug(1, "Acking anyway\n");
  9317. /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
  9318. we have anything to send, we'll retransmit and get an ACK back anyway XXX */
  9319. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  9320. }
  9321. } else {
  9322. /* Send a VNAK requesting retransmission */
  9323. iax2_vnak(fr->callno);
  9324. }
  9325. ast_variables_destroy(ies.vars);
  9326. ast_mutex_unlock(&iaxsl[fr->callno]);
  9327. return 1;
  9328. }
  9329. } else {
  9330. /* Increment unless it's an ACK or VNAK */
  9331. if (((f.subclass.integer != IAX_COMMAND_ACK) &&
  9332. (f.subclass.integer != IAX_COMMAND_INVAL) &&
  9333. (f.subclass.integer != IAX_COMMAND_TXCNT) &&
  9334. (f.subclass.integer != IAX_COMMAND_TXACC) &&
  9335. (f.subclass.integer != IAX_COMMAND_VNAK)) ||
  9336. (f.frametype != AST_FRAME_IAX))
  9337. iaxs[fr->callno]->iseqno++;
  9338. }
  9339. /* Ensure text frames are NULL-terminated */
  9340. if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
  9341. if (res < thread->buf_size)
  9342. thread->buf[res++] = '\0';
  9343. else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
  9344. thread->buf[res - 1] = '\0';
  9345. }
  9346. /* Handle implicit ACKing unless this is an INVAL, and only if this is
  9347. from the real peer, not the transfer peer */
  9348. if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
  9349. ((f.subclass.integer != IAX_COMMAND_INVAL) ||
  9350. (f.frametype != AST_FRAME_IAX))) {
  9351. unsigned char x;
  9352. int call_to_destroy;
  9353. /* First we have to qualify that the ACKed value is within our window */
  9354. if (iaxs[fr->callno]->rseqno >= iaxs[fr->callno]->oseqno || (fr->iseqno >= iaxs[fr->callno]->rseqno && fr->iseqno < iaxs[fr->callno]->oseqno))
  9355. x = fr->iseqno;
  9356. else
  9357. x = iaxs[fr->callno]->oseqno;
  9358. if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
  9359. /* The acknowledgement is within our window. Time to acknowledge everything
  9360. that it says to */
  9361. for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
  9362. /* Ack the packet with the given timestamp */
  9363. if (iaxdebug)
  9364. ast_debug(1, "Cancelling transmission of packet %d\n", x);
  9365. call_to_destroy = 0;
  9366. AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
  9367. /* If it's our call, and our timestamp, mark -1 retries */
  9368. if (x == cur->oseqno) {
  9369. cur->retries = -1;
  9370. /* Destroy call if this is the end */
  9371. if (cur->final)
  9372. call_to_destroy = fr->callno;
  9373. }
  9374. }
  9375. if (call_to_destroy) {
  9376. if (iaxdebug)
  9377. ast_debug(1, "Really destroying %d, having been acked on final message\n", call_to_destroy);
  9378. ast_mutex_lock(&iaxsl[call_to_destroy]);
  9379. iax2_destroy(call_to_destroy);
  9380. ast_mutex_unlock(&iaxsl[call_to_destroy]);
  9381. }
  9382. }
  9383. /* Note how much we've received acknowledgement for */
  9384. if (iaxs[fr->callno])
  9385. iaxs[fr->callno]->rseqno = fr->iseqno;
  9386. else {
  9387. /* Stop processing now */
  9388. ast_variables_destroy(ies.vars);
  9389. ast_mutex_unlock(&iaxsl[fr->callno]);
  9390. return 1;
  9391. }
  9392. } else {
  9393. ast_debug(1, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
  9394. }
  9395. }
  9396. if (inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
  9397. ((f.frametype != AST_FRAME_IAX) ||
  9398. ((f.subclass.integer != IAX_COMMAND_TXACC) &&
  9399. (f.subclass.integer != IAX_COMMAND_TXCNT)))) {
  9400. /* Only messages we accept from a transfer host are TXACC and TXCNT */
  9401. ast_variables_destroy(ies.vars);
  9402. ast_mutex_unlock(&iaxsl[fr->callno]);
  9403. return 1;
  9404. }
  9405. /* when we receive the first full frame for a new incoming channel,
  9406. it is safe to start the PBX on the channel because we have now
  9407. completed a 3-way handshake with the peer */
  9408. if ((f.frametype == AST_FRAME_VOICE) ||
  9409. (f.frametype == AST_FRAME_VIDEO) ||
  9410. (f.frametype == AST_FRAME_IAX)) {
  9411. if (ast_test_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
  9412. ast_clear_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART);
  9413. if (!ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->chosenformat, NULL,
  9414. ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED))) {
  9415. ast_variables_destroy(ies.vars);
  9416. ast_mutex_unlock(&iaxsl[fr->callno]);
  9417. return 1;
  9418. }
  9419. }
  9420. if (ies.vars) {
  9421. struct ast_datastore *variablestore = NULL;
  9422. struct ast_variable *var, *prev = NULL;
  9423. AST_LIST_HEAD(, ast_var_t) *varlist;
  9424. iax2_lock_owner(fr->callno);
  9425. if (!iaxs[fr->callno]) {
  9426. ast_variables_destroy(ies.vars);
  9427. ast_mutex_unlock(&iaxsl[fr->callno]);
  9428. return 1;
  9429. }
  9430. if ((c = iaxs[fr->callno]->owner)) {
  9431. varlist = ast_calloc(1, sizeof(*varlist));
  9432. variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
  9433. if (variablestore && varlist) {
  9434. variablestore->data = varlist;
  9435. variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
  9436. AST_LIST_HEAD_INIT(varlist);
  9437. ast_debug(1, "I can haz IAX vars?\n");
  9438. for (var = ies.vars; var; var = var->next) {
  9439. struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
  9440. if (prev) {
  9441. ast_free(prev);
  9442. }
  9443. prev = var;
  9444. if (!newvar) {
  9445. /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
  9446. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  9447. } else {
  9448. AST_LIST_INSERT_TAIL(varlist, newvar, entries);
  9449. }
  9450. }
  9451. if (prev) {
  9452. ast_free(prev);
  9453. }
  9454. ies.vars = NULL;
  9455. ast_channel_datastore_add(c, variablestore);
  9456. } else {
  9457. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  9458. if (variablestore) {
  9459. ast_datastore_free(variablestore);
  9460. }
  9461. if (varlist) {
  9462. ast_free(varlist);
  9463. }
  9464. }
  9465. ast_channel_unlock(c);
  9466. } else {
  9467. /* No channel yet, so transfer the variables directly over to the pvt,
  9468. * for later inheritance. */
  9469. ast_debug(1, "No channel, so populating IAXVARs to the pvt, as an intermediate step.\n");
  9470. for (var = ies.vars; var && var->next; var = var->next);
  9471. if (var) {
  9472. var->next = iaxs[fr->callno]->iaxvars;
  9473. iaxs[fr->callno]->iaxvars = ies.vars;
  9474. ies.vars = NULL;
  9475. }
  9476. }
  9477. }
  9478. if (ies.vars) {
  9479. ast_debug(1, "I have IAX variables, but they were not processed\n");
  9480. }
  9481. }
  9482. /* once we receive our first IAX Full Frame that is not CallToken related, send all
  9483. * queued signaling frames that were being held. */
  9484. if ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer != IAX_COMMAND_CALLTOKEN) && iaxs[fr->callno]->hold_signaling) {
  9485. send_signaling(iaxs[fr->callno]);
  9486. }
  9487. if (f.frametype == AST_FRAME_VOICE) {
  9488. if (ast_format_to_old_bitfield(&f.subclass.format) != iaxs[fr->callno]->voiceformat) {
  9489. iaxs[fr->callno]->voiceformat = ast_format_to_old_bitfield(&f.subclass.format);
  9490. ast_debug(1, "Ooh, voice format changed to '%s'\n", ast_getformatname(&f.subclass.format));
  9491. if (iaxs[fr->callno]->owner) {
  9492. iax2_lock_owner(fr->callno);
  9493. if (iaxs[fr->callno]) {
  9494. if (iaxs[fr->callno]->owner) {
  9495. struct ast_format_cap *orignative = ast_format_cap_dup(ast_channel_nativeformats(iaxs[fr->callno]->owner));
  9496. struct ast_format_cap *native = ast_channel_nativeformats(iaxs[fr->callno]->owner);
  9497. if (orignative) {
  9498. ast_format_cap_set(native, &f.subclass.format);
  9499. if (ast_channel_readformat(iaxs[fr->callno]->owner)->id) {
  9500. ast_set_read_format(iaxs[fr->callno]->owner, ast_channel_readformat(iaxs[fr->callno]->owner));
  9501. }
  9502. ast_format_cap_copy(native, orignative);
  9503. orignative = ast_format_cap_destroy(orignative);
  9504. }
  9505. ast_channel_unlock(iaxs[fr->callno]->owner);
  9506. }
  9507. } else {
  9508. ast_debug(1, "Neat, somebody took away the channel at a magical time but i found it!\n");
  9509. /* Free remote variables (if any) */
  9510. if (ies.vars) {
  9511. ast_variables_destroy(ies.vars);
  9512. ast_debug(1, "I can haz iaxvars, but they is no good. :-(\n");
  9513. ies.vars = NULL;
  9514. }
  9515. ast_mutex_unlock(&iaxsl[fr->callno]);
  9516. return 1;
  9517. }
  9518. }
  9519. }
  9520. }
  9521. if (f.frametype == AST_FRAME_VIDEO) {
  9522. if (f.subclass.format.id != ast_format_id_from_old_bitfield(iaxs[fr->callno]->videoformat)) {
  9523. ast_debug(1, "Ooh, video format changed to %s\n", ast_getformatname(&f.subclass.format));
  9524. iaxs[fr->callno]->videoformat = ast_format_to_old_bitfield(&f.subclass.format);
  9525. }
  9526. }
  9527. if (f.frametype == AST_FRAME_IAX) {
  9528. AST_SCHED_DEL(sched, iaxs[fr->callno]->initid);
  9529. /* Handle the IAX pseudo frame itself */
  9530. if (iaxdebug)
  9531. ast_debug(1, "IAX subclass %d received\n", f.subclass.integer);
  9532. /* Update last ts unless the frame's timestamp originated with us. */
  9533. if (iaxs[fr->callno]->last < fr->ts &&
  9534. f.subclass.integer != IAX_COMMAND_ACK &&
  9535. f.subclass.integer != IAX_COMMAND_PONG &&
  9536. f.subclass.integer != IAX_COMMAND_LAGRP) {
  9537. iaxs[fr->callno]->last = fr->ts;
  9538. if (iaxdebug)
  9539. ast_debug(1, "For call=%d, set last=%u\n", fr->callno, fr->ts);
  9540. }
  9541. iaxs[fr->callno]->last_iax_message = f.subclass.integer;
  9542. if (!iaxs[fr->callno]->first_iax_message) {
  9543. iaxs[fr->callno]->first_iax_message = f.subclass.integer;
  9544. }
  9545. switch(f.subclass.integer) {
  9546. case IAX_COMMAND_ACK:
  9547. /* Do nothing */
  9548. break;
  9549. case IAX_COMMAND_QUELCH:
  9550. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
  9551. /* Generate Manager Hold event, if necessary*/
  9552. if (iaxs[fr->callno]->owner) {
  9553. ast_manager_event(iaxs[fr->callno]->owner, EVENT_FLAG_CALL, "Hold",
  9554. "Status: On\r\n"
  9555. "Channel: %s\r\n"
  9556. "Uniqueid: %s\r\n",
  9557. ast_channel_name(iaxs[fr->callno]->owner),
  9558. ast_channel_uniqueid(iaxs[fr->callno]->owner));
  9559. }
  9560. ast_set_flag64(iaxs[fr->callno], IAX_QUELCH);
  9561. if (ies.musiconhold) {
  9562. iax2_lock_owner(fr->callno);
  9563. if (!iaxs[fr->callno] || !iaxs[fr->callno]->owner) {
  9564. break;
  9565. }
  9566. if (ast_bridged_channel(iaxs[fr->callno]->owner)) {
  9567. const char *moh_suggest = iaxs[fr->callno]->mohsuggest;
  9568. /*
  9569. * We already hold the owner lock so we do not
  9570. * need to check iaxs[fr->callno] after it returns.
  9571. */
  9572. iax2_queue_control_data(fr->callno, AST_CONTROL_HOLD,
  9573. S_OR(moh_suggest, NULL),
  9574. !ast_strlen_zero(moh_suggest) ? strlen(moh_suggest) + 1 : 0);
  9575. }
  9576. ast_channel_unlock(iaxs[fr->callno]->owner);
  9577. }
  9578. }
  9579. break;
  9580. case IAX_COMMAND_UNQUELCH:
  9581. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
  9582. iax2_lock_owner(fr->callno);
  9583. if (!iaxs[fr->callno]) {
  9584. break;
  9585. }
  9586. /* Generate Manager Unhold event, if necessary */
  9587. if (iaxs[fr->callno]->owner && ast_test_flag64(iaxs[fr->callno], IAX_QUELCH)) {
  9588. ast_manager_event(iaxs[fr->callno]->owner, EVENT_FLAG_CALL, "Hold",
  9589. "Status: Off\r\n"
  9590. "Channel: %s\r\n"
  9591. "Uniqueid: %s\r\n",
  9592. ast_channel_name(iaxs[fr->callno]->owner),
  9593. ast_channel_uniqueid(iaxs[fr->callno]->owner));
  9594. }
  9595. ast_clear_flag64(iaxs[fr->callno], IAX_QUELCH);
  9596. if (!iaxs[fr->callno]->owner) {
  9597. break;
  9598. }
  9599. if (ast_bridged_channel(iaxs[fr->callno]->owner)) {
  9600. /*
  9601. * We already hold the owner lock so we do not
  9602. * need to check iaxs[fr->callno] after it returns.
  9603. */
  9604. iax2_queue_control_data(fr->callno, AST_CONTROL_UNHOLD, NULL, 0);
  9605. }
  9606. ast_channel_unlock(iaxs[fr->callno]->owner);
  9607. }
  9608. break;
  9609. case IAX_COMMAND_TXACC:
  9610. if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
  9611. /* Ack the packet with the given timestamp */
  9612. AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
  9613. /* Cancel any outstanding txcnt's */
  9614. if (cur->transfer) {
  9615. cur->retries = -1;
  9616. }
  9617. }
  9618. memset(&ied1, 0, sizeof(ied1));
  9619. iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
  9620. send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
  9621. iaxs[fr->callno]->transferring = TRANSFER_READY;
  9622. }
  9623. break;
  9624. case IAX_COMMAND_NEW:
  9625. /* Ignore if it's already up */
  9626. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD))
  9627. break;
  9628. if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
  9629. ast_mutex_unlock(&iaxsl[fr->callno]);
  9630. check_provisioning(&sin, fd, ies.serviceident, ies.provver);
  9631. ast_mutex_lock(&iaxsl[fr->callno]);
  9632. if (!iaxs[fr->callno]) {
  9633. break;
  9634. }
  9635. }
  9636. /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
  9637. if (ast_test_flag64(iaxs[fr->callno], IAX_TRUNK)) {
  9638. int new_callno;
  9639. if ((new_callno = make_trunk(fr->callno, 1)) != -1)
  9640. fr->callno = new_callno;
  9641. }
  9642. /* For security, always ack immediately */
  9643. if (delayreject)
  9644. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  9645. if (check_access(fr->callno, &sin, &ies)) {
  9646. /* They're not allowed on */
  9647. auth_fail(fr->callno, IAX_COMMAND_REJECT);
  9648. if (authdebug)
  9649. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, who was trying to reach '%s@%s'\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
  9650. break;
  9651. }
  9652. if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_test_flag64(iaxs[fr->callno], IAX_FORCE_ENCRYPT)) {
  9653. auth_fail(fr->callno, IAX_COMMAND_REJECT);
  9654. ast_log(LOG_WARNING, "Rejected connect attempt. No secret present while force encrypt enabled.\n");
  9655. break;
  9656. }
  9657. if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
  9658. const char *context, *exten, *cid_num;
  9659. context = ast_strdupa(iaxs[fr->callno]->context);
  9660. exten = ast_strdupa(iaxs[fr->callno]->exten);
  9661. cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
  9662. /* This might re-enter the IAX code and need the lock */
  9663. ast_mutex_unlock(&iaxsl[fr->callno]);
  9664. exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
  9665. ast_mutex_lock(&iaxsl[fr->callno]);
  9666. if (!iaxs[fr->callno]) {
  9667. break;
  9668. }
  9669. } else
  9670. exists = 0;
  9671. /* Get OSP token if it does exist */
  9672. save_osptoken(fr, &ies);
  9673. if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
  9674. if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
  9675. memset(&ied0, 0, sizeof(ied0));
  9676. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
  9677. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
  9678. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  9679. if (!iaxs[fr->callno]) {
  9680. break;
  9681. }
  9682. if (authdebug)
  9683. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
  9684. } else {
  9685. /* Select an appropriate format */
  9686. if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
  9687. if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
  9688. using_prefs = "reqonly";
  9689. } else {
  9690. using_prefs = "disabled";
  9691. }
  9692. format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
  9693. memset(&pref, 0, sizeof(pref));
  9694. strcpy(caller_pref_buf, "disabled");
  9695. strcpy(host_pref_buf, "disabled");
  9696. } else {
  9697. struct ast_format tmpfmt;
  9698. using_prefs = "mine";
  9699. /* If the information elements are in here... use them */
  9700. if (ies.codec_prefs)
  9701. ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
  9702. if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
  9703. /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
  9704. if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
  9705. pref = iaxs[fr->callno]->rprefs;
  9706. using_prefs = "caller";
  9707. } else {
  9708. pref = iaxs[fr->callno]->prefs;
  9709. }
  9710. } else
  9711. pref = iaxs[fr->callno]->prefs;
  9712. format = iax2_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
  9713. ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
  9714. ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
  9715. }
  9716. if (!format) {
  9717. if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP))
  9718. format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
  9719. if (!format) {
  9720. memset(&ied0, 0, sizeof(ied0));
  9721. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
  9722. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  9723. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  9724. if (!iaxs[fr->callno]) {
  9725. break;
  9726. }
  9727. if (authdebug) {
  9728. char tmp[256], tmp2[256], tmp3[256];
  9729. if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
  9730. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
  9731. ast_inet_ntoa(sin.sin_addr),
  9732. iax2_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
  9733. iax2_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
  9734. } else {
  9735. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
  9736. ast_inet_ntoa(sin.sin_addr),
  9737. iax2_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
  9738. iax2_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
  9739. iax2_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
  9740. }
  9741. }
  9742. } else {
  9743. /* Pick one... */
  9744. if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
  9745. if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
  9746. format = 0;
  9747. } else {
  9748. if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
  9749. using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
  9750. memset(&pref, 0, sizeof(pref));
  9751. format = iax2_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
  9752. strcpy(caller_pref_buf,"disabled");
  9753. strcpy(host_pref_buf,"disabled");
  9754. } else {
  9755. struct ast_format tmpfmt;
  9756. using_prefs = "mine";
  9757. if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
  9758. /* Do the opposite of what we tried above. */
  9759. if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
  9760. pref = iaxs[fr->callno]->prefs;
  9761. } else {
  9762. pref = iaxs[fr->callno]->rprefs;
  9763. using_prefs = "caller";
  9764. }
  9765. format = iax2_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
  9766. } else /* if no codec_prefs IE do it the old way */
  9767. format = iax2_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
  9768. }
  9769. }
  9770. if (!format) {
  9771. char tmp[256], tmp2[256], tmp3[256];
  9772. memset(&ied0, 0, sizeof(ied0));
  9773. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
  9774. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  9775. ast_log(LOG_ERROR, "No best format in '%s'???\n", iax2_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability));
  9776. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  9777. if (!iaxs[fr->callno]) {
  9778. break;
  9779. }
  9780. if (authdebug) {
  9781. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
  9782. ast_inet_ntoa(sin.sin_addr),
  9783. iax2_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
  9784. iax2_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
  9785. iax2_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
  9786. }
  9787. ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
  9788. break;
  9789. }
  9790. }
  9791. }
  9792. if (format) {
  9793. /* No authentication required, let them in */
  9794. memset(&ied1, 0, sizeof(ied1));
  9795. iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
  9796. iax_ie_append_versioned_uint64(&ied1, IAX_IE_FORMAT2, 0, format);
  9797. send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
  9798. if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
  9799. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
  9800. ast_verb(3, "Accepting UNAUTHENTICATED call from %s:\n"
  9801. "%srequested format = %s,\n"
  9802. "%srequested prefs = %s,\n"
  9803. "%sactual format = %s,\n"
  9804. "%shost prefs = %s,\n"
  9805. "%spriority = %s\n",
  9806. ast_inet_ntoa(sin.sin_addr),
  9807. VERBOSE_PREFIX_4,
  9808. iax2_getformatname(iaxs[fr->callno]->peerformat),
  9809. VERBOSE_PREFIX_4,
  9810. caller_pref_buf,
  9811. VERBOSE_PREFIX_4,
  9812. iax2_getformatname(format),
  9813. VERBOSE_PREFIX_4,
  9814. host_pref_buf,
  9815. VERBOSE_PREFIX_4,
  9816. using_prefs);
  9817. iaxs[fr->callno]->chosenformat = format;
  9818. /* Since this is a new call, we should go ahead and set the callid for it. */
  9819. iax_pvt_callid_new(fr->callno);
  9820. ast_set_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART);
  9821. } else {
  9822. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
  9823. /* If this is a TBD call, we're ready but now what... */
  9824. ast_verb(3, "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
  9825. }
  9826. }
  9827. }
  9828. break;
  9829. }
  9830. if (iaxs[fr->callno]->authmethods & IAX_AUTH_MD5)
  9831. merge_encryption(iaxs[fr->callno],ies.encmethods);
  9832. else
  9833. iaxs[fr->callno]->encmethods = 0;
  9834. if (!authenticate_request(fr->callno) && iaxs[fr->callno])
  9835. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED);
  9836. break;
  9837. case IAX_COMMAND_DPREQ:
  9838. /* Request status in the dialplan */
  9839. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
  9840. !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
  9841. if (iaxcompat) {
  9842. /* Spawn a thread for the lookup */
  9843. spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
  9844. } else {
  9845. /* Just look it up */
  9846. dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
  9847. }
  9848. }
  9849. break;
  9850. case IAX_COMMAND_HANGUP:
  9851. ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
  9852. ast_debug(1, "Immediately destroying %d, having received hangup\n", fr->callno);
  9853. /* Set hangup cause according to remote and hangupsource */
  9854. if (iaxs[fr->callno]->owner) {
  9855. set_hangup_source_and_cause(fr->callno, ies.causecode);
  9856. if (!iaxs[fr->callno]) {
  9857. break;
  9858. }
  9859. }
  9860. /* Send ack immediately, before we destroy */
  9861. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  9862. iax2_destroy(fr->callno);
  9863. break;
  9864. case IAX_COMMAND_REJECT:
  9865. /* Set hangup cause according to remote and hangup source */
  9866. if (iaxs[fr->callno]->owner) {
  9867. set_hangup_source_and_cause(fr->callno, ies.causecode);
  9868. if (!iaxs[fr->callno]) {
  9869. break;
  9870. }
  9871. }
  9872. if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
  9873. if (iaxs[fr->callno]->owner && authdebug)
  9874. ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
  9875. ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr),
  9876. ies.cause ? ies.cause : "<Unknown>");
  9877. ast_debug(1, "Immediately destroying %d, having received reject\n",
  9878. fr->callno);
  9879. }
  9880. /* Send ack immediately, before we destroy */
  9881. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK,
  9882. fr->ts, NULL, 0, fr->iseqno);
  9883. if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION))
  9884. iaxs[fr->callno]->error = EPERM;
  9885. iax2_destroy(fr->callno);
  9886. break;
  9887. case IAX_COMMAND_TRANSFER:
  9888. {
  9889. struct ast_channel *bridged_chan;
  9890. struct ast_channel *owner;
  9891. iax2_lock_owner(fr->callno);
  9892. if (!iaxs[fr->callno]) {
  9893. /* Initiating call went away before we could transfer. */
  9894. break;
  9895. }
  9896. owner = iaxs[fr->callno]->owner;
  9897. bridged_chan = owner ? ast_bridged_channel(owner) : NULL;
  9898. if (bridged_chan && ies.called_number) {
  9899. const char *context;
  9900. context = ast_strdupa(iaxs[fr->callno]->context);
  9901. ast_channel_ref(owner);
  9902. ast_channel_ref(bridged_chan);
  9903. ast_channel_unlock(owner);
  9904. ast_mutex_unlock(&iaxsl[fr->callno]);
  9905. /* Set BLINDTRANSFER channel variables */
  9906. pbx_builtin_setvar_helper(owner, "BLINDTRANSFER", ast_channel_name(bridged_chan));
  9907. pbx_builtin_setvar_helper(bridged_chan, "BLINDTRANSFER", ast_channel_name(owner));
  9908. /* DO NOT hold any locks while calling ast_parking_ext_valid() */
  9909. if (ast_parking_ext_valid(ies.called_number, owner, context)) {
  9910. ast_debug(1, "Parking call '%s'\n", ast_channel_name(bridged_chan));
  9911. if (iax_park(bridged_chan, owner, ies.called_number, context)) {
  9912. ast_log(LOG_WARNING, "Failed to park call '%s'\n",
  9913. ast_channel_name(bridged_chan));
  9914. }
  9915. } else {
  9916. if (ast_async_goto(bridged_chan, context, ies.called_number, 1)) {
  9917. ast_log(LOG_WARNING,
  9918. "Async goto of '%s' to '%s@%s' failed\n",
  9919. ast_channel_name(bridged_chan), ies.called_number, context);
  9920. } else {
  9921. ast_debug(1, "Async goto of '%s' to '%s@%s' started\n",
  9922. ast_channel_name(bridged_chan), ies.called_number, context);
  9923. }
  9924. }
  9925. ast_channel_unref(owner);
  9926. ast_channel_unref(bridged_chan);
  9927. ast_mutex_lock(&iaxsl[fr->callno]);
  9928. } else {
  9929. ast_debug(1, "Async goto not applicable on call %d\n", fr->callno);
  9930. if (owner) {
  9931. ast_channel_unlock(owner);
  9932. }
  9933. }
  9934. break;
  9935. }
  9936. case IAX_COMMAND_ACCEPT:
  9937. /* Ignore if call is already up or needs authentication or is a TBD */
  9938. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD | IAX_STATE_AUTHENTICATED))
  9939. break;
  9940. if (ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
  9941. /* Send ack immediately, before we destroy */
  9942. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  9943. iax2_destroy(fr->callno);
  9944. break;
  9945. }
  9946. if (ies.format) {
  9947. iaxs[fr->callno]->peerformat = ies.format;
  9948. } else {
  9949. if (iaxs[fr->callno]->owner)
  9950. iaxs[fr->callno]->peerformat = ast_format_cap_to_old_bitfield(ast_channel_nativeformats(iaxs[fr->callno]->owner));
  9951. else
  9952. iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
  9953. }
  9954. ast_verb(3, "Call accepted by %s (format %s)\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iax2_getformatname(iaxs[fr->callno]->peerformat));
  9955. if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
  9956. memset(&ied0, 0, sizeof(ied0));
  9957. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
  9958. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  9959. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  9960. if (!iaxs[fr->callno]) {
  9961. break;
  9962. }
  9963. if (authdebug) {
  9964. char tmp1[256], tmp2[256];
  9965. ast_log(LOG_NOTICE, "Rejected call to %s, format %s incompatible with our capability %s.\n",
  9966. ast_inet_ntoa(sin.sin_addr),
  9967. iax2_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
  9968. iax2_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
  9969. }
  9970. } else {
  9971. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
  9972. iax2_lock_owner(fr->callno);
  9973. if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
  9974. char tmp[256];
  9975. /* Switch us to use a compatible format */
  9976. ast_format_cap_from_old_bitfield(ast_channel_nativeformats(iaxs[fr->callno]->owner), iaxs[fr->callno]->peerformat);
  9977. ast_verb(3, "Format for call is %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), ast_channel_nativeformats(iaxs[fr->callno]->owner)));
  9978. /* Setup read/write formats properly. */
  9979. if (ast_channel_writeformat(iaxs[fr->callno]->owner)->id)
  9980. ast_set_write_format(iaxs[fr->callno]->owner, ast_channel_writeformat(iaxs[fr->callno]->owner));
  9981. if (ast_channel_readformat(iaxs[fr->callno]->owner)->id)
  9982. ast_set_read_format(iaxs[fr->callno]->owner, ast_channel_readformat(iaxs[fr->callno]->owner));
  9983. ast_channel_unlock(iaxs[fr->callno]->owner);
  9984. }
  9985. }
  9986. if (iaxs[fr->callno]) {
  9987. AST_LIST_LOCK(&dpcache);
  9988. AST_LIST_TRAVERSE(&iaxs[fr->callno]->dpentries, dp, peer_list)
  9989. if (!(dp->flags & CACHE_FLAG_TRANSMITTED))
  9990. iax2_dprequest(dp, fr->callno);
  9991. AST_LIST_UNLOCK(&dpcache);
  9992. }
  9993. break;
  9994. case IAX_COMMAND_POKE:
  9995. /* Send back a pong packet with the original timestamp */
  9996. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
  9997. break;
  9998. case IAX_COMMAND_PING:
  9999. {
  10000. struct iax_ie_data pingied;
  10001. construct_rr(iaxs[fr->callno], &pingied);
  10002. /* Send back a pong packet with the original timestamp */
  10003. send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
  10004. }
  10005. break;
  10006. case IAX_COMMAND_PONG:
  10007. /* Calculate ping time */
  10008. iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
  10009. /* save RR info */
  10010. save_rr(fr, &ies);
  10011. /* Good time to write jb stats for this call */
  10012. log_jitterstats(fr->callno);
  10013. if (iaxs[fr->callno]->peerpoke) {
  10014. peer = iaxs[fr->callno]->peerpoke;
  10015. if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
  10016. if (iaxs[fr->callno]->pingtime <= peer->maxms) {
  10017. ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %u\n", peer->name, iaxs[fr->callno]->pingtime);
  10018. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Reachable\r\nTime: %u\r\n", peer->name, iaxs[fr->callno]->pingtime);
  10019. ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
  10020. }
  10021. } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
  10022. if (iaxs[fr->callno]->pingtime > peer->maxms) {
  10023. ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%u ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
  10024. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Lagged\r\nTime: %u\r\n", peer->name, iaxs[fr->callno]->pingtime);
  10025. ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
  10026. }
  10027. }
  10028. peer->lastms = iaxs[fr->callno]->pingtime;
  10029. if (peer->smoothing && (peer->lastms > -1))
  10030. peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
  10031. else if (peer->smoothing && peer->lastms < 0)
  10032. peer->historicms = (0 + peer->historicms) / 2;
  10033. else
  10034. peer->historicms = iaxs[fr->callno]->pingtime;
  10035. /* Remove scheduled iax2_poke_noanswer */
  10036. if (peer->pokeexpire > -1) {
  10037. if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
  10038. peer_unref(peer);
  10039. peer->pokeexpire = -1;
  10040. }
  10041. }
  10042. /* Schedule the next cycle */
  10043. if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
  10044. peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
  10045. else
  10046. peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
  10047. if (peer->pokeexpire == -1)
  10048. peer_unref(peer);
  10049. /* and finally send the ack */
  10050. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  10051. /* And wrap up the qualify call */
  10052. iax2_destroy(fr->callno);
  10053. peer->callno = 0;
  10054. ast_debug(1, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
  10055. }
  10056. break;
  10057. case IAX_COMMAND_LAGRQ:
  10058. case IAX_COMMAND_LAGRP:
  10059. f.src = "LAGRQ";
  10060. f.mallocd = 0;
  10061. f.offset = 0;
  10062. f.samples = 0;
  10063. iax_frame_wrap(fr, &f);
  10064. if (f.subclass.integer == IAX_COMMAND_LAGRQ) {
  10065. /* Received a LAGRQ - echo back a LAGRP */
  10066. fr->af.subclass.integer = IAX_COMMAND_LAGRP;
  10067. iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
  10068. } else {
  10069. /* Received LAGRP in response to our LAGRQ */
  10070. unsigned int ts;
  10071. /* This is a reply we've been given, actually measure the difference */
  10072. ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
  10073. iaxs[fr->callno]->lag = ts - fr->ts;
  10074. if (iaxdebug)
  10075. ast_debug(1, "Peer %s lag measured as %dms\n",
  10076. ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->lag);
  10077. }
  10078. break;
  10079. case IAX_COMMAND_AUTHREQ:
  10080. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
  10081. ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
  10082. break;
  10083. }
  10084. if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
  10085. struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
  10086. .subclass.integer = AST_CONTROL_HANGUP,
  10087. };
  10088. ast_log(LOG_WARNING,
  10089. "I don't know how to authenticate %s to %s\n",
  10090. ies.username ? ies.username : "<unknown>", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr));
  10091. iax2_queue_frame(fr->callno, &hangup_fr);
  10092. }
  10093. break;
  10094. case IAX_COMMAND_AUTHREP:
  10095. /* For security, always ack immediately */
  10096. if (delayreject)
  10097. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  10098. /* Ignore once we've started */
  10099. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
  10100. ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
  10101. break;
  10102. }
  10103. if (authenticate_verify(iaxs[fr->callno], &ies)) {
  10104. if (authdebug)
  10105. ast_log(LOG_NOTICE, "Host %s failed to authenticate as %s\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->username);
  10106. memset(&ied0, 0, sizeof(ied0));
  10107. auth_fail(fr->callno, IAX_COMMAND_REJECT);
  10108. break;
  10109. }
  10110. if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
  10111. /* This might re-enter the IAX code and need the lock */
  10112. exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
  10113. } else
  10114. exists = 0;
  10115. if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
  10116. if (authdebug)
  10117. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
  10118. memset(&ied0, 0, sizeof(ied0));
  10119. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
  10120. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
  10121. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  10122. if (!iaxs[fr->callno]) {
  10123. break;
  10124. }
  10125. } else {
  10126. /* Select an appropriate format */
  10127. if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
  10128. if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
  10129. using_prefs = "reqonly";
  10130. } else {
  10131. using_prefs = "disabled";
  10132. }
  10133. format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
  10134. memset(&pref, 0, sizeof(pref));
  10135. strcpy(caller_pref_buf, "disabled");
  10136. strcpy(host_pref_buf, "disabled");
  10137. } else {
  10138. struct ast_format tmpfmt;
  10139. using_prefs = "mine";
  10140. if (ies.codec_prefs)
  10141. ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
  10142. if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
  10143. if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
  10144. pref = iaxs[fr->callno]->rprefs;
  10145. using_prefs = "caller";
  10146. } else {
  10147. pref = iaxs[fr->callno]->prefs;
  10148. }
  10149. } else /* if no codec_prefs IE do it the old way */
  10150. pref = iaxs[fr->callno]->prefs;
  10151. format = iax2_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
  10152. ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
  10153. ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
  10154. }
  10155. if (!format) {
  10156. char tmp1[256], tmp2[256], tmp3[256];
  10157. if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
  10158. ast_debug(1, "We don't do requested format %s, falling back to peer capability '%s'\n",
  10159. iax2_getformatname(iaxs[fr->callno]->peerformat),
  10160. iax2_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peercapability));
  10161. format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
  10162. }
  10163. if (!format) {
  10164. if (authdebug) {
  10165. if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
  10166. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n", ast_inet_ntoa(sin.sin_addr),
  10167. iax2_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
  10168. iax2_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
  10169. } else {
  10170. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
  10171. ast_inet_ntoa(sin.sin_addr),
  10172. iax2_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
  10173. iax2_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
  10174. iax2_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
  10175. }
  10176. }
  10177. memset(&ied0, 0, sizeof(ied0));
  10178. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
  10179. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  10180. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  10181. if (!iaxs[fr->callno]) {
  10182. break;
  10183. }
  10184. } else {
  10185. /* Pick one... */
  10186. if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
  10187. if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
  10188. format = 0;
  10189. } else {
  10190. if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
  10191. using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
  10192. memset(&pref, 0, sizeof(pref));
  10193. format = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ?
  10194. iaxs[fr->callno]->peerformat : iax2_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
  10195. strcpy(caller_pref_buf,"disabled");
  10196. strcpy(host_pref_buf,"disabled");
  10197. } else {
  10198. struct ast_format tmpfmt;
  10199. using_prefs = "mine";
  10200. if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
  10201. /* Do the opposite of what we tried above. */
  10202. if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
  10203. pref = iaxs[fr->callno]->prefs;
  10204. } else {
  10205. pref = iaxs[fr->callno]->rprefs;
  10206. using_prefs = "caller";
  10207. }
  10208. format = iax2_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
  10209. } else /* if no codec_prefs IE do it the old way */
  10210. format = iax2_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
  10211. }
  10212. }
  10213. if (!format) {
  10214. char tmp1[256], tmp2[256], tmp3[256];
  10215. ast_log(LOG_ERROR, "No best format in %s???\n",
  10216. iax2_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability));
  10217. if (authdebug) {
  10218. if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
  10219. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
  10220. ast_inet_ntoa(sin.sin_addr),
  10221. iax2_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
  10222. iax2_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
  10223. } else {
  10224. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
  10225. ast_inet_ntoa(sin.sin_addr),
  10226. iax2_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
  10227. iax2_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
  10228. iax2_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
  10229. }
  10230. }
  10231. memset(&ied0, 0, sizeof(ied0));
  10232. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
  10233. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  10234. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  10235. if (!iaxs[fr->callno]) {
  10236. break;
  10237. }
  10238. }
  10239. }
  10240. }
  10241. if (format) {
  10242. /* Authentication received */
  10243. memset(&ied1, 0, sizeof(ied1));
  10244. iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
  10245. iax_ie_append_versioned_uint64(&ied1, IAX_IE_FORMAT2, 0, format);
  10246. send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
  10247. if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
  10248. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
  10249. ast_verb(3, "Accepting AUTHENTICATED call from %s:\n"
  10250. "%srequested format = %s,\n"
  10251. "%srequested prefs = %s,\n"
  10252. "%sactual format = %s,\n"
  10253. "%shost prefs = %s,\n"
  10254. "%spriority = %s\n",
  10255. ast_inet_ntoa(sin.sin_addr),
  10256. VERBOSE_PREFIX_4,
  10257. iax2_getformatname(iaxs[fr->callno]->peerformat),
  10258. VERBOSE_PREFIX_4,
  10259. caller_pref_buf,
  10260. VERBOSE_PREFIX_4,
  10261. iax2_getformatname(format),
  10262. VERBOSE_PREFIX_4,
  10263. host_pref_buf,
  10264. VERBOSE_PREFIX_4,
  10265. using_prefs);
  10266. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
  10267. if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, format, NULL, 1)))
  10268. iax2_destroy(fr->callno);
  10269. else if (ies.vars) {
  10270. struct ast_datastore *variablestore;
  10271. struct ast_variable *var, *prev = NULL;
  10272. AST_LIST_HEAD(, ast_var_t) *varlist;
  10273. varlist = ast_calloc(1, sizeof(*varlist));
  10274. variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
  10275. if (variablestore && varlist) {
  10276. variablestore->data = varlist;
  10277. variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
  10278. AST_LIST_HEAD_INIT(varlist);
  10279. ast_debug(1, "I can haz IAX vars? w00t\n");
  10280. for (var = ies.vars; var; var = var->next) {
  10281. struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
  10282. if (prev)
  10283. ast_free(prev);
  10284. prev = var;
  10285. if (!newvar) {
  10286. /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
  10287. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  10288. } else {
  10289. AST_LIST_INSERT_TAIL(varlist, newvar, entries);
  10290. }
  10291. }
  10292. if (prev)
  10293. ast_free(prev);
  10294. ies.vars = NULL;
  10295. ast_channel_datastore_add(c, variablestore);
  10296. } else {
  10297. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  10298. if (variablestore)
  10299. ast_datastore_free(variablestore);
  10300. if (varlist)
  10301. ast_free(varlist);
  10302. }
  10303. }
  10304. } else {
  10305. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
  10306. /* If this is a TBD call, we're ready but now what... */
  10307. ast_verb(3, "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
  10308. if (ast_test_flag64(iaxs[fr->callno], IAX_IMMEDIATE)) {
  10309. goto immediatedial;
  10310. }
  10311. }
  10312. }
  10313. }
  10314. break;
  10315. case IAX_COMMAND_DIAL:
  10316. immediatedial:
  10317. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
  10318. ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
  10319. ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
  10320. if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
  10321. if (authdebug)
  10322. ast_log(LOG_NOTICE, "Rejected dial attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
  10323. memset(&ied0, 0, sizeof(ied0));
  10324. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
  10325. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
  10326. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  10327. if (!iaxs[fr->callno]) {
  10328. break;
  10329. }
  10330. } else {
  10331. char tmp[256];
  10332. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
  10333. ast_verb(3, "Accepting DIAL from %s, formats = %s\n",
  10334. ast_inet_ntoa(sin.sin_addr),
  10335. iax2_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat));
  10336. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
  10337. send_command(iaxs[fr->callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
  10338. if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->peerformat, NULL, 1)))
  10339. iax2_destroy(fr->callno);
  10340. else if (ies.vars) {
  10341. struct ast_datastore *variablestore;
  10342. struct ast_variable *var, *prev = NULL;
  10343. AST_LIST_HEAD(, ast_var_t) *varlist;
  10344. varlist = ast_calloc(1, sizeof(*varlist));
  10345. variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
  10346. ast_debug(1, "I can haz IAX vars? w00t\n");
  10347. if (variablestore && varlist) {
  10348. variablestore->data = varlist;
  10349. variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
  10350. AST_LIST_HEAD_INIT(varlist);
  10351. for (var = ies.vars; var; var = var->next) {
  10352. struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
  10353. if (prev)
  10354. ast_free(prev);
  10355. prev = var;
  10356. if (!newvar) {
  10357. /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
  10358. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  10359. } else {
  10360. AST_LIST_INSERT_TAIL(varlist, newvar, entries);
  10361. }
  10362. }
  10363. if (prev)
  10364. ast_free(prev);
  10365. ies.vars = NULL;
  10366. ast_channel_datastore_add(c, variablestore);
  10367. } else {
  10368. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  10369. if (variablestore)
  10370. ast_datastore_free(variablestore);
  10371. if (varlist)
  10372. ast_free(varlist);
  10373. }
  10374. }
  10375. }
  10376. }
  10377. break;
  10378. case IAX_COMMAND_INVAL:
  10379. iaxs[fr->callno]->error = ENOTCONN;
  10380. ast_debug(1, "Immediately destroying %d, having received INVAL\n", fr->callno);
  10381. iax2_destroy(fr->callno);
  10382. ast_debug(1, "Destroying call %d\n", fr->callno);
  10383. break;
  10384. case IAX_COMMAND_VNAK:
  10385. ast_debug(1, "Received VNAK: resending outstanding frames\n");
  10386. /* Force retransmission */
  10387. vnak_retransmit(fr->callno, fr->iseqno);
  10388. break;
  10389. case IAX_COMMAND_REGREQ:
  10390. case IAX_COMMAND_REGREL:
  10391. /* For security, always ack immediately */
  10392. if (delayreject)
  10393. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  10394. if (register_verify(fr->callno, &sin, &ies)) {
  10395. if (!iaxs[fr->callno]) {
  10396. break;
  10397. }
  10398. /* Send delayed failure */
  10399. auth_fail(fr->callno, IAX_COMMAND_REGREJ);
  10400. break;
  10401. }
  10402. if (!iaxs[fr->callno]) {
  10403. break;
  10404. }
  10405. if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
  10406. ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED)) {
  10407. if (f.subclass.integer == IAX_COMMAND_REGREL) {
  10408. memset(&sin, 0, sizeof(sin));
  10409. sin.sin_family = AF_INET;
  10410. }
  10411. if (update_registry(&sin, fr->callno, ies.devicetype, fd, ies.refresh)) {
  10412. ast_log(LOG_WARNING, "Registry error\n");
  10413. }
  10414. if (!iaxs[fr->callno]) {
  10415. break;
  10416. }
  10417. if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
  10418. ast_mutex_unlock(&iaxsl[fr->callno]);
  10419. check_provisioning(&sin, fd, ies.serviceident, ies.provver);
  10420. ast_mutex_lock(&iaxsl[fr->callno]);
  10421. }
  10422. break;
  10423. }
  10424. registry_authrequest(fr->callno);
  10425. break;
  10426. case IAX_COMMAND_REGACK:
  10427. if (iax2_ack_registry(&ies, &sin, fr->callno))
  10428. ast_log(LOG_WARNING, "Registration failure\n");
  10429. /* Send ack immediately, before we destroy */
  10430. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  10431. iax2_destroy(fr->callno);
  10432. break;
  10433. case IAX_COMMAND_REGREJ:
  10434. if (iaxs[fr->callno]->reg) {
  10435. if (authdebug) {
  10436. ast_log(LOG_NOTICE, "Registration of '%s' rejected: '%s' from: '%s'\n", iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>", ast_inet_ntoa(sin.sin_addr));
  10437. manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: IAX2\r\nUsername: %s\r\nStatus: Rejected\r\nCause: %s\r\n", iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>");
  10438. }
  10439. iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
  10440. }
  10441. /* Send ack immediately, before we destroy */
  10442. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  10443. iax2_destroy(fr->callno);
  10444. break;
  10445. case IAX_COMMAND_REGAUTH:
  10446. /* Authentication request */
  10447. if (registry_rerequest(&ies, fr->callno, &sin)) {
  10448. memset(&ied0, 0, sizeof(ied0));
  10449. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
  10450. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
  10451. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  10452. }
  10453. break;
  10454. case IAX_COMMAND_TXREJ:
  10455. while (iaxs[fr->callno]
  10456. && iaxs[fr->callno]->bridgecallno
  10457. && ast_mutex_trylock(&iaxsl[iaxs[fr->callno]->bridgecallno])) {
  10458. DEADLOCK_AVOIDANCE(&iaxsl[fr->callno]);
  10459. }
  10460. if (!iaxs[fr->callno]) {
  10461. break;
  10462. }
  10463. iaxs[fr->callno]->transferring = TRANSFER_NONE;
  10464. ast_verb(3, "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
  10465. memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
  10466. if (!iaxs[fr->callno]->bridgecallno) {
  10467. break;
  10468. }
  10469. if (iaxs[iaxs[fr->callno]->bridgecallno]
  10470. && iaxs[iaxs[fr->callno]->bridgecallno]->transferring) {
  10471. iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_NONE;
  10472. send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
  10473. }
  10474. ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
  10475. break;
  10476. case IAX_COMMAND_TXREADY:
  10477. while (iaxs[fr->callno]
  10478. && iaxs[fr->callno]->bridgecallno
  10479. && ast_mutex_trylock(&iaxsl[iaxs[fr->callno]->bridgecallno])) {
  10480. DEADLOCK_AVOIDANCE(&iaxsl[fr->callno]);
  10481. }
  10482. if (!iaxs[fr->callno]) {
  10483. break;
  10484. }
  10485. if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
  10486. iaxs[fr->callno]->transferring = TRANSFER_READY;
  10487. } else if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN) {
  10488. iaxs[fr->callno]->transferring = TRANSFER_MREADY;
  10489. } else {
  10490. if (iaxs[fr->callno]->bridgecallno) {
  10491. ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
  10492. }
  10493. break;
  10494. }
  10495. ast_verb(3, "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
  10496. if (!iaxs[fr->callno]->bridgecallno) {
  10497. break;
  10498. }
  10499. if (!iaxs[iaxs[fr->callno]->bridgecallno]
  10500. || (iaxs[iaxs[fr->callno]->bridgecallno]->transferring != TRANSFER_READY
  10501. && iaxs[iaxs[fr->callno]->bridgecallno]->transferring != TRANSFER_MREADY)) {
  10502. ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
  10503. break;
  10504. }
  10505. /* Both sides are ready */
  10506. /* XXX what isn't checked here is that both sides match transfer types. */
  10507. if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
  10508. ast_verb(3, "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>",
  10509. iaxs[iaxs[fr->callno]->bridgecallno]->owner ? ast_channel_name(iaxs[iaxs[fr->callno]->bridgecallno]->owner) : "<Unknown>");
  10510. iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MEDIA;
  10511. iaxs[fr->callno]->transferring = TRANSFER_MEDIA;
  10512. memset(&ied0, 0, sizeof(ied0));
  10513. memset(&ied1, 0, sizeof(ied1));
  10514. iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
  10515. iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
  10516. send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
  10517. send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
  10518. } else {
  10519. ast_verb(3, "Releasing %s and %s\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>",
  10520. iaxs[iaxs[fr->callno]->bridgecallno]->owner ? ast_channel_name(iaxs[iaxs[fr->callno]->bridgecallno]->owner) : "<Unknown>");
  10521. iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
  10522. iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
  10523. ast_set_flag64(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
  10524. ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
  10525. /* Stop doing lag & ping requests */
  10526. stop_stuff(fr->callno);
  10527. stop_stuff(iaxs[fr->callno]->bridgecallno);
  10528. memset(&ied0, 0, sizeof(ied0));
  10529. memset(&ied1, 0, sizeof(ied1));
  10530. iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
  10531. iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
  10532. send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
  10533. send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
  10534. }
  10535. ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
  10536. break;
  10537. case IAX_COMMAND_TXREQ:
  10538. try_transfer(iaxs[fr->callno], &ies);
  10539. break;
  10540. case IAX_COMMAND_TXCNT:
  10541. if (iaxs[fr->callno]->transferring)
  10542. send_command_transfer(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, NULL, 0);
  10543. break;
  10544. case IAX_COMMAND_TXREL:
  10545. /* Send ack immediately, rather than waiting until we've changed addresses */
  10546. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  10547. complete_transfer(fr->callno, &ies);
  10548. stop_stuff(fr->callno); /* for attended transfer to work with libiax */
  10549. break;
  10550. case IAX_COMMAND_TXMEDIA:
  10551. if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
  10552. AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
  10553. /* Cancel any outstanding frames and start anew */
  10554. if (cur->transfer) {
  10555. cur->retries = -1;
  10556. }
  10557. }
  10558. /* Start sending our media to the transfer address, but otherwise leave the call as-is */
  10559. iaxs[fr->callno]->transferring = TRANSFER_MEDIAPASS;
  10560. }
  10561. break;
  10562. case IAX_COMMAND_RTKEY:
  10563. if (!IAX_CALLENCRYPTED(iaxs[fr->callno])) {
  10564. ast_log(LOG_WARNING,
  10565. "we've been told to rotate our encryption key, "
  10566. "but this isn't an encrypted call. bad things will happen.\n"
  10567. );
  10568. break;
  10569. }
  10570. IAX_DEBUGDIGEST("Receiving", ies.challenge);
  10571. ast_aes_set_decrypt_key((unsigned char *) ies.challenge, &iaxs[fr->callno]->dcx);
  10572. break;
  10573. case IAX_COMMAND_DPREP:
  10574. complete_dpreply(iaxs[fr->callno], &ies);
  10575. break;
  10576. case IAX_COMMAND_UNSUPPORT:
  10577. ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
  10578. break;
  10579. case IAX_COMMAND_FWDOWNL:
  10580. /* Firmware download */
  10581. if (!ast_test_flag64(&globalflags, IAX_ALLOWFWDOWNLOAD)) {
  10582. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, NULL, 0, -1);
  10583. break;
  10584. }
  10585. memset(&ied0, 0, sizeof(ied0));
  10586. res = iax_firmware_append(&ied0, (unsigned char *)ies.devicetype, ies.fwdesc);
  10587. if (res < 0)
  10588. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  10589. else if (res > 0)
  10590. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
  10591. else
  10592. send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
  10593. break;
  10594. case IAX_COMMAND_CALLTOKEN:
  10595. {
  10596. struct iax_frame *cur;
  10597. /* find last sent frame */
  10598. if ((cur = AST_LIST_LAST(&frame_queue[fr->callno])) && ies.calltoken && ies.calltokendata) {
  10599. resend_with_token(fr->callno, cur, (char *) ies.calltokendata);
  10600. }
  10601. break;
  10602. }
  10603. default:
  10604. ast_debug(1, "Unknown IAX command %d on %d/%d\n", f.subclass.integer, fr->callno, iaxs[fr->callno]->peercallno);
  10605. memset(&ied0, 0, sizeof(ied0));
  10606. iax_ie_append_byte(&ied0, IAX_IE_IAX_UNKNOWN, f.subclass.integer);
  10607. send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
  10608. }
  10609. /* Free remote variables (if any) */
  10610. if (ies.vars) {
  10611. ast_variables_destroy(ies.vars);
  10612. ast_debug(1, "I can haz IAX vars, but they is no good :-(\n");
  10613. ies.vars = NULL;
  10614. }
  10615. /* Don't actually pass these frames along */
  10616. if ((f.subclass.integer != IAX_COMMAND_ACK) &&
  10617. (f.subclass.integer != IAX_COMMAND_TXCNT) &&
  10618. (f.subclass.integer != IAX_COMMAND_TXACC) &&
  10619. (f.subclass.integer != IAX_COMMAND_INVAL) &&
  10620. (f.subclass.integer != IAX_COMMAND_VNAK)) {
  10621. if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno) {
  10622. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  10623. }
  10624. }
  10625. ast_mutex_unlock(&iaxsl[fr->callno]);
  10626. return 1;
  10627. }
  10628. /* Unless this is an ACK or INVAL frame, ack it */
  10629. if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
  10630. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  10631. } else if (minivid) {
  10632. f.frametype = AST_FRAME_VIDEO;
  10633. if (iaxs[fr->callno]->videoformat > 0) {
  10634. if (ntohs(vh->ts) & 0x8000LL) {
  10635. ast_format_set_video_mark(&f.subclass.format);
  10636. }
  10637. ast_format_from_old_bitfield(&f.subclass.format, iaxs[fr->callno]->videoformat);
  10638. } else {
  10639. ast_log(LOG_WARNING, "Received mini frame before first full video frame\n");
  10640. iax2_vnak(fr->callno);
  10641. ast_variables_destroy(ies.vars);
  10642. ast_mutex_unlock(&iaxsl[fr->callno]);
  10643. return 1;
  10644. }
  10645. f.datalen = res - sizeof(*vh);
  10646. if (f.datalen)
  10647. f.data.ptr = thread->buf + sizeof(*vh);
  10648. else
  10649. f.data.ptr = NULL;
  10650. #ifdef IAXTESTS
  10651. if (test_resync) {
  10652. fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
  10653. } else
  10654. #endif /* IAXTESTS */
  10655. fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
  10656. } else {
  10657. /* A mini frame */
  10658. f.frametype = AST_FRAME_VOICE;
  10659. if (iaxs[fr->callno]->voiceformat > 0)
  10660. ast_format_from_old_bitfield(&f.subclass.format, iaxs[fr->callno]->voiceformat);
  10661. else {
  10662. ast_debug(1, "Received mini frame before first full voice frame\n");
  10663. iax2_vnak(fr->callno);
  10664. ast_variables_destroy(ies.vars);
  10665. ast_mutex_unlock(&iaxsl[fr->callno]);
  10666. return 1;
  10667. }
  10668. f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
  10669. if (f.datalen < 0) {
  10670. ast_log(LOG_WARNING, "Datalen < 0?\n");
  10671. ast_variables_destroy(ies.vars);
  10672. ast_mutex_unlock(&iaxsl[fr->callno]);
  10673. return 1;
  10674. }
  10675. if (f.datalen)
  10676. f.data.ptr = thread->buf + sizeof(*mh);
  10677. else
  10678. f.data.ptr = NULL;
  10679. #ifdef IAXTESTS
  10680. if (test_resync) {
  10681. fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
  10682. } else
  10683. #endif /* IAXTESTS */
  10684. fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
  10685. /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
  10686. }
  10687. /* Don't pass any packets until we're started */
  10688. if (!iaxs[fr->callno]
  10689. || !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
  10690. ast_variables_destroy(ies.vars);
  10691. ast_mutex_unlock(&iaxsl[fr->callno]);
  10692. return 1;
  10693. }
  10694. if (f.frametype == AST_FRAME_CONTROL) {
  10695. if (!iax2_is_control_frame_allowed(f.subclass.integer)) {
  10696. /* Control frame not allowed to come from the wire. */
  10697. ast_debug(2, "Callno %d: Blocked receiving control frame %d.\n",
  10698. fr->callno, f.subclass.integer);
  10699. ast_variables_destroy(ies.vars);
  10700. ast_mutex_unlock(&iaxsl[fr->callno]);
  10701. return 1;
  10702. }
  10703. if (f.subclass.integer == AST_CONTROL_CONNECTED_LINE
  10704. || f.subclass.integer == AST_CONTROL_REDIRECTING) {
  10705. if (iaxs[fr->callno]
  10706. && !ast_test_flag64(iaxs[fr->callno], IAX_RECVCONNECTEDLINE)) {
  10707. /* We are not configured to allow receiving these updates. */
  10708. ast_debug(2, "Callno %d: Config blocked receiving control frame %d.\n",
  10709. fr->callno, f.subclass.integer);
  10710. ast_variables_destroy(ies.vars);
  10711. ast_mutex_unlock(&iaxsl[fr->callno]);
  10712. return 1;
  10713. }
  10714. }
  10715. iax2_lock_owner(fr->callno);
  10716. if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
  10717. if (f.subclass.integer == AST_CONTROL_BUSY) {
  10718. ast_channel_hangupcause_set(iaxs[fr->callno]->owner, AST_CAUSE_BUSY);
  10719. } else if (f.subclass.integer == AST_CONTROL_CONGESTION) {
  10720. ast_channel_hangupcause_set(iaxs[fr->callno]->owner, AST_CAUSE_CONGESTION);
  10721. }
  10722. ast_channel_unlock(iaxs[fr->callno]->owner);
  10723. }
  10724. }
  10725. if (f.frametype == AST_FRAME_CONTROL
  10726. && f.subclass.integer == AST_CONTROL_CONNECTED_LINE
  10727. && iaxs[fr->callno]) {
  10728. struct ast_party_connected_line connected;
  10729. /*
  10730. * Process a received connected line update.
  10731. *
  10732. * Initialize defaults.
  10733. */
  10734. ast_party_connected_line_init(&connected);
  10735. connected.id.number.presentation = iaxs[fr->callno]->calling_pres;
  10736. connected.id.name.presentation = iaxs[fr->callno]->calling_pres;
  10737. if (!ast_connected_line_parse_data(f.data.ptr, f.datalen, &connected)) {
  10738. ast_string_field_set(iaxs[fr->callno], cid_num, connected.id.number.str);
  10739. ast_string_field_set(iaxs[fr->callno], cid_name, connected.id.name.str);
  10740. iaxs[fr->callno]->calling_pres = ast_party_id_presentation(&connected.id);
  10741. iax2_lock_owner(fr->callno);
  10742. if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
  10743. ast_set_callerid(iaxs[fr->callno]->owner,
  10744. S_COR(connected.id.number.valid, connected.id.number.str, ""),
  10745. S_COR(connected.id.name.valid, connected.id.name.str, ""),
  10746. NULL);
  10747. ast_channel_caller(iaxs[fr->callno]->owner)->id.number.presentation = connected.id.number.presentation;
  10748. ast_channel_caller(iaxs[fr->callno]->owner)->id.name.presentation = connected.id.name.presentation;
  10749. ast_channel_unlock(iaxs[fr->callno]->owner);
  10750. }
  10751. }
  10752. ast_party_connected_line_free(&connected);
  10753. }
  10754. /* Common things */
  10755. f.src = "IAX2";
  10756. f.mallocd = 0;
  10757. f.offset = 0;
  10758. f.len = 0;
  10759. if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
  10760. f.samples = ast_codec_get_samples(&f);
  10761. /* We need to byteswap incoming slinear samples from network byte order */
  10762. if (f.subclass.format.id == AST_FORMAT_SLINEAR)
  10763. ast_frame_byteswap_be(&f);
  10764. } else
  10765. f.samples = 0;
  10766. iax_frame_wrap(fr, &f);
  10767. /* If this is our most recent packet, use it as our basis for timestamping */
  10768. if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
  10769. /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
  10770. fr->outoforder = 0;
  10771. } else {
  10772. if (iaxdebug && iaxs[fr->callno]) {
  10773. ast_debug(1, "Received out of order packet... (type=%u, subclass %d, ts = %u, last = %u)\n", f.frametype, f.subclass.integer, fr->ts, iaxs[fr->callno]->last);
  10774. }
  10775. fr->outoforder = 1;
  10776. }
  10777. fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
  10778. if (iaxs[fr->callno]) {
  10779. duped_fr = iaxfrdup2(fr);
  10780. if (duped_fr) {
  10781. schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
  10782. }
  10783. }
  10784. if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
  10785. iaxs[fr->callno]->last = fr->ts;
  10786. #if 1
  10787. if (iaxdebug)
  10788. ast_debug(1, "For call=%d, set last=%u\n", fr->callno, fr->ts);
  10789. #endif
  10790. }
  10791. /* Always run again */
  10792. ast_variables_destroy(ies.vars);
  10793. ast_mutex_unlock(&iaxsl[fr->callno]);
  10794. return 1;
  10795. }
  10796. static int socket_process(struct iax2_thread *thread)
  10797. {
  10798. struct ast_callid *callid;
  10799. int res = socket_process_helper(thread);
  10800. if ((callid = ast_read_threadstorage_callid())) {
  10801. ast_callid_threadassoc_remove();
  10802. callid = ast_callid_unref(callid);
  10803. }
  10804. return res;
  10805. }
  10806. /* Function to clean up process thread if it is cancelled */
  10807. static void iax2_process_thread_cleanup(void *data)
  10808. {
  10809. struct iax2_thread *thread = data;
  10810. ast_mutex_destroy(&thread->lock);
  10811. ast_cond_destroy(&thread->cond);
  10812. ast_mutex_destroy(&thread->init_lock);
  10813. ast_cond_destroy(&thread->init_cond);
  10814. ast_free(thread);
  10815. /* Ignore check_return warning from Coverity for ast_atomic_dec_and_test below */
  10816. ast_atomic_dec_and_test(&iaxactivethreadcount);
  10817. }
  10818. static void *iax2_process_thread(void *data)
  10819. {
  10820. struct iax2_thread *thread = data;
  10821. struct timeval wait;
  10822. struct timespec ts;
  10823. int put_into_idle = 0;
  10824. int first_time = 1;
  10825. int old_state;
  10826. ast_atomic_fetchadd_int(&iaxactivethreadcount, 1);
  10827. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);
  10828. pthread_cleanup_push(iax2_process_thread_cleanup, data);
  10829. for (;;) {
  10830. /* Wait for something to signal us to be awake */
  10831. ast_mutex_lock(&thread->lock);
  10832. if (thread->stop) {
  10833. ast_mutex_unlock(&thread->lock);
  10834. break;
  10835. }
  10836. /* Flag that we're ready to accept signals */
  10837. if (first_time) {
  10838. signal_condition(&thread->init_lock, &thread->init_cond);
  10839. first_time = 0;
  10840. }
  10841. /* Put into idle list if applicable */
  10842. if (put_into_idle) {
  10843. insert_idle_thread(thread);
  10844. }
  10845. if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
  10846. struct iax2_thread *t = NULL;
  10847. /* Wait to be signalled or time out */
  10848. wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
  10849. ts.tv_sec = wait.tv_sec;
  10850. ts.tv_nsec = wait.tv_usec * 1000;
  10851. if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
  10852. /* This thread was never put back into the available dynamic
  10853. * thread list, so just go away. */
  10854. if (!put_into_idle || thread->stop) {
  10855. ast_mutex_unlock(&thread->lock);
  10856. break;
  10857. }
  10858. AST_LIST_LOCK(&dynamic_list);
  10859. /* Account for the case where this thread is acquired *right* after a timeout */
  10860. if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
  10861. ast_atomic_fetchadd_int(&iaxdynamicthreadcount, -1);
  10862. AST_LIST_UNLOCK(&dynamic_list);
  10863. if (t) {
  10864. /* This dynamic thread timed out waiting for a task and was
  10865. * not acquired immediately after the timeout,
  10866. * so it's time to go away. */
  10867. ast_mutex_unlock(&thread->lock);
  10868. break;
  10869. }
  10870. /* Someone grabbed our thread *right* after we timed out.
  10871. * Wait for them to set us up with something to do and signal
  10872. * us to continue. */
  10873. wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
  10874. ts.tv_sec = wait.tv_sec;
  10875. ts.tv_nsec = wait.tv_usec * 1000;
  10876. if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
  10877. ast_mutex_unlock(&thread->lock);
  10878. break;
  10879. }
  10880. }
  10881. } else {
  10882. ast_cond_wait(&thread->cond, &thread->lock);
  10883. }
  10884. /* Go back into our respective list */
  10885. put_into_idle = 1;
  10886. ast_mutex_unlock(&thread->lock);
  10887. if (thread->stop) {
  10888. break;
  10889. }
  10890. /* See what we need to do */
  10891. switch (thread->iostate) {
  10892. case IAX_IOSTATE_IDLE:
  10893. continue;
  10894. case IAX_IOSTATE_READY:
  10895. thread->actions++;
  10896. thread->iostate = IAX_IOSTATE_PROCESSING;
  10897. socket_process(thread);
  10898. handle_deferred_full_frames(thread);
  10899. break;
  10900. case IAX_IOSTATE_SCHEDREADY:
  10901. thread->actions++;
  10902. thread->iostate = IAX_IOSTATE_PROCESSING;
  10903. #ifdef SCHED_MULTITHREADED
  10904. thread->schedfunc(thread->scheddata);
  10905. #endif
  10906. break;
  10907. default:
  10908. break;
  10909. }
  10910. /* The network thread added us to the active_thread list when we were given
  10911. * frames to process, Now that we are done, we must remove ourselves from
  10912. * the active list, and return to the idle list */
  10913. AST_LIST_LOCK(&active_list);
  10914. AST_LIST_REMOVE(&active_list, thread, list);
  10915. AST_LIST_UNLOCK(&active_list);
  10916. /* Make sure another frame didn't sneak in there after we thought we were done. */
  10917. handle_deferred_full_frames(thread);
  10918. time(&thread->checktime);
  10919. thread->iostate = IAX_IOSTATE_IDLE;
  10920. #ifdef DEBUG_SCHED_MULTITHREAD
  10921. thread->curfunc[0]='\0';
  10922. #endif
  10923. }
  10924. /*!
  10925. * \note For some reason, idle threads are exiting without being
  10926. * removed from an idle list, which is causing memory
  10927. * corruption. Forcibly remove it from the list, if it's there.
  10928. */
  10929. AST_LIST_LOCK(&idle_list);
  10930. AST_LIST_REMOVE(&idle_list, thread, list);
  10931. AST_LIST_UNLOCK(&idle_list);
  10932. AST_LIST_LOCK(&dynamic_list);
  10933. AST_LIST_REMOVE(&dynamic_list, thread, list);
  10934. AST_LIST_UNLOCK(&dynamic_list);
  10935. if (!thread->stop) {
  10936. /* Nobody asked me to stop so nobody is waiting to join me. */
  10937. pthread_detach(pthread_self());
  10938. }
  10939. /* I am exiting here on my own volition, I need to clean up my own data structures
  10940. * Assume that I am no longer in any of the lists (idle, active, or dynamic)
  10941. */
  10942. pthread_cleanup_pop(1);
  10943. return NULL;
  10944. }
  10945. static int iax2_do_register(struct iax2_registry *reg)
  10946. {
  10947. struct iax_ie_data ied;
  10948. if (iaxdebug)
  10949. ast_debug(1, "Sending registration request for '%s'\n", reg->username);
  10950. if (reg->dnsmgr &&
  10951. ((reg->regstate == REG_STATE_TIMEOUT) || !ast_sockaddr_ipv4(&reg->addr))) {
  10952. /* Maybe the IP has changed, force DNS refresh */
  10953. ast_dnsmgr_refresh(reg->dnsmgr);
  10954. }
  10955. /*
  10956. * if IP has Changed, free allocated call to create a new one with new IP
  10957. * call has the pointer to IP and must be updated to the new one
  10958. */
  10959. if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
  10960. int callno = reg->callno;
  10961. ast_mutex_lock(&iaxsl[callno]);
  10962. iax2_destroy(callno);
  10963. ast_mutex_unlock(&iaxsl[callno]);
  10964. reg->callno = 0;
  10965. }
  10966. if (!ast_sockaddr_ipv4(&reg->addr)) {
  10967. if (iaxdebug)
  10968. ast_debug(1, "Unable to send registration request for '%s' without IP address\n", reg->username);
  10969. /* Setup the next registration attempt */
  10970. reg->expire = iax2_sched_replace(reg->expire, sched,
  10971. (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
  10972. return -1;
  10973. }
  10974. if (!ast_sockaddr_port(&reg->addr) && reg->port) {
  10975. ast_sockaddr_set_port(&reg->addr, reg->port);
  10976. }
  10977. if (!reg->callno) {
  10978. struct sockaddr_in reg_addr;
  10979. ast_debug(3, "Allocate call number\n");
  10980. ast_sockaddr_to_sin(&reg->addr, &reg_addr);
  10981. reg->callno = find_callno_locked(0, 0, &reg_addr, NEW_FORCE, defaultsockfd, 0);
  10982. if (reg->callno < 1) {
  10983. ast_log(LOG_WARNING, "Unable to create call for registration\n");
  10984. return -1;
  10985. } else
  10986. ast_debug(3, "Registration created on call %d\n", reg->callno);
  10987. iaxs[reg->callno]->reg = reg;
  10988. ast_mutex_unlock(&iaxsl[reg->callno]);
  10989. }
  10990. /* Setup the next registration a little early */
  10991. reg->expire = iax2_sched_replace(reg->expire, sched,
  10992. (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
  10993. /* Send the request */
  10994. memset(&ied, 0, sizeof(ied));
  10995. iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
  10996. iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
  10997. add_empty_calltoken_ie(iaxs[reg->callno], &ied); /* this _MUST_ be the last ie added */
  10998. send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
  10999. reg->regstate = REG_STATE_REGSENT;
  11000. return 0;
  11001. }
  11002. static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force)
  11003. {
  11004. /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
  11005. is found for template */
  11006. struct iax_ie_data provdata;
  11007. struct iax_ie_data ied;
  11008. unsigned int sig;
  11009. struct sockaddr_in sin;
  11010. int callno;
  11011. struct create_addr_info cai;
  11012. memset(&cai, 0, sizeof(cai));
  11013. ast_debug(1, "Provisioning '%s' from template '%s'\n", dest, template);
  11014. if (iax_provision_build(&provdata, &sig, template, force)) {
  11015. ast_debug(1, "No provisioning found for template '%s'\n", template);
  11016. return 0;
  11017. }
  11018. if (end) {
  11019. memcpy(&sin, end, sizeof(sin));
  11020. cai.sockfd = sockfd;
  11021. } else if (create_addr(dest, NULL, &sin, &cai))
  11022. return -1;
  11023. /* Build the rest of the message */
  11024. memset(&ied, 0, sizeof(ied));
  11025. iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
  11026. callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
  11027. if (!callno)
  11028. return -1;
  11029. if (iaxs[callno]) {
  11030. /* Schedule autodestruct in case they don't ever give us anything back */
  11031. iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
  11032. sched, 15000, auto_hangup, (void *)(long)callno);
  11033. ast_set_flag64(iaxs[callno], IAX_PROVISION);
  11034. /* Got a call number now, so go ahead and send the provisioning information */
  11035. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
  11036. }
  11037. ast_mutex_unlock(&iaxsl[callno]);
  11038. return 1;
  11039. }
  11040. static char *papp = "IAX2Provision";
  11041. /*! iax2provision
  11042. \ingroup applications
  11043. */
  11044. static int iax2_prov_app(struct ast_channel *chan, const char *data)
  11045. {
  11046. int res;
  11047. char *sdata;
  11048. char *opts;
  11049. int force =0;
  11050. unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(chan));
  11051. if (ast_strlen_zero(data))
  11052. data = "default";
  11053. sdata = ast_strdupa(data);
  11054. opts = strchr(sdata, '|');
  11055. if (opts)
  11056. *opts='\0';
  11057. if (ast_channel_tech(chan) != &iax2_tech) {
  11058. ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
  11059. return -1;
  11060. }
  11061. if (!callno || !iaxs[callno] || !iaxs[callno]->addr.sin_addr.s_addr) {
  11062. ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
  11063. return -1;
  11064. }
  11065. res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
  11066. ast_verb(3, "Provisioned IAXY at '%s' with '%s'= %d\n",
  11067. ast_inet_ntoa(iaxs[callno]->addr.sin_addr),
  11068. sdata, res);
  11069. return res;
  11070. }
  11071. static char *handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  11072. {
  11073. int force = 0;
  11074. int res;
  11075. switch (cmd) {
  11076. case CLI_INIT:
  11077. e->command = "iax2 provision";
  11078. e->usage =
  11079. "Usage: iax2 provision <host> <template> [forced]\n"
  11080. " Provisions the given peer or IP address using a template\n"
  11081. " matching either 'template' or '*' if the template is not\n"
  11082. " found. If 'forced' is specified, even empty provisioning\n"
  11083. " fields will be provisioned as empty fields.\n";
  11084. return NULL;
  11085. case CLI_GENERATE:
  11086. if (a->pos == 3)
  11087. return iax_prov_complete_template(a->line, a->word, a->pos, a->n);
  11088. return NULL;
  11089. }
  11090. if (a->argc < 4)
  11091. return CLI_SHOWUSAGE;
  11092. if (a->argc > 4) {
  11093. if (!strcasecmp(a->argv[4], "forced"))
  11094. force = 1;
  11095. else
  11096. return CLI_SHOWUSAGE;
  11097. }
  11098. res = iax2_provision(NULL, -1, a->argv[2], a->argv[3], force);
  11099. if (res < 0)
  11100. ast_cli(a->fd, "Unable to find peer/address '%s'\n", a->argv[2]);
  11101. else if (res < 1)
  11102. ast_cli(a->fd, "No template (including wildcard) matching '%s'\n", a->argv[3]);
  11103. else
  11104. ast_cli(a->fd, "Provisioning '%s' with template '%s'%s\n", a->argv[2], a->argv[3], force ? ", forced" : "");
  11105. return CLI_SUCCESS;
  11106. }
  11107. static void __iax2_poke_noanswer(const void *data)
  11108. {
  11109. struct iax2_peer *peer = (struct iax2_peer *)data;
  11110. int callno;
  11111. if (peer->lastms > -1) {
  11112. ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
  11113. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, peer->lastms);
  11114. ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
  11115. }
  11116. if ((callno = peer->callno) > 0) {
  11117. ast_mutex_lock(&iaxsl[callno]);
  11118. iax2_destroy(callno);
  11119. ast_mutex_unlock(&iaxsl[callno]);
  11120. }
  11121. peer->callno = 0;
  11122. peer->lastms = -1;
  11123. /* Try again quickly */
  11124. peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
  11125. if (peer->pokeexpire == -1)
  11126. peer_unref(peer);
  11127. }
  11128. static int iax2_poke_noanswer(const void *data)
  11129. {
  11130. struct iax2_peer *peer = (struct iax2_peer *)data;
  11131. peer->pokeexpire = -1;
  11132. #ifdef SCHED_MULTITHREADED
  11133. if (schedule_action(__iax2_poke_noanswer, data))
  11134. #endif
  11135. __iax2_poke_noanswer(data);
  11136. peer_unref(peer);
  11137. return 0;
  11138. }
  11139. static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
  11140. {
  11141. struct iax2_peer *peer = obj;
  11142. iax2_poke_peer(peer, 0);
  11143. return 0;
  11144. }
  11145. static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
  11146. {
  11147. int callno;
  11148. int poke_timeout;
  11149. struct sockaddr_in peer_addr;
  11150. if (!peer->maxms || (!ast_sockaddr_ipv4(&peer->addr) && !peer->dnsmgr)) {
  11151. /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
  11152. immediately after clearing things out */
  11153. peer->lastms = 0;
  11154. peer->historicms = 0;
  11155. peer->pokeexpire = -1;
  11156. peer->callno = 0;
  11157. return 0;
  11158. }
  11159. ast_sockaddr_to_sin(&peer->addr, &peer_addr);
  11160. /* The peer could change the callno inside iax2_destroy, since we do deadlock avoidance */
  11161. if ((callno = peer->callno) > 0) {
  11162. ast_log(LOG_NOTICE, "Still have a callno...\n");
  11163. ast_mutex_lock(&iaxsl[callno]);
  11164. iax2_destroy(callno);
  11165. ast_mutex_unlock(&iaxsl[callno]);
  11166. }
  11167. if (heldcall)
  11168. ast_mutex_unlock(&iaxsl[heldcall]);
  11169. callno = peer->callno = find_callno(0, 0, &peer_addr, NEW_FORCE, peer->sockfd, 0);
  11170. if (heldcall)
  11171. ast_mutex_lock(&iaxsl[heldcall]);
  11172. if (callno < 1) {
  11173. ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
  11174. return -1;
  11175. }
  11176. if (peer->pokeexpire > -1) {
  11177. if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
  11178. peer->pokeexpire = -1;
  11179. peer_unref(peer);
  11180. }
  11181. }
  11182. if (peer->lastms < 0){
  11183. /* If the host is already unreachable then use time less than the unreachable
  11184. * interval. 5/6 is arbitrary multiplier to get value less than
  11185. * peer->pokefreqnotok. Value less than peer->pokefreqnotok is used to expire
  11186. * current POKE before starting new POKE (which is scheduled after
  11187. * peer->pokefreqnotok). */
  11188. poke_timeout = peer->pokefreqnotok * 5 / 6;
  11189. } else {
  11190. /* If the host is reachable, use timeout large enough to allow for multiple
  11191. * POKE retries. Limit this value to less than peer->pokefreqok. 5/6 is arbitrary
  11192. * multiplier to get value less than peer->pokefreqok. Value less than
  11193. * peer->pokefreqok is used to expire current POKE before starting new POKE
  11194. * (which is scheduled after peer->pokefreqok). */
  11195. poke_timeout = MIN(MAX_RETRY_TIME * 2 + peer->maxms, peer->pokefreqok * 5 / 6);
  11196. }
  11197. /* Queue up a new task to handle no reply */
  11198. peer->pokeexpire = iax2_sched_add(sched, poke_timeout, iax2_poke_noanswer, peer_ref(peer));
  11199. if (peer->pokeexpire == -1)
  11200. peer_unref(peer);
  11201. /* And send the poke */
  11202. ast_mutex_lock(&iaxsl[callno]);
  11203. if (iaxs[callno]) {
  11204. struct iax_ie_data ied = {
  11205. .buf = { 0 },
  11206. .pos = 0,
  11207. };
  11208. /* Speed up retransmission times for this qualify call */
  11209. iaxs[callno]->pingtime = peer->maxms / 8;
  11210. iaxs[callno]->peerpoke = peer;
  11211. add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
  11212. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, ied.buf, ied.pos, -1);
  11213. }
  11214. ast_mutex_unlock(&iaxsl[callno]);
  11215. return 0;
  11216. }
  11217. static void free_context(struct iax2_context *con)
  11218. {
  11219. struct iax2_context *conl;
  11220. while(con) {
  11221. conl = con;
  11222. con = con->next;
  11223. ast_free(conl);
  11224. }
  11225. }
  11226. static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause)
  11227. {
  11228. int callno;
  11229. int res;
  11230. struct sockaddr_in sin;
  11231. struct ast_channel *c;
  11232. struct parsed_dial_string pds;
  11233. struct create_addr_info cai;
  11234. char *tmpstr;
  11235. struct ast_callid *callid;
  11236. memset(&pds, 0, sizeof(pds));
  11237. tmpstr = ast_strdupa(data);
  11238. parse_dial_string(tmpstr, &pds);
  11239. callid = ast_read_threadstorage_callid();
  11240. if (ast_strlen_zero(pds.peer)) {
  11241. ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
  11242. return NULL;
  11243. }
  11244. memset(&cai, 0, sizeof(cai));
  11245. cai.capability = iax2_capability;
  11246. ast_copy_flags64(&cai, &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
  11247. /* Populate our address from the given */
  11248. if (create_addr(pds.peer, NULL, &sin, &cai)) {
  11249. *cause = AST_CAUSE_UNREGISTERED;
  11250. return NULL;
  11251. }
  11252. if (pds.port)
  11253. sin.sin_port = htons(atoi(pds.port));
  11254. callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
  11255. if (callno < 1) {
  11256. ast_log(LOG_WARNING, "Unable to create call\n");
  11257. *cause = AST_CAUSE_CONGESTION;
  11258. return NULL;
  11259. }
  11260. /* If this is a trunk, update it now */
  11261. ast_copy_flags64(iaxs[callno], &cai, IAX_TRUNK | IAX_SENDANI | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
  11262. if (ast_test_flag64(&cai, IAX_TRUNK)) {
  11263. int new_callno;
  11264. if ((new_callno = make_trunk(callno, 1)) != -1)
  11265. callno = new_callno;
  11266. }
  11267. iaxs[callno]->maxtime = cai.maxtime;
  11268. if (callid) {
  11269. iax_pvt_callid_set(callno, callid);
  11270. }
  11271. if (cai.found) {
  11272. ast_string_field_set(iaxs[callno], host, pds.peer);
  11273. }
  11274. c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability, requestor ? ast_channel_linkedid(requestor) : NULL, cai.found);
  11275. ast_mutex_unlock(&iaxsl[callno]);
  11276. if (c) {
  11277. struct ast_format_cap *joint;
  11278. if (callid) {
  11279. ast_channel_callid_set(c, callid);
  11280. }
  11281. /* Choose a format we can live with */
  11282. if ((joint = ast_format_cap_joint(ast_channel_nativeformats(c), cap))) {
  11283. ast_format_cap_copy(ast_channel_nativeformats(c), joint);
  11284. joint = ast_format_cap_destroy(joint);
  11285. } else {
  11286. struct ast_format best_fmt_cap;
  11287. struct ast_format best_fmt_native;
  11288. res = ast_translator_best_choice(cap, ast_channel_nativeformats(c), &best_fmt_cap, &best_fmt_native);
  11289. if (res < 0) {
  11290. char tmp[256];
  11291. char tmp2[256];
  11292. ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
  11293. ast_getformatname_multiple(tmp, sizeof(tmp), ast_channel_nativeformats(c)), ast_getformatname_multiple(tmp2, sizeof(tmp2), cap), ast_channel_name(c));
  11294. ast_hangup(c);
  11295. return NULL;
  11296. }
  11297. ast_format_cap_set(ast_channel_nativeformats(c), &best_fmt_native);
  11298. }
  11299. ast_best_codec(ast_channel_nativeformats(c), ast_channel_readformat(c));
  11300. ast_format_copy(ast_channel_writeformat(c), ast_channel_readformat(c));
  11301. }
  11302. if (callid) {
  11303. ast_callid_unref(callid);
  11304. }
  11305. return c;
  11306. }
  11307. static void *network_thread(void *ignore)
  11308. {
  11309. if (timer) {
  11310. ast_io_add(io, ast_timer_fd(timer), timing_read, AST_IO_IN | AST_IO_PRI, NULL);
  11311. }
  11312. for (;;) {
  11313. pthread_testcancel();
  11314. /* Wake up once a second just in case SIGURG was sent while
  11315. * we weren't in poll(), to make sure we don't hang when trying
  11316. * to unload. */
  11317. if (ast_io_wait(io, 1000) <= 0) {
  11318. break;
  11319. }
  11320. }
  11321. return NULL;
  11322. }
  11323. static int start_network_thread(void)
  11324. {
  11325. struct iax2_thread *thread;
  11326. int threadcount = 0;
  11327. int x;
  11328. for (x = 0; x < iaxthreadcount; x++) {
  11329. thread = ast_calloc(1, sizeof(*thread));
  11330. if (thread) {
  11331. thread->type = IAX_THREAD_TYPE_POOL;
  11332. thread->threadnum = ++threadcount;
  11333. ast_mutex_init(&thread->lock);
  11334. ast_cond_init(&thread->cond, NULL);
  11335. ast_mutex_init(&thread->init_lock);
  11336. ast_cond_init(&thread->init_cond, NULL);
  11337. ast_mutex_lock(&thread->init_lock);
  11338. if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
  11339. ast_log(LOG_WARNING, "Failed to create new thread!\n");
  11340. ast_mutex_destroy(&thread->lock);
  11341. ast_cond_destroy(&thread->cond);
  11342. ast_mutex_unlock(&thread->init_lock);
  11343. ast_mutex_destroy(&thread->init_lock);
  11344. ast_cond_destroy(&thread->init_cond);
  11345. ast_free(thread);
  11346. thread = NULL;
  11347. continue;
  11348. }
  11349. /* Wait for the thread to be ready */
  11350. ast_cond_wait(&thread->init_cond, &thread->init_lock);
  11351. /* Done with init_lock */
  11352. ast_mutex_unlock(&thread->init_lock);
  11353. AST_LIST_LOCK(&idle_list);
  11354. AST_LIST_INSERT_TAIL(&idle_list, thread, list);
  11355. AST_LIST_UNLOCK(&idle_list);
  11356. }
  11357. }
  11358. if (ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL)) {
  11359. ast_log(LOG_ERROR, "Failed to create new thread!\n");
  11360. return -1;
  11361. }
  11362. ast_verb(2, "%d helper threads started\n", threadcount);
  11363. return 0;
  11364. }
  11365. static struct iax2_context *build_context(const char *context)
  11366. {
  11367. struct iax2_context *con;
  11368. if ((con = ast_calloc(1, sizeof(*con))))
  11369. ast_copy_string(con->context, context, sizeof(con->context));
  11370. return con;
  11371. }
  11372. static int get_auth_methods(const char *value)
  11373. {
  11374. int methods = 0;
  11375. if (strstr(value, "rsa"))
  11376. methods |= IAX_AUTH_RSA;
  11377. if (strstr(value, "md5"))
  11378. methods |= IAX_AUTH_MD5;
  11379. if (strstr(value, "plaintext"))
  11380. methods |= IAX_AUTH_PLAINTEXT;
  11381. return methods;
  11382. }
  11383. /*! \brief Check if address can be used as packet source.
  11384. \return 0 address available, 1 address unavailable, -1 error
  11385. */
  11386. static int check_srcaddr(struct ast_sockaddr *addr)
  11387. {
  11388. int sd;
  11389. sd = socket(addr->ss.ss_family, SOCK_DGRAM, 0);
  11390. if (sd < 0) {
  11391. ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
  11392. return -1;
  11393. }
  11394. if (ast_bind(sd, addr) < 0) {
  11395. ast_debug(1, "Can't bind: %s\n", strerror(errno));
  11396. close(sd);
  11397. return 1;
  11398. }
  11399. close(sd);
  11400. return 0;
  11401. }
  11402. /*! \brief Parse the "sourceaddress" value,
  11403. lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
  11404. not found. */
  11405. static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
  11406. {
  11407. struct ast_sockaddr addr;
  11408. int nonlocal = 1;
  11409. int port = IAX_DEFAULT_PORTNO;
  11410. int sockfd = defaultsockfd;
  11411. char *tmp;
  11412. char *host;
  11413. char *portstr;
  11414. tmp = ast_strdupa(srcaddr);
  11415. ast_sockaddr_split_hostport(tmp, &host, &portstr, 0);
  11416. if (portstr) {
  11417. port = atoi(portstr);
  11418. if (port < 1)
  11419. port = IAX_DEFAULT_PORTNO;
  11420. }
  11421. addr.ss.ss_family = AF_INET;
  11422. if (!ast_get_ip(&addr, host)) {
  11423. struct ast_netsock *sock;
  11424. if (check_srcaddr(&addr) == 0) {
  11425. /* ip address valid. */
  11426. ast_sockaddr_set_port(&addr, port);
  11427. if (!(sock = ast_netsock_find(netsock, &addr)))
  11428. sock = ast_netsock_find(outsock, &addr);
  11429. if (sock) {
  11430. sockfd = ast_netsock_sockfd(sock);
  11431. nonlocal = 0;
  11432. } else {
  11433. /* INADDR_ANY matches anyway! */
  11434. ast_sockaddr_parse(&addr, "0.0.0.0", 0);
  11435. ast_sockaddr_set_port(&addr, port);
  11436. if (ast_netsock_find(netsock, &addr)) {
  11437. sock = ast_netsock_bind(outsock, io, srcaddr, port, qos.tos, qos.cos, socket_read, NULL);
  11438. if (sock) {
  11439. sockfd = ast_netsock_sockfd(sock);
  11440. ast_netsock_unref(sock);
  11441. nonlocal = 0;
  11442. } else {
  11443. nonlocal = 2;
  11444. }
  11445. }
  11446. }
  11447. }
  11448. }
  11449. peer->sockfd = sockfd;
  11450. if (nonlocal == 1) {
  11451. ast_log(LOG_WARNING,
  11452. "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
  11453. srcaddr,
  11454. peer->name);
  11455. return -1;
  11456. } else if (nonlocal == 2) {
  11457. ast_log(LOG_WARNING,
  11458. "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
  11459. srcaddr,
  11460. peer->name);
  11461. return -1;
  11462. } else {
  11463. ast_debug(1, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
  11464. return 0;
  11465. }
  11466. }
  11467. static void peer_destructor(void *obj)
  11468. {
  11469. struct iax2_peer *peer = obj;
  11470. int callno = peer->callno;
  11471. ast_free_acl_list(peer->acl);
  11472. if (callno > 0) {
  11473. ast_mutex_lock(&iaxsl[callno]);
  11474. iax2_destroy(callno);
  11475. ast_mutex_unlock(&iaxsl[callno]);
  11476. }
  11477. register_peer_exten(peer, 0);
  11478. if (peer->dnsmgr)
  11479. ast_dnsmgr_release(peer->dnsmgr);
  11480. if (peer->mwi_event_sub)
  11481. ast_event_unsubscribe(peer->mwi_event_sub);
  11482. ast_string_field_free_memory(peer);
  11483. }
  11484. /*! \brief Create peer structure based on configuration */
  11485. static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
  11486. {
  11487. struct iax2_peer *peer = NULL;
  11488. struct ast_acl_list *oldacl = NULL;
  11489. int maskfound = 0;
  11490. int found = 0;
  11491. int firstpass = 1;
  11492. int subscribe_acl_change = 0;
  11493. if (!temponly) {
  11494. peer = ao2_find(peers, name, OBJ_KEY);
  11495. if (peer && !ast_test_flag64(peer, IAX_DELME))
  11496. firstpass = 0;
  11497. }
  11498. if (peer) {
  11499. found++;
  11500. if (firstpass) {
  11501. oldacl = peer->acl;
  11502. peer->acl = NULL;
  11503. }
  11504. unlink_peer(peer);
  11505. } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
  11506. peer->expire = -1;
  11507. peer->pokeexpire = -1;
  11508. peer->sockfd = defaultsockfd;
  11509. peer->addr.ss.ss_family = AF_INET;
  11510. peer->addr.len = sizeof(struct sockaddr_in);
  11511. if (ast_string_field_init(peer, 32))
  11512. peer = peer_unref(peer);
  11513. }
  11514. if (peer) {
  11515. if (firstpass) {
  11516. ast_copy_flags64(peer, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
  11517. peer->encmethods = iax2_encryption;
  11518. peer->adsi = adsi;
  11519. ast_string_field_set(peer,secret,"");
  11520. if (!found) {
  11521. ast_string_field_set(peer, name, name);
  11522. ast_sockaddr_set_port(&peer->addr, IAX_DEFAULT_PORTNO);
  11523. peer->expiry = min_reg_expire;
  11524. }
  11525. peer->prefs = prefs;
  11526. peer->capability = iax2_capability;
  11527. peer->smoothing = 0;
  11528. peer->pokefreqok = DEFAULT_FREQ_OK;
  11529. peer->pokefreqnotok = DEFAULT_FREQ_NOTOK;
  11530. peer->maxcallno = 0;
  11531. peercnt_modify((unsigned char) 0, 0, &peer->addr);
  11532. peer->calltoken_required = CALLTOKEN_DEFAULT;
  11533. ast_string_field_set(peer,context,"");
  11534. ast_string_field_set(peer,peercontext,"");
  11535. ast_clear_flag64(peer, IAX_HASCALLERID);
  11536. ast_string_field_set(peer, cid_name, "");
  11537. ast_string_field_set(peer, cid_num, "");
  11538. ast_string_field_set(peer, mohinterpret, mohinterpret);
  11539. ast_string_field_set(peer, mohsuggest, mohsuggest);
  11540. }
  11541. if (!v) {
  11542. v = alt;
  11543. alt = NULL;
  11544. }
  11545. while(v) {
  11546. if (!strcasecmp(v->name, "secret")) {
  11547. ast_string_field_set(peer, secret, v->value);
  11548. } else if (!strcasecmp(v->name, "mailbox")) {
  11549. ast_string_field_set(peer, mailbox, v->value);
  11550. } else if (!strcasecmp(v->name, "hasvoicemail")) {
  11551. if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
  11552. ast_string_field_set(peer, mailbox, name);
  11553. }
  11554. } else if (!strcasecmp(v->name, "mohinterpret")) {
  11555. ast_string_field_set(peer, mohinterpret, v->value);
  11556. } else if (!strcasecmp(v->name, "mohsuggest")) {
  11557. ast_string_field_set(peer, mohsuggest, v->value);
  11558. } else if (!strcasecmp(v->name, "dbsecret")) {
  11559. ast_string_field_set(peer, dbsecret, v->value);
  11560. } else if (!strcasecmp(v->name, "description")) {
  11561. ast_string_field_set(peer, description, v->value);
  11562. } else if (!strcasecmp(v->name, "trunk")) {
  11563. ast_set2_flag64(peer, ast_true(v->value), IAX_TRUNK);
  11564. if (ast_test_flag64(peer, IAX_TRUNK) && !timer) {
  11565. ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without a timing interface\n", peer->name);
  11566. ast_clear_flag64(peer, IAX_TRUNK);
  11567. }
  11568. } else if (!strcasecmp(v->name, "auth")) {
  11569. peer->authmethods = get_auth_methods(v->value);
  11570. } else if (!strcasecmp(v->name, "encryption")) {
  11571. peer->encmethods |= get_encrypt_methods(v->value);
  11572. if (!peer->encmethods) {
  11573. ast_clear_flag64(peer, IAX_FORCE_ENCRYPT);
  11574. }
  11575. } else if (!strcasecmp(v->name, "forceencryption")) {
  11576. if (ast_false(v->value)) {
  11577. ast_clear_flag64(peer, IAX_FORCE_ENCRYPT);
  11578. } else {
  11579. peer->encmethods |= get_encrypt_methods(v->value);
  11580. if (peer->encmethods) {
  11581. ast_set_flag64(peer, IAX_FORCE_ENCRYPT);
  11582. }
  11583. }
  11584. } else if (!strcasecmp(v->name, "transfer")) {
  11585. if (!strcasecmp(v->value, "mediaonly")) {
  11586. ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
  11587. } else if (ast_true(v->value)) {
  11588. ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
  11589. } else
  11590. ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
  11591. } else if (!strcasecmp(v->name, "jitterbuffer")) {
  11592. ast_set2_flag64(peer, ast_true(v->value), IAX_USEJITTERBUF);
  11593. } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
  11594. ast_set2_flag64(peer, ast_true(v->value), IAX_FORCEJITTERBUF);
  11595. } else if (!strcasecmp(v->name, "host")) {
  11596. if (!strcasecmp(v->value, "dynamic")) {
  11597. /* They'll register with us */
  11598. ast_set_flag64(peer, IAX_DYNAMIC);
  11599. if (!found) {
  11600. /* Initialize stuff iff we're not found, otherwise
  11601. we keep going with what we had */
  11602. if (ast_sockaddr_port(&peer->addr)) {
  11603. peer->defaddr.sin_port = htons(ast_sockaddr_port(&peer->addr));
  11604. }
  11605. ast_sockaddr_setnull(&peer->addr);
  11606. }
  11607. } else {
  11608. /* Non-dynamic. Make sure we become that way if we're not */
  11609. AST_SCHED_DEL(sched, peer->expire);
  11610. ast_clear_flag64(peer, IAX_DYNAMIC);
  11611. if (ast_dnsmgr_lookup(v->value, &peer->addr, &peer->dnsmgr, srvlookup ? "_iax._udp" : NULL))
  11612. return peer_unref(peer);
  11613. if (!ast_sockaddr_port(&peer->addr)) {
  11614. ast_sockaddr_set_port(&peer->addr, IAX_DEFAULT_PORTNO);
  11615. }
  11616. }
  11617. if (!maskfound)
  11618. inet_aton("255.255.255.255", &peer->mask);
  11619. } else if (!strcasecmp(v->name, "defaultip")) {
  11620. struct ast_sockaddr peer_defaddr_tmp;
  11621. peer_defaddr_tmp.ss.ss_family = AF_INET;
  11622. if (ast_get_ip(&peer_defaddr_tmp, v->value)) {
  11623. return peer_unref(peer);
  11624. }
  11625. ast_sockaddr_to_sin(&peer_defaddr_tmp,
  11626. &peer->defaddr);
  11627. } else if (!strcasecmp(v->name, "sourceaddress")) {
  11628. peer_set_srcaddr(peer, v->value);
  11629. } else if (!strcasecmp(v->name, "permit") ||
  11630. !strcasecmp(v->name, "deny") ||
  11631. !strcasecmp(v->name, "acl")) {
  11632. ast_append_acl(v->name, v->value, &peer->acl, NULL, &subscribe_acl_change);
  11633. } else if (!strcasecmp(v->name, "mask")) {
  11634. maskfound++;
  11635. inet_aton(v->value, &peer->mask);
  11636. } else if (!strcasecmp(v->name, "context")) {
  11637. ast_string_field_set(peer, context, v->value);
  11638. } else if (!strcasecmp(v->name, "regexten")) {
  11639. ast_string_field_set(peer, regexten, v->value);
  11640. } else if (!strcasecmp(v->name, "peercontext")) {
  11641. ast_string_field_set(peer, peercontext, v->value);
  11642. } else if (!strcasecmp(v->name, "port")) {
  11643. if (ast_test_flag64(peer, IAX_DYNAMIC)) {
  11644. peer->defaddr.sin_port = htons(atoi(v->value));
  11645. } else {
  11646. ast_sockaddr_set_port(&peer->addr, atoi(v->value));
  11647. }
  11648. } else if (!strcasecmp(v->name, "username")) {
  11649. ast_string_field_set(peer, username, v->value);
  11650. } else if (!strcasecmp(v->name, "allow")) {
  11651. iax2_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
  11652. } else if (!strcasecmp(v->name, "disallow")) {
  11653. iax2_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
  11654. } else if (!strcasecmp(v->name, "callerid")) {
  11655. if (!ast_strlen_zero(v->value)) {
  11656. char name2[80];
  11657. char num2[80];
  11658. ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
  11659. ast_string_field_set(peer, cid_name, name2);
  11660. ast_string_field_set(peer, cid_num, num2);
  11661. } else {
  11662. ast_string_field_set(peer, cid_name, "");
  11663. ast_string_field_set(peer, cid_num, "");
  11664. }
  11665. ast_set_flag64(peer, IAX_HASCALLERID);
  11666. } else if (!strcasecmp(v->name, "fullname")) {
  11667. ast_string_field_set(peer, cid_name, S_OR(v->value, ""));
  11668. ast_set_flag64(peer, IAX_HASCALLERID);
  11669. } else if (!strcasecmp(v->name, "cid_number")) {
  11670. ast_string_field_set(peer, cid_num, S_OR(v->value, ""));
  11671. ast_set_flag64(peer, IAX_HASCALLERID);
  11672. } else if (!strcasecmp(v->name, "sendani")) {
  11673. ast_set2_flag64(peer, ast_true(v->value), IAX_SENDANI);
  11674. } else if (!strcasecmp(v->name, "inkeys")) {
  11675. ast_string_field_set(peer, inkeys, v->value);
  11676. } else if (!strcasecmp(v->name, "outkey")) {
  11677. ast_string_field_set(peer, outkey, v->value);
  11678. } else if (!strcasecmp(v->name, "qualify")) {
  11679. if (!strcasecmp(v->value, "no")) {
  11680. peer->maxms = 0;
  11681. } else if (!strcasecmp(v->value, "yes")) {
  11682. peer->maxms = DEFAULT_MAXMS;
  11683. } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
  11684. 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);
  11685. peer->maxms = 0;
  11686. }
  11687. } else if (!strcasecmp(v->name, "qualifysmoothing")) {
  11688. peer->smoothing = ast_true(v->value);
  11689. } else if (!strcasecmp(v->name, "qualifyfreqok")) {
  11690. if (sscanf(v->value, "%30d", &peer->pokefreqok) != 1) {
  11691. ast_log(LOG_WARNING, "Qualification testing frequency of peer '%s' when OK should a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
  11692. }
  11693. } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
  11694. if (sscanf(v->value, "%30d", &peer->pokefreqnotok) != 1) {
  11695. ast_log(LOG_WARNING, "Qualification testing frequency of peer '%s' when NOT OK should be a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
  11696. }
  11697. } else if (!strcasecmp(v->name, "timezone")) {
  11698. ast_string_field_set(peer, zonetag, v->value);
  11699. } else if (!strcasecmp(v->name, "adsi")) {
  11700. peer->adsi = ast_true(v->value);
  11701. } else if (!strcasecmp(v->name, "connectedline")) {
  11702. if (ast_true(v->value)) {
  11703. ast_set_flag64(peer, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
  11704. } else if (!strcasecmp(v->value, "send")) {
  11705. ast_clear_flag64(peer, IAX_RECVCONNECTEDLINE);
  11706. ast_set_flag64(peer, IAX_SENDCONNECTEDLINE);
  11707. } else if (!strcasecmp(v->value, "receive")) {
  11708. ast_clear_flag64(peer, IAX_SENDCONNECTEDLINE);
  11709. ast_set_flag64(peer, IAX_RECVCONNECTEDLINE);
  11710. } else {
  11711. ast_clear_flag64(peer, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
  11712. }
  11713. } else if (!strcasecmp(v->name, "maxcallnumbers")) {
  11714. if (sscanf(v->value, "%10hu", &peer->maxcallno) != 1) {
  11715. ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
  11716. } else {
  11717. peercnt_modify((unsigned char) 1, peer->maxcallno, &peer->addr);
  11718. }
  11719. } else if (!strcasecmp(v->name, "requirecalltoken")) {
  11720. /* default is required unless in optional ip list */
  11721. if (ast_false(v->value)) {
  11722. peer->calltoken_required = CALLTOKEN_NO;
  11723. } else if (!strcasecmp(v->value, "auto")) {
  11724. peer->calltoken_required = CALLTOKEN_AUTO;
  11725. } else if (ast_true(v->value)) {
  11726. peer->calltoken_required = CALLTOKEN_YES;
  11727. } else {
  11728. ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
  11729. }
  11730. } /* else if (strcasecmp(v->name,"type")) */
  11731. /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
  11732. v = v->next;
  11733. if (!v) {
  11734. v = alt;
  11735. alt = NULL;
  11736. }
  11737. }
  11738. if (!peer->authmethods)
  11739. peer->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
  11740. ast_clear_flag64(peer, IAX_DELME);
  11741. }
  11742. if (oldacl)
  11743. ast_free_acl_list(oldacl);
  11744. if (!ast_strlen_zero(peer->mailbox)) {
  11745. char *mailbox, *context;
  11746. context = mailbox = ast_strdupa(peer->mailbox);
  11747. strsep(&context, "@");
  11748. if (ast_strlen_zero(context))
  11749. context = "default";
  11750. peer->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "IAX MWI subscription", NULL,
  11751. AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
  11752. AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
  11753. AST_EVENT_IE_END);
  11754. }
  11755. if (subscribe_acl_change) {
  11756. acl_change_event_subscribe();
  11757. }
  11758. return peer;
  11759. }
  11760. static void user_destructor(void *obj)
  11761. {
  11762. struct iax2_user *user = obj;
  11763. ast_free_acl_list(user->acl);
  11764. free_context(user->contexts);
  11765. if(user->vars) {
  11766. ast_variables_destroy(user->vars);
  11767. user->vars = NULL;
  11768. }
  11769. ast_string_field_free_memory(user);
  11770. }
  11771. /*! \brief Create in-memory user structure from configuration */
  11772. static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
  11773. {
  11774. struct iax2_user *user = NULL;
  11775. struct iax2_context *con, *conl = NULL;
  11776. struct ast_acl_list *oldacl = NULL;
  11777. struct iax2_context *oldcon = NULL;
  11778. int format;
  11779. int firstpass=1;
  11780. int oldcurauthreq = 0;
  11781. int subscribe_acl_change = 0;
  11782. char *varname = NULL, *varval = NULL;
  11783. struct ast_variable *tmpvar = NULL;
  11784. if (!temponly) {
  11785. user = ao2_find(users, name, OBJ_KEY);
  11786. if (user && !ast_test_flag64(user, IAX_DELME))
  11787. firstpass = 0;
  11788. }
  11789. if (user) {
  11790. if (firstpass) {
  11791. oldcurauthreq = user->curauthreq;
  11792. oldacl = user->acl;
  11793. oldcon = user->contexts;
  11794. user->acl = NULL;
  11795. user->contexts = NULL;
  11796. }
  11797. /* Already in the list, remove it and it will be added back (or FREE'd) */
  11798. ao2_unlink(users, user);
  11799. } else {
  11800. user = ao2_alloc(sizeof(*user), user_destructor);
  11801. }
  11802. if (user) {
  11803. if (firstpass) {
  11804. ast_string_field_free_memory(user);
  11805. memset(user, 0, sizeof(struct iax2_user));
  11806. if (ast_string_field_init(user, 32)) {
  11807. user = user_unref(user);
  11808. goto cleanup;
  11809. }
  11810. user->maxauthreq = maxauthreq;
  11811. user->curauthreq = oldcurauthreq;
  11812. user->prefs = prefs;
  11813. user->capability = iax2_capability;
  11814. user->encmethods = iax2_encryption;
  11815. user->adsi = adsi;
  11816. user->calltoken_required = CALLTOKEN_DEFAULT;
  11817. ast_string_field_set(user, name, name);
  11818. ast_string_field_set(user, language, language);
  11819. ast_copy_flags64(user, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_CODEC_USER_FIRST | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
  11820. ast_clear_flag64(user, IAX_HASCALLERID);
  11821. ast_string_field_set(user, cid_name, "");
  11822. ast_string_field_set(user, cid_num, "");
  11823. ast_string_field_set(user, accountcode, accountcode);
  11824. ast_string_field_set(user, mohinterpret, mohinterpret);
  11825. ast_string_field_set(user, mohsuggest, mohsuggest);
  11826. }
  11827. if (!v) {
  11828. v = alt;
  11829. alt = NULL;
  11830. }
  11831. while(v) {
  11832. if (!strcasecmp(v->name, "context")) {
  11833. con = build_context(v->value);
  11834. if (con) {
  11835. if (conl)
  11836. conl->next = con;
  11837. else
  11838. user->contexts = con;
  11839. conl = con;
  11840. }
  11841. } else if (!strcasecmp(v->name, "permit") ||
  11842. !strcasecmp(v->name, "deny") ||
  11843. !strcasecmp(v->name, "acl")) {
  11844. ast_append_acl(v->name, v->value, &user->acl, NULL, &subscribe_acl_change);
  11845. } else if (!strcasecmp(v->name, "setvar")) {
  11846. varname = ast_strdupa(v->value);
  11847. if ((varval = strchr(varname, '='))) {
  11848. *varval = '\0';
  11849. varval++;
  11850. if((tmpvar = ast_variable_new(varname, varval, ""))) {
  11851. tmpvar->next = user->vars;
  11852. user->vars = tmpvar;
  11853. }
  11854. }
  11855. } else if (!strcasecmp(v->name, "allow")) {
  11856. iax2_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
  11857. } else if (!strcasecmp(v->name, "disallow")) {
  11858. iax2_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
  11859. } else if (!strcasecmp(v->name, "trunk")) {
  11860. ast_set2_flag64(user, ast_true(v->value), IAX_TRUNK);
  11861. if (ast_test_flag64(user, IAX_TRUNK) && !timer) {
  11862. ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without a timing interface\n", user->name);
  11863. ast_clear_flag64(user, IAX_TRUNK);
  11864. }
  11865. } else if (!strcasecmp(v->name, "auth")) {
  11866. user->authmethods = get_auth_methods(v->value);
  11867. } else if (!strcasecmp(v->name, "encryption")) {
  11868. user->encmethods |= get_encrypt_methods(v->value);
  11869. if (!user->encmethods) {
  11870. ast_clear_flag64(user, IAX_FORCE_ENCRYPT);
  11871. }
  11872. } else if (!strcasecmp(v->name, "forceencryption")) {
  11873. if (ast_false(v->value)) {
  11874. ast_clear_flag64(user, IAX_FORCE_ENCRYPT);
  11875. } else {
  11876. user->encmethods |= get_encrypt_methods(v->value);
  11877. if (user->encmethods) {
  11878. ast_set_flag64(user, IAX_FORCE_ENCRYPT);
  11879. }
  11880. }
  11881. } else if (!strcasecmp(v->name, "transfer")) {
  11882. if (!strcasecmp(v->value, "mediaonly")) {
  11883. ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
  11884. } else if (ast_true(v->value)) {
  11885. ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
  11886. } else
  11887. ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
  11888. } else if (!strcasecmp(v->name, "codecpriority")) {
  11889. if(!strcasecmp(v->value, "caller"))
  11890. ast_set_flag64(user, IAX_CODEC_USER_FIRST);
  11891. else if(!strcasecmp(v->value, "disabled"))
  11892. ast_set_flag64(user, IAX_CODEC_NOPREFS);
  11893. else if(!strcasecmp(v->value, "reqonly")) {
  11894. ast_set_flag64(user, IAX_CODEC_NOCAP);
  11895. ast_set_flag64(user, IAX_CODEC_NOPREFS);
  11896. }
  11897. } else if (!strcasecmp(v->name, "immediate")) {
  11898. ast_set2_flag64(user, ast_true(v->value), IAX_IMMEDIATE);
  11899. } else if (!strcasecmp(v->name, "jitterbuffer")) {
  11900. ast_set2_flag64(user, ast_true(v->value), IAX_USEJITTERBUF);
  11901. } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
  11902. ast_set2_flag64(user, ast_true(v->value), IAX_FORCEJITTERBUF);
  11903. } else if (!strcasecmp(v->name, "dbsecret")) {
  11904. ast_string_field_set(user, dbsecret, v->value);
  11905. } else if (!strcasecmp(v->name, "secret")) {
  11906. if (!ast_strlen_zero(user->secret)) {
  11907. char *old = ast_strdupa(user->secret);
  11908. ast_string_field_build(user, secret, "%s;%s", old, v->value);
  11909. } else
  11910. ast_string_field_set(user, secret, v->value);
  11911. } else if (!strcasecmp(v->name, "callerid")) {
  11912. if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
  11913. char name2[80];
  11914. char num2[80];
  11915. ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
  11916. ast_string_field_set(user, cid_name, name2);
  11917. ast_string_field_set(user, cid_num, num2);
  11918. ast_set_flag64(user, IAX_HASCALLERID);
  11919. } else {
  11920. ast_clear_flag64(user, IAX_HASCALLERID);
  11921. ast_string_field_set(user, cid_name, "");
  11922. ast_string_field_set(user, cid_num, "");
  11923. }
  11924. } else if (!strcasecmp(v->name, "fullname")) {
  11925. if (!ast_strlen_zero(v->value)) {
  11926. ast_string_field_set(user, cid_name, v->value);
  11927. ast_set_flag64(user, IAX_HASCALLERID);
  11928. } else {
  11929. ast_string_field_set(user, cid_name, "");
  11930. if (ast_strlen_zero(user->cid_num))
  11931. ast_clear_flag64(user, IAX_HASCALLERID);
  11932. }
  11933. } else if (!strcasecmp(v->name, "cid_number")) {
  11934. if (!ast_strlen_zero(v->value)) {
  11935. ast_string_field_set(user, cid_num, v->value);
  11936. ast_set_flag64(user, IAX_HASCALLERID);
  11937. } else {
  11938. ast_string_field_set(user, cid_num, "");
  11939. if (ast_strlen_zero(user->cid_name))
  11940. ast_clear_flag64(user, IAX_HASCALLERID);
  11941. }
  11942. } else if (!strcasecmp(v->name, "accountcode")) {
  11943. ast_string_field_set(user, accountcode, v->value);
  11944. } else if (!strcasecmp(v->name, "mohinterpret")) {
  11945. ast_string_field_set(user, mohinterpret, v->value);
  11946. } else if (!strcasecmp(v->name, "mohsuggest")) {
  11947. ast_string_field_set(user, mohsuggest, v->value);
  11948. } else if (!strcasecmp(v->name, "parkinglot")) {
  11949. ast_string_field_set(user, parkinglot, v->value);
  11950. } else if (!strcasecmp(v->name, "language")) {
  11951. ast_string_field_set(user, language, v->value);
  11952. } else if (!strcasecmp(v->name, "amaflags")) {
  11953. format = ast_cdr_amaflags2int(v->value);
  11954. if (format < 0) {
  11955. ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
  11956. } else {
  11957. user->amaflags = format;
  11958. }
  11959. } else if (!strcasecmp(v->name, "inkeys")) {
  11960. ast_string_field_set(user, inkeys, v->value);
  11961. } else if (!strcasecmp(v->name, "maxauthreq")) {
  11962. user->maxauthreq = atoi(v->value);
  11963. if (user->maxauthreq < 0)
  11964. user->maxauthreq = 0;
  11965. } else if (!strcasecmp(v->name, "adsi")) {
  11966. user->adsi = ast_true(v->value);
  11967. } else if (!strcasecmp(v->name, "connectedline")) {
  11968. if (ast_true(v->value)) {
  11969. ast_set_flag64(user, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
  11970. } else if (!strcasecmp(v->value, "send")) {
  11971. ast_clear_flag64(user, IAX_RECVCONNECTEDLINE);
  11972. ast_set_flag64(user, IAX_SENDCONNECTEDLINE);
  11973. } else if (!strcasecmp(v->value, "receive")) {
  11974. ast_clear_flag64(user, IAX_SENDCONNECTEDLINE);
  11975. ast_set_flag64(user, IAX_RECVCONNECTEDLINE);
  11976. } else {
  11977. ast_clear_flag64(user, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
  11978. }
  11979. } else if (!strcasecmp(v->name, "requirecalltoken")) {
  11980. /* default is required unless in optional ip list */
  11981. if (ast_false(v->value)) {
  11982. user->calltoken_required = CALLTOKEN_NO;
  11983. } else if (!strcasecmp(v->value, "auto")) {
  11984. user->calltoken_required = CALLTOKEN_AUTO;
  11985. } else if (ast_true(v->value)) {
  11986. user->calltoken_required = CALLTOKEN_YES;
  11987. } else {
  11988. ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
  11989. }
  11990. } /* else if (strcasecmp(v->name,"type")) */
  11991. /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
  11992. v = v->next;
  11993. if (!v) {
  11994. v = alt;
  11995. alt = NULL;
  11996. }
  11997. }
  11998. if (!user->authmethods) {
  11999. if (!ast_strlen_zero(user->secret)) {
  12000. user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
  12001. if (!ast_strlen_zero(user->inkeys))
  12002. user->authmethods |= IAX_AUTH_RSA;
  12003. } else if (!ast_strlen_zero(user->inkeys)) {
  12004. user->authmethods = IAX_AUTH_RSA;
  12005. } else {
  12006. user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
  12007. }
  12008. }
  12009. ast_clear_flag64(user, IAX_DELME);
  12010. }
  12011. cleanup:
  12012. if (oldacl) {
  12013. ast_free_acl_list(oldacl);
  12014. }
  12015. if (oldcon) {
  12016. free_context(oldcon);
  12017. }
  12018. if (subscribe_acl_change) {
  12019. acl_change_event_subscribe();
  12020. }
  12021. return user;
  12022. }
  12023. static int peer_delme_cb(void *obj, void *arg, int flags)
  12024. {
  12025. struct iax2_peer *peer = obj;
  12026. ast_set_flag64(peer, IAX_DELME);
  12027. return 0;
  12028. }
  12029. static int user_delme_cb(void *obj, void *arg, int flags)
  12030. {
  12031. struct iax2_user *user = obj;
  12032. ast_set_flag64(user, IAX_DELME);
  12033. return 0;
  12034. }
  12035. static void delete_users(void)
  12036. {
  12037. struct iax2_registry *reg;
  12038. ao2_callback(users, OBJ_NODATA, user_delme_cb, NULL);
  12039. AST_LIST_LOCK(&registrations);
  12040. while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
  12041. if (sched) {
  12042. AST_SCHED_DEL(sched, reg->expire);
  12043. }
  12044. if (reg->callno) {
  12045. int callno = reg->callno;
  12046. ast_mutex_lock(&iaxsl[callno]);
  12047. if (iaxs[callno]) {
  12048. iaxs[callno]->reg = NULL;
  12049. iax2_destroy(callno);
  12050. }
  12051. ast_mutex_unlock(&iaxsl[callno]);
  12052. }
  12053. if (reg->dnsmgr)
  12054. ast_dnsmgr_release(reg->dnsmgr);
  12055. ast_free(reg);
  12056. }
  12057. AST_LIST_UNLOCK(&registrations);
  12058. ao2_callback(peers, OBJ_NODATA, peer_delme_cb, NULL);
  12059. }
  12060. static void prune_users(void)
  12061. {
  12062. struct iax2_user *user;
  12063. struct ao2_iterator i;
  12064. i = ao2_iterator_init(users, 0);
  12065. while ((user = ao2_iterator_next(&i))) {
  12066. if (ast_test_flag64(user, IAX_DELME) || ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
  12067. ao2_unlink(users, user);
  12068. }
  12069. user_unref(user);
  12070. }
  12071. ao2_iterator_destroy(&i);
  12072. }
  12073. /* Prune peers who still are supposed to be deleted */
  12074. static void prune_peers(void)
  12075. {
  12076. struct iax2_peer *peer;
  12077. struct ao2_iterator i;
  12078. i = ao2_iterator_init(peers, 0);
  12079. while ((peer = ao2_iterator_next(&i))) {
  12080. if (ast_test_flag64(peer, IAX_DELME) || ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
  12081. unlink_peer(peer);
  12082. }
  12083. peer_unref(peer);
  12084. }
  12085. ao2_iterator_destroy(&i);
  12086. }
  12087. static void set_config_destroy(void)
  12088. {
  12089. strcpy(accountcode, "");
  12090. strcpy(language, "");
  12091. strcpy(mohinterpret, "");
  12092. strcpy(mohsuggest, "");
  12093. trunkmaxsize = MAX_TRUNKDATA;
  12094. amaflags = 0;
  12095. delayreject = 0;
  12096. ast_clear_flag64((&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF |
  12097. IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
  12098. delete_users();
  12099. ao2_callback(callno_limits, OBJ_NODATA, addr_range_delme_cb, NULL);
  12100. ao2_callback(calltoken_ignores, OBJ_NODATA, addr_range_delme_cb, NULL);
  12101. }
  12102. /*! \brief Load configuration */
  12103. static int set_config(const char *config_file, int reload, int forced)
  12104. {
  12105. struct ast_config *cfg, *ucfg;
  12106. iax2_format capability = iax2_capability;
  12107. struct ast_variable *v;
  12108. char *cat;
  12109. const char *utype;
  12110. const char *tosval;
  12111. int format;
  12112. int portno = IAX_DEFAULT_PORTNO;
  12113. int x;
  12114. int mtuv;
  12115. int subscribe_network_change = 1;
  12116. struct iax2_user *user;
  12117. struct iax2_peer *peer;
  12118. struct ast_netsock *ns;
  12119. struct ast_flags config_flags = { (reload && !forced) ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  12120. #if 0
  12121. static unsigned short int last_port=0;
  12122. #endif
  12123. cfg = ast_config_load(config_file, config_flags);
  12124. if (!cfg) {
  12125. ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
  12126. return -1;
  12127. } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  12128. ucfg = ast_config_load("users.conf", config_flags);
  12129. if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
  12130. return 0;
  12131. /* Otherwise we need to reread both files */
  12132. ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
  12133. if ((cfg = ast_config_load(config_file, config_flags)) == CONFIG_STATUS_FILEINVALID) {
  12134. ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
  12135. ast_config_destroy(ucfg);
  12136. return 0;
  12137. }
  12138. if (!cfg) {
  12139. /* should have been able to load the config here */
  12140. ast_log(LOG_ERROR, "Unable to load config %s again\n", config_file);
  12141. return -1;
  12142. }
  12143. } else if (cfg == CONFIG_STATUS_FILEINVALID) {
  12144. ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
  12145. return 0;
  12146. } else { /* iax.conf changed, gotta reread users.conf, too */
  12147. ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
  12148. if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
  12149. ast_log(LOG_ERROR, "Config file users.conf is in an invalid format. Aborting.\n");
  12150. ast_config_destroy(cfg);
  12151. return 0;
  12152. }
  12153. }
  12154. if (reload) {
  12155. set_config_destroy();
  12156. }
  12157. /* Reset global codec prefs */
  12158. memset(&prefs, 0 , sizeof(struct ast_codec_pref));
  12159. /* Reset Global Flags */
  12160. memset(&globalflags, 0, sizeof(globalflags));
  12161. ast_set_flag64(&globalflags, IAX_RTUPDATE);
  12162. ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
  12163. #ifdef SO_NO_CHECK
  12164. nochecksums = 0;
  12165. #endif
  12166. /* Reset default parking lot */
  12167. default_parkinglot[0] = '\0';
  12168. min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
  12169. max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
  12170. global_max_trunk_mtu = MAX_TRUNK_MTU;
  12171. global_maxcallno = DEFAULT_MAXCALLNO_LIMIT;
  12172. global_maxcallno_nonval = DEFAULT_MAXCALLNO_LIMIT_NONVAL;
  12173. maxauthreq = 3;
  12174. srvlookup = 0;
  12175. v = ast_variable_browse(cfg, "general");
  12176. /* Seed initial tos value */
  12177. tosval = ast_variable_retrieve(cfg, "general", "tos");
  12178. if (tosval) {
  12179. if (ast_str2tos(tosval, &qos.tos))
  12180. ast_log(LOG_WARNING, "Invalid tos value, refer to QoS documentation\n");
  12181. }
  12182. /* Seed initial cos value */
  12183. tosval = ast_variable_retrieve(cfg, "general", "cos");
  12184. if (tosval) {
  12185. if (ast_str2cos(tosval, &qos.cos))
  12186. ast_log(LOG_WARNING, "Invalid cos value, refer to QoS documentation\n");
  12187. }
  12188. while(v) {
  12189. if (!strcasecmp(v->name, "bindport")){
  12190. if (reload)
  12191. ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
  12192. else
  12193. portno = atoi(v->value);
  12194. } else if (!strcasecmp(v->name, "pingtime"))
  12195. ping_time = atoi(v->value);
  12196. else if (!strcasecmp(v->name, "iaxthreadcount")) {
  12197. if (reload) {
  12198. if (atoi(v->value) != iaxthreadcount)
  12199. ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
  12200. } else {
  12201. iaxthreadcount = atoi(v->value);
  12202. if (iaxthreadcount < 1) {
  12203. ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
  12204. iaxthreadcount = 1;
  12205. } else if (iaxthreadcount > 256) {
  12206. ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
  12207. iaxthreadcount = 256;
  12208. }
  12209. }
  12210. } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
  12211. if (reload) {
  12212. AST_LIST_LOCK(&dynamic_list);
  12213. iaxmaxthreadcount = atoi(v->value);
  12214. AST_LIST_UNLOCK(&dynamic_list);
  12215. } else {
  12216. iaxmaxthreadcount = atoi(v->value);
  12217. if (iaxmaxthreadcount < 0) {
  12218. ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
  12219. iaxmaxthreadcount = 0;
  12220. } else if (iaxmaxthreadcount > 256) {
  12221. ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
  12222. iaxmaxthreadcount = 256;
  12223. }
  12224. }
  12225. } else if (!strcasecmp(v->name, "nochecksums")) {
  12226. #ifdef SO_NO_CHECK
  12227. if (ast_true(v->value))
  12228. nochecksums = 1;
  12229. else
  12230. nochecksums = 0;
  12231. #else
  12232. if (ast_true(v->value))
  12233. ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
  12234. #endif
  12235. }
  12236. else if (!strcasecmp(v->name, "maxjitterbuffer"))
  12237. maxjitterbuffer = atoi(v->value);
  12238. else if (!strcasecmp(v->name, "resyncthreshold"))
  12239. resyncthreshold = atoi(v->value);
  12240. else if (!strcasecmp(v->name, "maxjitterinterps"))
  12241. maxjitterinterps = atoi(v->value);
  12242. else if (!strcasecmp(v->name, "jittertargetextra"))
  12243. jittertargetextra = atoi(v->value);
  12244. else if (!strcasecmp(v->name, "lagrqtime"))
  12245. lagrq_time = atoi(v->value);
  12246. else if (!strcasecmp(v->name, "maxregexpire"))
  12247. max_reg_expire = atoi(v->value);
  12248. else if (!strcasecmp(v->name, "minregexpire"))
  12249. min_reg_expire = atoi(v->value);
  12250. else if (!strcasecmp(v->name, "bindaddr")) {
  12251. if (reload) {
  12252. ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
  12253. } else {
  12254. if (!(ns = ast_netsock_bind(netsock, io, v->value, portno, qos.tos, qos.cos, socket_read, NULL))) {
  12255. ast_log(LOG_WARNING, "Unable apply binding to '%s' at line %d\n", v->value, v->lineno);
  12256. } else {
  12257. if (strchr(v->value, ':'))
  12258. ast_verb(2, "Binding IAX2 to '%s'\n", v->value);
  12259. else
  12260. ast_verb(2, "Binding IAX2 to '%s:%d'\n", v->value, portno);
  12261. if (defaultsockfd < 0)
  12262. defaultsockfd = ast_netsock_sockfd(ns);
  12263. ast_netsock_unref(ns);
  12264. }
  12265. }
  12266. } else if (!strcasecmp(v->name, "authdebug")) {
  12267. authdebug = ast_true(v->value);
  12268. } else if (!strcasecmp(v->name, "encryption")) {
  12269. iax2_encryption |= get_encrypt_methods(v->value);
  12270. if (!iax2_encryption) {
  12271. ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
  12272. }
  12273. } else if (!strcasecmp(v->name, "forceencryption")) {
  12274. if (ast_false(v->value)) {
  12275. ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
  12276. } else {
  12277. iax2_encryption |= get_encrypt_methods(v->value);
  12278. if (iax2_encryption) {
  12279. ast_set_flag64((&globalflags), IAX_FORCE_ENCRYPT);
  12280. }
  12281. }
  12282. } else if (!strcasecmp(v->name, "transfer")) {
  12283. if (!strcasecmp(v->value, "mediaonly")) {
  12284. ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
  12285. } else if (ast_true(v->value)) {
  12286. ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
  12287. } else
  12288. ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
  12289. } else if (!strcasecmp(v->name, "codecpriority")) {
  12290. if(!strcasecmp(v->value, "caller"))
  12291. ast_set_flag64((&globalflags), IAX_CODEC_USER_FIRST);
  12292. else if(!strcasecmp(v->value, "disabled"))
  12293. ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
  12294. else if(!strcasecmp(v->value, "reqonly")) {
  12295. ast_set_flag64((&globalflags), IAX_CODEC_NOCAP);
  12296. ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
  12297. }
  12298. } else if (!strcasecmp(v->name, "jitterbuffer"))
  12299. ast_set2_flag64((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
  12300. else if (!strcasecmp(v->name, "forcejitterbuffer"))
  12301. ast_set2_flag64((&globalflags), ast_true(v->value), IAX_FORCEJITTERBUF);
  12302. else if (!strcasecmp(v->name, "delayreject"))
  12303. delayreject = ast_true(v->value);
  12304. else if (!strcasecmp(v->name, "allowfwdownload"))
  12305. ast_set2_flag64((&globalflags), ast_true(v->value), IAX_ALLOWFWDOWNLOAD);
  12306. else if (!strcasecmp(v->name, "rtcachefriends"))
  12307. ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
  12308. else if (!strcasecmp(v->name, "rtignoreregexpire"))
  12309. ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
  12310. else if (!strcasecmp(v->name, "rtupdate"))
  12311. ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTUPDATE);
  12312. else if (!strcasecmp(v->name, "rtsavesysname"))
  12313. ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTSAVE_SYSNAME);
  12314. else if (!strcasecmp(v->name, "trunktimestamps"))
  12315. ast_set2_flag64(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
  12316. else if (!strcasecmp(v->name, "rtautoclear")) {
  12317. int i = atoi(v->value);
  12318. if(i > 0)
  12319. global_rtautoclear = i;
  12320. else
  12321. i = 0;
  12322. ast_set2_flag64((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
  12323. } else if (!strcasecmp(v->name, "trunkfreq")) {
  12324. trunkfreq = atoi(v->value);
  12325. if (trunkfreq < 10) {
  12326. ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 10ms instead.\n");
  12327. trunkfreq = 10;
  12328. } else if (trunkfreq > 1000) {
  12329. ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 1000ms instead.\n");
  12330. trunkfreq = 1000;
  12331. }
  12332. if (timer) {
  12333. ast_timer_set_rate(timer, 1000 / trunkfreq);
  12334. }
  12335. } else if (!strcasecmp(v->name, "trunkmtu")) {
  12336. mtuv = atoi(v->value);
  12337. if (mtuv == 0 )
  12338. global_max_trunk_mtu = 0;
  12339. else if (mtuv >= 172 && mtuv < 4000)
  12340. global_max_trunk_mtu = mtuv;
  12341. else
  12342. ast_log(LOG_NOTICE, "trunkmtu value out of bounds (%d) at line %d\n",
  12343. mtuv, v->lineno);
  12344. } else if (!strcasecmp(v->name, "trunkmaxsize")) {
  12345. trunkmaxsize = atoi(v->value);
  12346. if (trunkmaxsize == 0)
  12347. trunkmaxsize = MAX_TRUNKDATA;
  12348. } else if (!strcasecmp(v->name, "autokill")) {
  12349. if (sscanf(v->value, "%30d", &x) == 1) {
  12350. if (x >= 0)
  12351. autokill = x;
  12352. else
  12353. ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
  12354. } else if (ast_true(v->value)) {
  12355. autokill = DEFAULT_MAXMS;
  12356. } else {
  12357. autokill = 0;
  12358. }
  12359. } else if (!strcasecmp(v->name, "bandwidth")) {
  12360. if (!strcasecmp(v->value, "low")) {
  12361. capability = IAX_CAPABILITY_LOWBANDWIDTH;
  12362. } else if (!strcasecmp(v->value, "medium")) {
  12363. capability = IAX_CAPABILITY_MEDBANDWIDTH;
  12364. } else if (!strcasecmp(v->value, "high")) {
  12365. capability = IAX_CAPABILITY_FULLBANDWIDTH;
  12366. } else
  12367. ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
  12368. } else if (!strcasecmp(v->name, "allow")) {
  12369. iax2_parse_allow_disallow(&prefs, &capability, v->value, 1);
  12370. } else if (!strcasecmp(v->name, "disallow")) {
  12371. iax2_parse_allow_disallow(&prefs, &capability, v->value, 0);
  12372. } else if (!strcasecmp(v->name, "register")) {
  12373. iax2_register(v->value, v->lineno);
  12374. } else if (!strcasecmp(v->name, "iaxcompat")) {
  12375. iaxcompat = ast_true(v->value);
  12376. } else if (!strcasecmp(v->name, "regcontext")) {
  12377. ast_copy_string(regcontext, v->value, sizeof(regcontext));
  12378. /* Create context if it doesn't exist already */
  12379. ast_context_find_or_create(NULL, NULL, regcontext, "IAX2");
  12380. } else if (!strcasecmp(v->name, "tos")) {
  12381. if (ast_str2tos(v->value, &qos.tos))
  12382. ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
  12383. } else if (!strcasecmp(v->name, "cos")) {
  12384. if (ast_str2cos(v->value, &qos.cos))
  12385. ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
  12386. } else if (!strcasecmp(v->name, "parkinglot")) {
  12387. ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
  12388. } else if (!strcasecmp(v->name, "accountcode")) {
  12389. ast_copy_string(accountcode, v->value, sizeof(accountcode));
  12390. } else if (!strcasecmp(v->name, "mohinterpret")) {
  12391. ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
  12392. } else if (!strcasecmp(v->name, "mohsuggest")) {
  12393. ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
  12394. } else if (!strcasecmp(v->name, "amaflags")) {
  12395. format = ast_cdr_amaflags2int(v->value);
  12396. if (format < 0) {
  12397. ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
  12398. } else {
  12399. amaflags = format;
  12400. }
  12401. } else if (!strcasecmp(v->name, "language")) {
  12402. ast_copy_string(language, v->value, sizeof(language));
  12403. } else if (!strcasecmp(v->name, "maxauthreq")) {
  12404. maxauthreq = atoi(v->value);
  12405. if (maxauthreq < 0)
  12406. maxauthreq = 0;
  12407. } else if (!strcasecmp(v->name, "adsi")) {
  12408. adsi = ast_true(v->value);
  12409. } else if (!strcasecmp(v->name, "srvlookup")) {
  12410. srvlookup = ast_true(v->value);
  12411. } else if (!strcasecmp(v->name, "connectedline")) {
  12412. if (ast_true(v->value)) {
  12413. ast_set_flag64((&globalflags), IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
  12414. } else if (!strcasecmp(v->value, "send")) {
  12415. ast_clear_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
  12416. ast_set_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
  12417. } else if (!strcasecmp(v->value, "receive")) {
  12418. ast_clear_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
  12419. ast_set_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
  12420. } else {
  12421. ast_clear_flag64((&globalflags), IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
  12422. }
  12423. } else if (!strcasecmp(v->name, "maxcallnumbers")) {
  12424. if (sscanf(v->value, "%10hu", &global_maxcallno) != 1) {
  12425. ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d\n", v->value, v->lineno);
  12426. }
  12427. } else if (!strcasecmp(v->name, "maxcallnumbers_nonvalidated")) {
  12428. if (sscanf(v->value, "%10hu", &global_maxcallno_nonval) != 1) {
  12429. ast_log(LOG_WARNING, "maxcallnumbers_nonvalidated must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
  12430. }
  12431. } else if (!strcasecmp(v->name, "calltokenoptional")) {
  12432. if (add_calltoken_ignore(v->value)) {
  12433. ast_log(LOG_WARNING, "Invalid calltokenoptional address range - '%s' line %d\n", v->value, v->lineno);
  12434. }
  12435. } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
  12436. if (ast_true(v->value)) {
  12437. subscribe_network_change = 1;
  12438. } else if (ast_false(v->value)) {
  12439. subscribe_network_change = 0;
  12440. } else {
  12441. ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
  12442. }
  12443. } else if (!strcasecmp(v->name, "shrinkcallerid")) {
  12444. if (ast_true(v->value)) {
  12445. ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
  12446. } else if (ast_false(v->value)) {
  12447. ast_clear_flag64((&globalflags), IAX_SHRINKCALLERID);
  12448. } else {
  12449. ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
  12450. }
  12451. }/*else if (strcasecmp(v->name,"type")) */
  12452. /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
  12453. v = v->next;
  12454. }
  12455. if (subscribe_network_change) {
  12456. network_change_event_subscribe();
  12457. } else {
  12458. network_change_event_unsubscribe();
  12459. }
  12460. if (defaultsockfd < 0) {
  12461. if (!(ns = ast_netsock_bind(netsock, io, "0.0.0.0", portno, qos.tos, qos.cos, socket_read, NULL))) {
  12462. ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
  12463. } else {
  12464. ast_verb(2, "Binding IAX2 to default address 0.0.0.0:%d\n", portno);
  12465. defaultsockfd = ast_netsock_sockfd(ns);
  12466. ast_netsock_unref(ns);
  12467. }
  12468. }
  12469. if (reload) {
  12470. ast_netsock_release(outsock);
  12471. outsock = ast_netsock_list_alloc();
  12472. if (!outsock) {
  12473. ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
  12474. return -1;
  12475. }
  12476. ast_netsock_init(outsock);
  12477. }
  12478. if (min_reg_expire > max_reg_expire) {
  12479. ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
  12480. min_reg_expire, max_reg_expire, max_reg_expire);
  12481. min_reg_expire = max_reg_expire;
  12482. }
  12483. iax2_capability = capability;
  12484. if (ucfg) {
  12485. struct ast_variable *gen;
  12486. int genhasiax;
  12487. int genregisteriax;
  12488. const char *hasiax, *registeriax;
  12489. genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
  12490. genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
  12491. gen = ast_variable_browse(ucfg, "general");
  12492. cat = ast_category_browse(ucfg, NULL);
  12493. while (cat) {
  12494. if (strcasecmp(cat, "general")) {
  12495. hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
  12496. registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
  12497. if (ast_true(hasiax) || (!hasiax && genhasiax)) {
  12498. /* Start with general parameters, then specific parameters, user and peer */
  12499. user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
  12500. if (user) {
  12501. ao2_link(users, user);
  12502. user = user_unref(user);
  12503. }
  12504. peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
  12505. if (peer) {
  12506. if (ast_test_flag64(peer, IAX_DYNAMIC))
  12507. reg_source_db(peer);
  12508. ao2_link(peers, peer);
  12509. peer = peer_unref(peer);
  12510. }
  12511. }
  12512. if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
  12513. char tmp[256];
  12514. const char *host = ast_variable_retrieve(ucfg, cat, "host");
  12515. const char *username = ast_variable_retrieve(ucfg, cat, "username");
  12516. const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
  12517. if (!host)
  12518. host = ast_variable_retrieve(ucfg, "general", "host");
  12519. if (!username)
  12520. username = ast_variable_retrieve(ucfg, "general", "username");
  12521. if (!secret)
  12522. secret = ast_variable_retrieve(ucfg, "general", "secret");
  12523. if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
  12524. if (!ast_strlen_zero(secret))
  12525. snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
  12526. else
  12527. snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
  12528. iax2_register(tmp, 0);
  12529. }
  12530. }
  12531. }
  12532. cat = ast_category_browse(ucfg, cat);
  12533. }
  12534. ast_config_destroy(ucfg);
  12535. }
  12536. cat = ast_category_browse(cfg, NULL);
  12537. while(cat) {
  12538. if (strcasecmp(cat, "general")) {
  12539. utype = ast_variable_retrieve(cfg, cat, "type");
  12540. if (!strcasecmp(cat, "callnumberlimits")) {
  12541. build_callno_limits(ast_variable_browse(cfg, cat));
  12542. } else if (utype) {
  12543. if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
  12544. user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
  12545. if (user) {
  12546. ao2_link(users, user);
  12547. user = user_unref(user);
  12548. }
  12549. }
  12550. if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
  12551. peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
  12552. if (peer) {
  12553. if (ast_test_flag64(peer, IAX_DYNAMIC))
  12554. reg_source_db(peer);
  12555. ao2_link(peers, peer);
  12556. peer = peer_unref(peer);
  12557. }
  12558. } else if (strcasecmp(utype, "user")) {
  12559. ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
  12560. }
  12561. } else
  12562. ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
  12563. }
  12564. cat = ast_category_browse(cfg, cat);
  12565. }
  12566. ast_config_destroy(cfg);
  12567. return 1;
  12568. }
  12569. static void poke_all_peers(void)
  12570. {
  12571. struct ao2_iterator i;
  12572. struct iax2_peer *peer;
  12573. i = ao2_iterator_init(peers, 0);
  12574. while ((peer = ao2_iterator_next(&i))) {
  12575. iax2_poke_peer(peer, 0);
  12576. peer_unref(peer);
  12577. }
  12578. ao2_iterator_destroy(&i);
  12579. }
  12580. static int reload_config(int forced_reload)
  12581. {
  12582. static const char config[] = "iax.conf";
  12583. struct iax2_registry *reg;
  12584. if (set_config(config, 1, forced_reload) > 0) {
  12585. prune_peers();
  12586. prune_users();
  12587. ao2_callback(callno_limits, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
  12588. ao2_callback(calltoken_ignores, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
  12589. ao2_callback(peercnts, OBJ_NODATA, set_peercnt_limit_all_cb, NULL);
  12590. trunk_timed = trunk_untimed = 0;
  12591. trunk_nmaxmtu = trunk_maxmtu = 0;
  12592. memset(&debugaddr, '\0', sizeof(debugaddr));
  12593. AST_LIST_LOCK(&registrations);
  12594. AST_LIST_TRAVERSE(&registrations, reg, entry)
  12595. iax2_do_register(reg);
  12596. AST_LIST_UNLOCK(&registrations);
  12597. /* Qualify hosts, too */
  12598. poke_all_peers();
  12599. }
  12600. reload_firmware(0);
  12601. iax_provision_reload(1);
  12602. ast_unload_realtime("iaxpeers");
  12603. return 0;
  12604. }
  12605. static char *handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  12606. {
  12607. switch (cmd) {
  12608. case CLI_INIT:
  12609. e->command = "iax2 reload";
  12610. e->usage =
  12611. "Usage: iax2 reload\n"
  12612. " Reloads IAX configuration from iax.conf\n";
  12613. return NULL;
  12614. case CLI_GENERATE:
  12615. return NULL;
  12616. }
  12617. reload_config(0);
  12618. return CLI_SUCCESS;
  12619. }
  12620. static int reload(void)
  12621. {
  12622. return reload_config(0);
  12623. }
  12624. static int cache_get_callno_locked(const char *data)
  12625. {
  12626. struct sockaddr_in sin;
  12627. int x;
  12628. int callno;
  12629. struct iax_ie_data ied;
  12630. struct create_addr_info cai;
  12631. struct parsed_dial_string pds;
  12632. char *tmpstr;
  12633. for (x = 0; x < ARRAY_LEN(iaxs); x++) {
  12634. /* Look for an *exact match* call. Once a call is negotiated, it can only
  12635. look up entries for a single context */
  12636. if (!ast_mutex_trylock(&iaxsl[x])) {
  12637. if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
  12638. return x;
  12639. ast_mutex_unlock(&iaxsl[x]);
  12640. }
  12641. }
  12642. /* No match found, we need to create a new one */
  12643. memset(&cai, 0, sizeof(cai));
  12644. memset(&ied, 0, sizeof(ied));
  12645. memset(&pds, 0, sizeof(pds));
  12646. tmpstr = ast_strdupa(data);
  12647. parse_dial_string(tmpstr, &pds);
  12648. if (ast_strlen_zero(pds.peer)) {
  12649. ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
  12650. return -1;
  12651. }
  12652. /* Populate our address from the given */
  12653. if (create_addr(pds.peer, NULL, &sin, &cai))
  12654. return -1;
  12655. ast_debug(1, "peer: %s, username: %s, password: %s, context: %s\n",
  12656. pds.peer, pds.username, pds.password, pds.context);
  12657. callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
  12658. if (callno < 1) {
  12659. ast_log(LOG_WARNING, "Unable to create call\n");
  12660. return -1;
  12661. }
  12662. ast_string_field_set(iaxs[callno], dproot, data);
  12663. iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
  12664. iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
  12665. iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, "TBD");
  12666. /* the string format is slightly different from a standard dial string,
  12667. because the context appears in the 'exten' position
  12668. */
  12669. if (pds.exten)
  12670. iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.exten);
  12671. if (pds.username)
  12672. iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
  12673. iax_ie_append_int(&ied, IAX_IE_FORMAT, IAX_CAPABILITY_FULLBANDWIDTH);
  12674. iax_ie_append_int(&ied, IAX_IE_CAPABILITY, IAX_CAPABILITY_FULLBANDWIDTH);
  12675. /* Keep password handy */
  12676. if (pds.password)
  12677. ast_string_field_set(iaxs[callno], secret, pds.password);
  12678. if (pds.key)
  12679. ast_string_field_set(iaxs[callno], outkey, pds.key);
  12680. /* Start the call going */
  12681. add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
  12682. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
  12683. return callno;
  12684. }
  12685. static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
  12686. {
  12687. struct iax2_dpcache *dp = NULL;
  12688. struct timeval now = ast_tvnow();
  12689. int x, com[2], timeout, old = 0, outfd, doabort, callno;
  12690. struct ast_channel *c = NULL;
  12691. struct ast_frame *f = NULL;
  12692. AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, cache_list) {
  12693. if (ast_tvcmp(now, dp->expiry) > 0) {
  12694. AST_LIST_REMOVE_CURRENT(cache_list);
  12695. if ((dp->flags & CACHE_FLAG_PENDING) || dp->callno)
  12696. ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp->flags, dp->callno);
  12697. else
  12698. ast_free(dp);
  12699. continue;
  12700. }
  12701. if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
  12702. break;
  12703. }
  12704. AST_LIST_TRAVERSE_SAFE_END;
  12705. if (!dp) {
  12706. /* No matching entry. Create a new one. */
  12707. /* First, can we make a callno? */
  12708. if ((callno = cache_get_callno_locked(data)) < 0) {
  12709. ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
  12710. return NULL;
  12711. }
  12712. if (!(dp = ast_calloc(1, sizeof(*dp)))) {
  12713. ast_mutex_unlock(&iaxsl[callno]);
  12714. return NULL;
  12715. }
  12716. ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
  12717. ast_copy_string(dp->exten, exten, sizeof(dp->exten));
  12718. dp->expiry = ast_tvnow();
  12719. dp->orig = dp->expiry;
  12720. /* Expires in 30 mins by default */
  12721. dp->expiry.tv_sec += iaxdefaultdpcache;
  12722. dp->flags = CACHE_FLAG_PENDING;
  12723. for (x = 0; x < ARRAY_LEN(dp->waiters); x++)
  12724. dp->waiters[x] = -1;
  12725. /* Insert into the lists */
  12726. AST_LIST_INSERT_TAIL(&dpcache, dp, cache_list);
  12727. AST_LIST_INSERT_TAIL(&iaxs[callno]->dpentries, dp, peer_list);
  12728. /* Send the request if we're already up */
  12729. if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
  12730. iax2_dprequest(dp, callno);
  12731. ast_mutex_unlock(&iaxsl[callno]);
  12732. }
  12733. /* By here we must have a dp */
  12734. if (dp->flags & CACHE_FLAG_PENDING) {
  12735. struct timeval start;
  12736. int ms;
  12737. /* Okay, here it starts to get nasty. We need a pipe now to wait
  12738. for a reply to come back so long as it's pending */
  12739. for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
  12740. /* Find an empty slot */
  12741. if (dp->waiters[x] < 0)
  12742. break;
  12743. }
  12744. if (x >= ARRAY_LEN(dp->waiters)) {
  12745. ast_log(LOG_WARNING, "No more waiter positions available\n");
  12746. return NULL;
  12747. }
  12748. if (pipe(com)) {
  12749. ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
  12750. return NULL;
  12751. }
  12752. dp->waiters[x] = com[1];
  12753. /* Okay, now we wait */
  12754. timeout = iaxdefaulttimeout * 1000;
  12755. /* Temporarily unlock */
  12756. AST_LIST_UNLOCK(&dpcache);
  12757. /* Defer any dtmf */
  12758. if (chan)
  12759. old = ast_channel_defer_dtmf(chan);
  12760. doabort = 0;
  12761. start = ast_tvnow();
  12762. while ((ms = ast_remaining_ms(start, timeout))) {
  12763. c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &ms);
  12764. if (outfd > -1)
  12765. break;
  12766. if (!c)
  12767. continue;
  12768. if (!(f = ast_read(c))) {
  12769. doabort = 1;
  12770. break;
  12771. }
  12772. ast_frfree(f);
  12773. }
  12774. if (!ms) {
  12775. ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
  12776. }
  12777. AST_LIST_LOCK(&dpcache);
  12778. dp->waiters[x] = -1;
  12779. close(com[1]);
  12780. close(com[0]);
  12781. if (doabort) {
  12782. /* Don't interpret anything, just abort. Not sure what th epoint
  12783. of undeferring dtmf on a hung up channel is but hey whatever */
  12784. if (!old && chan)
  12785. ast_channel_undefer_dtmf(chan);
  12786. return NULL;
  12787. }
  12788. if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
  12789. /* Now to do non-independent analysis the results of our wait */
  12790. if (dp->flags & CACHE_FLAG_PENDING) {
  12791. /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
  12792. pending. Don't let it take as long to timeout. */
  12793. dp->flags &= ~CACHE_FLAG_PENDING;
  12794. dp->flags |= CACHE_FLAG_TIMEOUT;
  12795. /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
  12796. systems without leaving it unavailable once the server comes back online */
  12797. dp->expiry.tv_sec = dp->orig.tv_sec + 60;
  12798. for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
  12799. if (dp->waiters[x] > -1) {
  12800. if (write(dp->waiters[x], "asdf", 4) < 0) {
  12801. ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
  12802. }
  12803. }
  12804. }
  12805. }
  12806. }
  12807. /* Our caller will obtain the rest */
  12808. if (!old && chan)
  12809. ast_channel_undefer_dtmf(chan);
  12810. }
  12811. return dp;
  12812. }
  12813. /*! \brief Part of the IAX2 switch interface */
  12814. static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
  12815. {
  12816. int res = 0;
  12817. struct iax2_dpcache *dp = NULL;
  12818. #if 0
  12819. ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
  12820. #endif
  12821. if ((priority != 1) && (priority != 2))
  12822. return 0;
  12823. AST_LIST_LOCK(&dpcache);
  12824. if ((dp = find_cache(chan, data, context, exten, priority))) {
  12825. if (dp->flags & CACHE_FLAG_EXISTS)
  12826. res = 1;
  12827. } else {
  12828. ast_log(LOG_WARNING, "Unable to make DP cache\n");
  12829. }
  12830. AST_LIST_UNLOCK(&dpcache);
  12831. return res;
  12832. }
  12833. /*! \brief part of the IAX2 dial plan switch interface */
  12834. static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
  12835. {
  12836. int res = 0;
  12837. struct iax2_dpcache *dp = NULL;
  12838. #if 0
  12839. ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
  12840. #endif
  12841. if ((priority != 1) && (priority != 2))
  12842. return 0;
  12843. AST_LIST_LOCK(&dpcache);
  12844. if ((dp = find_cache(chan, data, context, exten, priority))) {
  12845. if (dp->flags & CACHE_FLAG_CANEXIST)
  12846. res = 1;
  12847. } else {
  12848. ast_log(LOG_WARNING, "Unable to make DP cache\n");
  12849. }
  12850. AST_LIST_UNLOCK(&dpcache);
  12851. return res;
  12852. }
  12853. /*! \brief Part of the IAX2 Switch interface */
  12854. static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
  12855. {
  12856. int res = 0;
  12857. struct iax2_dpcache *dp = NULL;
  12858. #if 0
  12859. ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
  12860. #endif
  12861. if ((priority != 1) && (priority != 2))
  12862. return 0;
  12863. AST_LIST_LOCK(&dpcache);
  12864. if ((dp = find_cache(chan, data, context, exten, priority))) {
  12865. if (dp->flags & CACHE_FLAG_MATCHMORE)
  12866. res = 1;
  12867. } else {
  12868. ast_log(LOG_WARNING, "Unable to make DP cache\n");
  12869. }
  12870. AST_LIST_UNLOCK(&dpcache);
  12871. return res;
  12872. }
  12873. /*! \brief Execute IAX2 dialplan switch */
  12874. static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
  12875. {
  12876. char odata[256];
  12877. char req[256];
  12878. char *ncontext;
  12879. struct iax2_dpcache *dp = NULL;
  12880. struct ast_app *dial = NULL;
  12881. #if 0
  12882. 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);
  12883. #endif
  12884. if (priority == 2) {
  12885. /* Indicate status, can be overridden in dialplan */
  12886. const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
  12887. if (dialstatus) {
  12888. dial = pbx_findapp(dialstatus);
  12889. if (dial)
  12890. pbx_exec(chan, dial, "");
  12891. }
  12892. return -1;
  12893. } else if (priority != 1)
  12894. return -1;
  12895. AST_LIST_LOCK(&dpcache);
  12896. if ((dp = find_cache(chan, data, context, exten, priority))) {
  12897. if (dp->flags & CACHE_FLAG_EXISTS) {
  12898. ast_copy_string(odata, data, sizeof(odata));
  12899. ncontext = strchr(odata, '/');
  12900. if (ncontext) {
  12901. *ncontext = '\0';
  12902. ncontext++;
  12903. snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
  12904. } else {
  12905. snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
  12906. }
  12907. ast_verb(3, "Executing Dial('%s')\n", req);
  12908. } else {
  12909. AST_LIST_UNLOCK(&dpcache);
  12910. ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
  12911. return -1;
  12912. }
  12913. }
  12914. AST_LIST_UNLOCK(&dpcache);
  12915. if ((dial = pbx_findapp("Dial")))
  12916. return pbx_exec(chan, dial, req);
  12917. else
  12918. ast_log(LOG_WARNING, "No dial application registered\n");
  12919. return -1;
  12920. }
  12921. static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  12922. {
  12923. struct iax2_peer *peer;
  12924. char *peername, *colname;
  12925. peername = ast_strdupa(data);
  12926. /* if our channel, return the IP address of the endpoint of current channel */
  12927. if (!strcmp(peername,"CURRENTCHANNEL")) {
  12928. unsigned short callno;
  12929. if (!chan || ast_channel_tech(chan) != &iax2_tech) {
  12930. return -1;
  12931. }
  12932. callno = PTR_TO_CALLNO(ast_channel_tech_pvt(chan));
  12933. ast_copy_string(buf, iaxs[callno]->addr.sin_addr.s_addr ? ast_inet_ntoa(iaxs[callno]->addr.sin_addr) : "", len);
  12934. return 0;
  12935. }
  12936. if ((colname = strchr(peername, ',')))
  12937. *colname++ = '\0';
  12938. else
  12939. colname = "ip";
  12940. if (!(peer = find_peer(peername, 1)))
  12941. return -1;
  12942. if (!strcasecmp(colname, "ip")) {
  12943. ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
  12944. } else if (!strcasecmp(colname, "status")) {
  12945. peer_status(peer, buf, len);
  12946. } else if (!strcasecmp(colname, "mailbox")) {
  12947. ast_copy_string(buf, peer->mailbox, len);
  12948. } else if (!strcasecmp(colname, "context")) {
  12949. ast_copy_string(buf, peer->context, len);
  12950. } else if (!strcasecmp(colname, "expire")) {
  12951. snprintf(buf, len, "%d", peer->expire);
  12952. } else if (!strcasecmp(colname, "dynamic")) {
  12953. ast_copy_string(buf, (ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
  12954. } else if (!strcasecmp(colname, "callerid_name")) {
  12955. ast_copy_string(buf, peer->cid_name, len);
  12956. } else if (!strcasecmp(colname, "callerid_num")) {
  12957. ast_copy_string(buf, peer->cid_num, len);
  12958. } else if (!strcasecmp(colname, "codecs")) {
  12959. iax2_getformatname_multiple(buf, len -1, peer->capability);
  12960. } else if (!strncasecmp(colname, "codec[", 6)) {
  12961. char *codecnum, *ptr;
  12962. struct ast_format tmpfmt;
  12963. /* skip over "codec" to the '[' */
  12964. codecnum = colname + 5;
  12965. *codecnum = '\0';
  12966. codecnum++;
  12967. if ((ptr = strchr(codecnum, ']'))) {
  12968. *ptr = '\0';
  12969. }
  12970. if((ast_codec_pref_index(&peer->prefs, atoi(codecnum), &tmpfmt))) {
  12971. ast_copy_string(buf, ast_getformatname(&tmpfmt), len);
  12972. } else {
  12973. buf[0] = '\0';
  12974. }
  12975. } else {
  12976. buf[0] = '\0';
  12977. }
  12978. peer_unref(peer);
  12979. return 0;
  12980. }
  12981. static struct ast_custom_function iaxpeer_function = {
  12982. .name = "IAXPEER",
  12983. .read = function_iaxpeer,
  12984. };
  12985. static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *args, char *buf, size_t buflen)
  12986. {
  12987. struct chan_iax2_pvt *pvt;
  12988. unsigned int callno;
  12989. int res = 0;
  12990. if (!chan || ast_channel_tech(chan) != &iax2_tech) {
  12991. ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
  12992. return -1;
  12993. }
  12994. callno = PTR_TO_CALLNO(ast_channel_tech_pvt(chan));
  12995. ast_mutex_lock(&iaxsl[callno]);
  12996. if (!(pvt = iaxs[callno])) {
  12997. ast_mutex_unlock(&iaxsl[callno]);
  12998. return -1;
  12999. }
  13000. if (!strcasecmp(args, "osptoken")) {
  13001. ast_copy_string(buf, pvt->osptoken, buflen);
  13002. } else if (!strcasecmp(args, "peerip")) {
  13003. ast_copy_string(buf, pvt->addr.sin_addr.s_addr ? ast_inet_ntoa(pvt->addr.sin_addr) : "", buflen);
  13004. } else if (!strcasecmp(args, "peername")) {
  13005. ast_copy_string(buf, pvt->username, buflen);
  13006. } else if (!strcasecmp(args, "secure_signaling") || !strcasecmp(args, "secure_media")) {
  13007. snprintf(buf, buflen, "%s", IAX_CALLENCRYPTED(pvt) ? "1" : "");
  13008. } else {
  13009. res = -1;
  13010. }
  13011. ast_mutex_unlock(&iaxsl[callno]);
  13012. return res;
  13013. }
  13014. /*! \brief Part of the device state notification system ---*/
  13015. static int iax2_devicestate(const char *data)
  13016. {
  13017. struct parsed_dial_string pds;
  13018. char *tmp = ast_strdupa(data);
  13019. struct iax2_peer *p;
  13020. int res = AST_DEVICE_INVALID;
  13021. memset(&pds, 0, sizeof(pds));
  13022. parse_dial_string(tmp, &pds);
  13023. if (ast_strlen_zero(pds.peer)) {
  13024. ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
  13025. return res;
  13026. }
  13027. ast_debug(3, "Checking device state for device %s\n", pds.peer);
  13028. /* SLD: FIXME: second call to find_peer during registration */
  13029. if (!(p = find_peer(pds.peer, 1)))
  13030. return res;
  13031. res = AST_DEVICE_UNAVAILABLE;
  13032. ast_debug(3, "Found peer. What's device state of %s? addr=%u, defaddr=%u maxms=%d, lastms=%d\n",
  13033. pds.peer, ast_sockaddr_ipv4(&p->addr), p->defaddr.sin_addr.s_addr, p->maxms, p->lastms);
  13034. if ((ast_sockaddr_ipv4(&p->addr) || p->defaddr.sin_addr.s_addr) &&
  13035. (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
  13036. /* Peer is registered, or have default IP address
  13037. and a valid registration */
  13038. if (p->historicms == 0 || p->historicms <= p->maxms)
  13039. /* let the core figure out whether it is in use or not */
  13040. res = AST_DEVICE_UNKNOWN;
  13041. }
  13042. peer_unref(p);
  13043. return res;
  13044. }
  13045. static struct ast_switch iax2_switch =
  13046. {
  13047. .name = "IAX2",
  13048. .description = "IAX Remote Dialplan Switch",
  13049. .exists = iax2_exists,
  13050. .canmatch = iax2_canmatch,
  13051. .exec = iax2_exec,
  13052. .matchmore = iax2_matchmore,
  13053. };
  13054. /*
  13055. { { "iax2", "show", "cache", NULL },
  13056. iax2_show_cache, "Display IAX cached dialplan",
  13057. show_cache_usage },
  13058. { { "iax2", "show", "channels", NULL },
  13059. iax2_show_channels, "List active IAX channels",
  13060. show_channels_usage },
  13061. { { "iax2", "show", "firmware", NULL },
  13062. iax2_show_firmware, "List available IAX firmwares",
  13063. show_firmware_usage },
  13064. { { "iax2", "show", "netstats", NULL },
  13065. iax2_show_netstats, "List active IAX channel netstats",
  13066. show_netstats_usage },
  13067. { { "iax2", "show", "peers", NULL },
  13068. iax2_show_peers, "List defined IAX peers",
  13069. show_peers_usage },
  13070. { { "iax2", "show", "registry", NULL },
  13071. iax2_show_registry, "Display IAX registration status",
  13072. show_reg_usage },
  13073. { { "iax2", "show", "stats", NULL },
  13074. iax2_show_stats, "Display IAX statistics",
  13075. show_stats_usage },
  13076. { { "iax2", "show", "threads", NULL },
  13077. iax2_show_threads, "Display IAX helper thread info",
  13078. show_threads_usage },
  13079. { { "iax2", "unregister", NULL },
  13080. iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry",
  13081. unregister_usage, complete_iax2_unregister },
  13082. { { "iax2", "set", "mtu", NULL },
  13083. iax2_set_mtu, "Set the IAX systemwide trunking MTU",
  13084. set_mtu_usage, NULL, NULL },
  13085. { { "iax2", "show", "users", NULL },
  13086. iax2_show_users, "List defined IAX users",
  13087. show_users_usage },
  13088. { { "iax2", "prune", "realtime", NULL },
  13089. iax2_prune_realtime, "Prune a cached realtime lookup",
  13090. prune_realtime_usage, complete_iax2_show_peer },
  13091. { { "iax2", "reload", NULL },
  13092. iax2_reload, "Reload IAX configuration",
  13093. iax2_reload_usage },
  13094. { { "iax2", "show", "peer", NULL },
  13095. iax2_show_peer, "Show details on specific IAX peer",
  13096. show_peer_usage, complete_iax2_show_peer },
  13097. { { "iax2", "set", "debug", NULL },
  13098. iax2_do_debug, "Enable IAX debugging",
  13099. debug_usage },
  13100. { { "iax2", "set", "debug", "trunk", NULL },
  13101. iax2_do_trunk_debug, "Enable IAX trunk debugging",
  13102. debug_trunk_usage },
  13103. { { "iax2", "set", "debug", "jb", NULL },
  13104. iax2_do_jb_debug, "Enable IAX jitterbuffer debugging",
  13105. debug_jb_usage },
  13106. { { "iax2", "set", "debug", "off", NULL },
  13107. iax2_no_debug, "Disable IAX debugging",
  13108. no_debug_usage },
  13109. { { "iax2", "set", "debug", "trunk", "off", NULL },
  13110. iax2_no_trunk_debug, "Disable IAX trunk debugging",
  13111. no_debug_trunk_usage },
  13112. { { "iax2", "set", "debug", "jb", "off", NULL },
  13113. iax2_no_jb_debug, "Disable IAX jitterbuffer debugging",
  13114. no_debug_jb_usage },
  13115. { { "iax2", "test", "losspct", NULL },
  13116. iax2_test_losspct, "Set IAX2 incoming frame loss percentage",
  13117. iax2_test_losspct_usage },
  13118. { { "iax2", "provision", NULL },
  13119. iax2_prov_cmd, "Provision an IAX device",
  13120. show_prov_usage, iax2_prov_complete_template_3rd },
  13121. #ifdef IAXTESTS
  13122. { { "iax2", "test", "late", NULL },
  13123. iax2_test_late, "Test the receipt of a late frame",
  13124. iax2_test_late_usage },
  13125. { { "iax2", "test", "resync", NULL },
  13126. iax2_test_resync, "Test a resync in received timestamps",
  13127. iax2_test_resync_usage },
  13128. { { "iax2", "test", "jitter", NULL },
  13129. iax2_test_jitter, "Simulates jitter for testing",
  13130. iax2_test_jitter_usage },
  13131. #endif
  13132. */
  13133. static struct ast_cli_entry cli_iax2[] = {
  13134. AST_CLI_DEFINE(handle_cli_iax2_provision, "Provision an IAX device"),
  13135. AST_CLI_DEFINE(handle_cli_iax2_prune_realtime, "Prune a cached realtime lookup"),
  13136. AST_CLI_DEFINE(handle_cli_iax2_reload, "Reload IAX configuration"),
  13137. AST_CLI_DEFINE(handle_cli_iax2_set_mtu, "Set the IAX systemwide trunking MTU"),
  13138. AST_CLI_DEFINE(handle_cli_iax2_set_debug, "Enable/Disable IAX debugging"),
  13139. AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk, "Enable/Disable IAX trunk debugging"),
  13140. AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb, "Enable/Disable IAX jitterbuffer debugging"),
  13141. AST_CLI_DEFINE(handle_cli_iax2_show_cache, "Display IAX cached dialplan"),
  13142. AST_CLI_DEFINE(handle_cli_iax2_show_channels, "List active IAX channels"),
  13143. AST_CLI_DEFINE(handle_cli_iax2_show_firmware, "List available IAX firmware"),
  13144. AST_CLI_DEFINE(handle_cli_iax2_show_netstats, "List active IAX channel netstats"),
  13145. AST_CLI_DEFINE(handle_cli_iax2_show_peer, "Show details on specific IAX peer"),
  13146. AST_CLI_DEFINE(handle_cli_iax2_show_peers, "List defined IAX peers"),
  13147. AST_CLI_DEFINE(handle_cli_iax2_show_registry, "Display IAX registration status"),
  13148. AST_CLI_DEFINE(handle_cli_iax2_show_stats, "Display IAX statistics"),
  13149. AST_CLI_DEFINE(handle_cli_iax2_show_threads, "Display IAX helper thread info"),
  13150. AST_CLI_DEFINE(handle_cli_iax2_show_users, "List defined IAX users"),
  13151. AST_CLI_DEFINE(handle_cli_iax2_test_losspct, "Set IAX2 incoming frame loss percentage"),
  13152. AST_CLI_DEFINE(handle_cli_iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry"),
  13153. AST_CLI_DEFINE(handle_cli_iax2_show_callno_limits, "Show current entries in IP call number limit table"),
  13154. #ifdef IAXTESTS
  13155. AST_CLI_DEFINE(handle_cli_iax2_test_jitter, "Simulates jitter for testing"),
  13156. AST_CLI_DEFINE(handle_cli_iax2_test_late, "Test the receipt of a late frame"),
  13157. AST_CLI_DEFINE(handle_cli_iax2_test_resync, "Test a resync in received timestamps"),
  13158. #endif /* IAXTESTS */
  13159. };
  13160. #ifdef TEST_FRAMEWORK
  13161. AST_TEST_DEFINE(test_iax2_peers_get)
  13162. {
  13163. struct ast_data_query query = {
  13164. .path = "/asterisk/channel/iax2/peers",
  13165. .search = "peers/peer/name=test_peer_data_provider"
  13166. };
  13167. struct ast_data *node;
  13168. struct iax2_peer *peer;
  13169. switch (cmd) {
  13170. case TEST_INIT:
  13171. info->name = "iax2_peers_get_data_test";
  13172. info->category = "/main/data/iax2/peers/";
  13173. info->summary = "IAX2 peers data providers unit test";
  13174. info->description =
  13175. "Tests whether the IAX2 peers data provider implementation works as expected.";
  13176. return AST_TEST_NOT_RUN;
  13177. case TEST_EXECUTE:
  13178. break;
  13179. }
  13180. /* build a test peer */
  13181. peer = build_peer("test_peer_data_provider", NULL, NULL, 0);
  13182. if (!peer) {
  13183. return AST_TEST_FAIL;
  13184. }
  13185. peer->expiry= 1010;
  13186. ao2_link(peers, peer);
  13187. node = ast_data_get(&query);
  13188. if (!node) {
  13189. ao2_unlink(peers, peer);
  13190. peer_unref(peer);
  13191. return AST_TEST_FAIL;
  13192. }
  13193. /* check returned data node. */
  13194. if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
  13195. ao2_unlink(peers, peer);
  13196. peer_unref(peer);
  13197. ast_data_free(node);
  13198. return AST_TEST_FAIL;
  13199. }
  13200. if (ast_data_retrieve_int(node, "peer/expiry") != 1010) {
  13201. ao2_unlink(peers, peer);
  13202. peer_unref(peer);
  13203. ast_data_free(node);
  13204. return AST_TEST_FAIL;
  13205. }
  13206. /* release resources */
  13207. ast_data_free(node);
  13208. ao2_unlink(peers, peer);
  13209. peer_unref(peer);
  13210. return AST_TEST_PASS;
  13211. }
  13212. AST_TEST_DEFINE(test_iax2_users_get)
  13213. {
  13214. struct ast_data_query query = {
  13215. .path = "/asterisk/channel/iax2/users",
  13216. .search = "users/user/name=test_user_data_provider"
  13217. };
  13218. struct ast_data *node;
  13219. struct iax2_user *user;
  13220. switch (cmd) {
  13221. case TEST_INIT:
  13222. info->name = "iax2_users_get_data_test";
  13223. info->category = "/main/data/iax2/users/";
  13224. info->summary = "IAX2 users data providers unit test";
  13225. info->description =
  13226. "Tests whether the IAX2 users data provider implementation works as expected.";
  13227. return AST_TEST_NOT_RUN;
  13228. case TEST_EXECUTE:
  13229. break;
  13230. }
  13231. user = build_user("test_user_data_provider", NULL, NULL, 0);
  13232. if (!user) {
  13233. ast_test_status_update(test, "Failed to build a test user\n");
  13234. return AST_TEST_FAIL;
  13235. }
  13236. user->amaflags = 1010;
  13237. ao2_link(users, user);
  13238. node = ast_data_get(&query);
  13239. if (!node) {
  13240. ast_test_status_update(test, "The data query to find our test user failed\n");
  13241. ao2_unlink(users, user);
  13242. user_unref(user);
  13243. return AST_TEST_FAIL;
  13244. }
  13245. if (strcmp(ast_data_retrieve_string(node, "user/name"), "test_user_data_provider")) {
  13246. ast_test_status_update(test, "Our data results did not return the test user created in the previous step.\n");
  13247. ao2_unlink(users, user);
  13248. user_unref(user);
  13249. ast_data_free(node);
  13250. return AST_TEST_FAIL;
  13251. }
  13252. if (ast_data_retrieve_int(node, "user/amaflags/value") != 1010) {
  13253. ast_test_status_update(test, "The amaflags field in our test user was '%d' not the expected value '1010'\n", ast_data_retrieve_int(node, "user/amaflags/value"));
  13254. ao2_unlink(users, user);
  13255. user_unref(user);
  13256. ast_data_free(node);
  13257. return AST_TEST_FAIL;
  13258. }
  13259. ast_data_free(node);
  13260. ao2_unlink(users, user);
  13261. user_unref(user);
  13262. return AST_TEST_PASS;
  13263. }
  13264. #endif
  13265. static void cleanup_thread_list(void *head)
  13266. {
  13267. AST_LIST_HEAD(iax2_thread_list, iax2_thread);
  13268. struct iax2_thread_list *list_head = head;
  13269. struct iax2_thread *thread;
  13270. AST_LIST_LOCK(list_head);
  13271. while ((thread = AST_LIST_REMOVE_HEAD(list_head, list))) {
  13272. pthread_t thread_id = thread->threadid;
  13273. thread->stop = 1;
  13274. signal_condition(&thread->lock, &thread->cond);
  13275. AST_LIST_UNLOCK(list_head);
  13276. pthread_join(thread_id, NULL);
  13277. AST_LIST_LOCK(list_head);
  13278. }
  13279. AST_LIST_UNLOCK(list_head);
  13280. }
  13281. static int __unload_module(void)
  13282. {
  13283. struct ast_context *con;
  13284. int x;
  13285. network_change_event_unsubscribe();
  13286. acl_change_event_unsubscribe();
  13287. ast_manager_unregister("IAXpeers");
  13288. ast_manager_unregister("IAXpeerlist");
  13289. ast_manager_unregister("IAXnetstats");
  13290. ast_manager_unregister("IAXregistry");
  13291. ast_unregister_application(papp);
  13292. ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
  13293. ast_unregister_switch(&iax2_switch);
  13294. ast_channel_unregister(&iax2_tech);
  13295. if (netthreadid != AST_PTHREADT_NULL) {
  13296. pthread_cancel(netthreadid);
  13297. pthread_kill(netthreadid, SIGURG);
  13298. pthread_join(netthreadid, NULL);
  13299. }
  13300. for (x = 0; x < ARRAY_LEN(iaxs); x++) {
  13301. if (iaxs[x]) {
  13302. iax2_destroy(x);
  13303. }
  13304. }
  13305. /* Call for all threads to halt */
  13306. cleanup_thread_list(&active_list);
  13307. cleanup_thread_list(&dynamic_list);
  13308. cleanup_thread_list(&idle_list);
  13309. ast_netsock_release(netsock);
  13310. ast_netsock_release(outsock);
  13311. for (x = 0; x < ARRAY_LEN(iaxs); x++) {
  13312. if (iaxs[x]) {
  13313. iax2_destroy(x);
  13314. }
  13315. }
  13316. ast_manager_unregister( "IAXpeers" );
  13317. ast_manager_unregister( "IAXpeerlist" );
  13318. ast_manager_unregister( "IAXnetstats" );
  13319. ast_manager_unregister( "IAXregistry" );
  13320. ast_unregister_application(papp);
  13321. #ifdef TEST_FRAMEWORK
  13322. AST_TEST_UNREGISTER(test_iax2_peers_get);
  13323. AST_TEST_UNREGISTER(test_iax2_users_get);
  13324. #endif
  13325. ast_data_unregister(NULL);
  13326. ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
  13327. ast_unregister_switch(&iax2_switch);
  13328. ast_channel_unregister(&iax2_tech);
  13329. delete_users();
  13330. iax_provision_unload();
  13331. reload_firmware(1);
  13332. for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
  13333. ast_mutex_destroy(&iaxsl[x]);
  13334. }
  13335. ao2_ref(peers, -1);
  13336. ao2_ref(users, -1);
  13337. ao2_ref(iax_peercallno_pvts, -1);
  13338. ao2_ref(iax_transfercallno_pvts, -1);
  13339. ao2_ref(callno_limits, -1);
  13340. ao2_ref(calltoken_ignores, -1);
  13341. if (timer) {
  13342. ast_timer_close(timer);
  13343. timer = NULL;
  13344. }
  13345. transmit_processor = ast_taskprocessor_unreference(transmit_processor);
  13346. ast_sched_clean_by_callback(sched, peercnt_remove_cb, peercnt_remove_cb);
  13347. ast_sched_clean_by_callback(sched, replace_callno, replace_callno);
  13348. ast_sched_context_destroy(sched);
  13349. sched = NULL;
  13350. ao2_ref(peercnts, -1);
  13351. ao2_ref(callno_pool, -1);
  13352. ao2_ref(callno_pool_trunk, -1);
  13353. con = ast_context_find(regcontext);
  13354. if (con)
  13355. ast_context_destroy(con, "IAX2");
  13356. ast_unload_realtime("iaxpeers");
  13357. iax2_tech.capabilities = ast_format_cap_destroy(iax2_tech.capabilities);
  13358. return 0;
  13359. }
  13360. static int unload_module(void)
  13361. {
  13362. ast_custom_function_unregister(&iaxpeer_function);
  13363. ast_custom_function_unregister(&iaxvar_function);
  13364. return __unload_module();
  13365. }
  13366. static int peer_set_sock_cb(void *obj, void *arg, int flags)
  13367. {
  13368. struct iax2_peer *peer = obj;
  13369. if (peer->sockfd < 0)
  13370. peer->sockfd = defaultsockfd;
  13371. return 0;
  13372. }
  13373. static int pvt_hash_cb(const void *obj, const int flags)
  13374. {
  13375. const struct chan_iax2_pvt *pvt = obj;
  13376. return pvt->peercallno;
  13377. }
  13378. static int pvt_cmp_cb(void *obj, void *arg, int flags)
  13379. {
  13380. struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
  13381. /* The frames_received field is used to hold whether we're matching
  13382. * against a full frame or not ... */
  13383. return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt,
  13384. pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
  13385. }
  13386. static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
  13387. {
  13388. const struct chan_iax2_pvt *pvt = obj;
  13389. return pvt->transfercallno;
  13390. }
  13391. static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
  13392. {
  13393. struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
  13394. /* The frames_received field is used to hold whether we're matching
  13395. * against a full frame or not ... */
  13396. return match(&pvt2->transfer, pvt2->transfercallno, pvt2->callno, pvt,
  13397. pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
  13398. }
  13399. static int load_objects(void)
  13400. {
  13401. peers = users = iax_peercallno_pvts = iax_transfercallno_pvts = NULL;
  13402. peercnts = callno_limits = calltoken_ignores = callno_pool = callno_pool_trunk = NULL;
  13403. if (!(peers = ao2_container_alloc(MAX_PEER_BUCKETS, peer_hash_cb, peer_cmp_cb))) {
  13404. goto container_fail;
  13405. } else if (!(users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_cb, user_cmp_cb))) {
  13406. goto container_fail;
  13407. } else if (!(iax_peercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, pvt_hash_cb, pvt_cmp_cb))) {
  13408. goto container_fail;
  13409. } else if (!(iax_transfercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, transfercallno_pvt_hash_cb, transfercallno_pvt_cmp_cb))) {
  13410. goto container_fail;
  13411. } else if (!(peercnts = ao2_container_alloc(MAX_PEER_BUCKETS, peercnt_hash_cb, peercnt_cmp_cb))) {
  13412. goto container_fail;
  13413. } else if (!(callno_limits = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
  13414. goto container_fail;
  13415. } else if (!(calltoken_ignores = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
  13416. goto container_fail;
  13417. } else if (create_callno_pools()) {
  13418. goto container_fail;
  13419. } else if (!(transmit_processor = ast_taskprocessor_get("iax2_transmit", TPS_REF_DEFAULT))) {
  13420. goto container_fail;
  13421. }
  13422. return 0;
  13423. container_fail:
  13424. if (peers) {
  13425. ao2_ref(peers, -1);
  13426. }
  13427. if (users) {
  13428. ao2_ref(users, -1);
  13429. }
  13430. if (iax_peercallno_pvts) {
  13431. ao2_ref(iax_peercallno_pvts, -1);
  13432. }
  13433. if (iax_transfercallno_pvts) {
  13434. ao2_ref(iax_transfercallno_pvts, -1);
  13435. }
  13436. if (peercnts) {
  13437. ao2_ref(peercnts, -1);
  13438. }
  13439. if (callno_limits) {
  13440. ao2_ref(callno_limits, -1);
  13441. }
  13442. if (calltoken_ignores) {
  13443. ao2_ref(calltoken_ignores, -1);
  13444. }
  13445. if (callno_pool) {
  13446. ao2_ref(callno_pool, -1);
  13447. }
  13448. if (callno_pool_trunk) {
  13449. ao2_ref(callno_pool_trunk, -1);
  13450. }
  13451. return AST_MODULE_LOAD_FAILURE;
  13452. }
  13453. #define DATA_EXPORT_IAX2_PEER(MEMBER) \
  13454. MEMBER(iax2_peer, name, AST_DATA_STRING) \
  13455. MEMBER(iax2_peer, username, AST_DATA_STRING) \
  13456. MEMBER(iax2_peer, secret, AST_DATA_PASSWORD) \
  13457. MEMBER(iax2_peer, dbsecret, AST_DATA_PASSWORD) \
  13458. MEMBER(iax2_peer, outkey, AST_DATA_STRING) \
  13459. MEMBER(iax2_peer, regexten, AST_DATA_STRING) \
  13460. MEMBER(iax2_peer, context, AST_DATA_STRING) \
  13461. MEMBER(iax2_peer, peercontext, AST_DATA_STRING) \
  13462. MEMBER(iax2_peer, mailbox, AST_DATA_STRING) \
  13463. MEMBER(iax2_peer, mohinterpret, AST_DATA_STRING) \
  13464. MEMBER(iax2_peer, mohsuggest, AST_DATA_STRING) \
  13465. MEMBER(iax2_peer, inkeys, AST_DATA_STRING) \
  13466. MEMBER(iax2_peer, cid_num, AST_DATA_STRING) \
  13467. MEMBER(iax2_peer, cid_name, AST_DATA_STRING) \
  13468. MEMBER(iax2_peer, zonetag, AST_DATA_STRING) \
  13469. MEMBER(iax2_peer, parkinglot, AST_DATA_STRING) \
  13470. MEMBER(iax2_peer, expiry, AST_DATA_SECONDS) \
  13471. MEMBER(iax2_peer, callno, AST_DATA_INTEGER) \
  13472. MEMBER(iax2_peer, lastms, AST_DATA_MILLISECONDS) \
  13473. MEMBER(iax2_peer, maxms, AST_DATA_MILLISECONDS) \
  13474. MEMBER(iax2_peer, pokefreqok, AST_DATA_MILLISECONDS) \
  13475. MEMBER(iax2_peer, pokefreqnotok, AST_DATA_MILLISECONDS) \
  13476. MEMBER(iax2_peer, historicms, AST_DATA_INTEGER) \
  13477. MEMBER(iax2_peer, smoothing, AST_DATA_BOOLEAN) \
  13478. MEMBER(iax2_peer, maxcallno, AST_DATA_INTEGER)
  13479. AST_DATA_STRUCTURE(iax2_peer, DATA_EXPORT_IAX2_PEER);
  13480. static int peers_data_provider_get(const struct ast_data_search *search,
  13481. struct ast_data *data_root)
  13482. {
  13483. struct ast_data *data_peer;
  13484. struct iax2_peer *peer;
  13485. struct ao2_iterator i;
  13486. char status[20];
  13487. struct ast_str *encmethods = ast_str_alloca(256);
  13488. i = ao2_iterator_init(peers, 0);
  13489. while ((peer = ao2_iterator_next(&i))) {
  13490. data_peer = ast_data_add_node(data_root, "peer");
  13491. if (!data_peer) {
  13492. peer_unref(peer);
  13493. continue;
  13494. }
  13495. ast_data_add_structure(iax2_peer, data_peer, peer);
  13496. iax2_data_add_codecs(data_peer, "codecs", peer->capability);
  13497. peer_status(peer, status, sizeof(status));
  13498. ast_data_add_str(data_peer, "status", status);
  13499. ast_data_add_str(data_peer, "host", ast_sockaddr_stringify_host(&peer->addr));
  13500. ast_data_add_str(data_peer, "mask", ast_inet_ntoa(peer->mask));
  13501. ast_data_add_int(data_peer, "port", ast_sockaddr_port(&peer->addr));
  13502. ast_data_add_bool(data_peer, "trunk", ast_test_flag64(peer, IAX_TRUNK));
  13503. ast_data_add_bool(data_peer, "dynamic", ast_test_flag64(peer, IAX_DYNAMIC));
  13504. encmethods_to_str(peer->encmethods, &encmethods);
  13505. ast_data_add_str(data_peer, "encryption", peer->encmethods ? ast_str_buffer(encmethods) : "no");
  13506. peer_unref(peer);
  13507. if (!ast_data_search_match(search, data_peer)) {
  13508. ast_data_remove_node(data_root, data_peer);
  13509. }
  13510. }
  13511. ao2_iterator_destroy(&i);
  13512. return 0;
  13513. }
  13514. #define DATA_EXPORT_IAX2_USER(MEMBER) \
  13515. MEMBER(iax2_user, name, AST_DATA_STRING) \
  13516. MEMBER(iax2_user, dbsecret, AST_DATA_PASSWORD) \
  13517. MEMBER(iax2_user, accountcode, AST_DATA_STRING) \
  13518. MEMBER(iax2_user, mohinterpret, AST_DATA_STRING) \
  13519. MEMBER(iax2_user, mohsuggest, AST_DATA_STRING) \
  13520. MEMBER(iax2_user, inkeys, AST_DATA_STRING) \
  13521. MEMBER(iax2_user, language, AST_DATA_STRING) \
  13522. MEMBER(iax2_user, cid_num, AST_DATA_STRING) \
  13523. MEMBER(iax2_user, cid_name, AST_DATA_STRING) \
  13524. MEMBER(iax2_user, parkinglot, AST_DATA_STRING) \
  13525. MEMBER(iax2_user, maxauthreq, AST_DATA_INTEGER) \
  13526. MEMBER(iax2_user, curauthreq, AST_DATA_INTEGER)
  13527. AST_DATA_STRUCTURE(iax2_user, DATA_EXPORT_IAX2_USER);
  13528. static int users_data_provider_get(const struct ast_data_search *search,
  13529. struct ast_data *data_root)
  13530. {
  13531. struct ast_data *data_user, *data_authmethods, *data_enum_node;
  13532. struct iax2_user *user;
  13533. struct ao2_iterator i;
  13534. char auth[90];
  13535. char *pstr = "";
  13536. i = ao2_iterator_init(users, 0);
  13537. for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
  13538. data_user = ast_data_add_node(data_root, "user");
  13539. if (!data_user) {
  13540. continue;
  13541. }
  13542. ast_data_add_structure(iax2_user, data_user, user);
  13543. iax2_data_add_codecs(data_user, "codecs", user->capability);
  13544. if (!ast_strlen_zero(user->secret)) {
  13545. ast_copy_string(auth, user->secret, sizeof(auth));
  13546. } else if (!ast_strlen_zero(user->inkeys)) {
  13547. snprintf(auth, sizeof(auth), "Key: %s", user->inkeys);
  13548. } else {
  13549. ast_copy_string(auth, "no secret", sizeof(auth));
  13550. }
  13551. ast_data_add_password(data_user, "secret", auth);
  13552. ast_data_add_str(data_user, "context", user->contexts ? user->contexts->context : DEFAULT_CONTEXT);
  13553. /* authmethods */
  13554. data_authmethods = ast_data_add_node(data_user, "authmethods");
  13555. if (!data_authmethods) {
  13556. ast_data_remove_node(data_root, data_user);
  13557. continue;
  13558. }
  13559. ast_data_add_bool(data_authmethods, "rsa", user->authmethods & IAX_AUTH_RSA);
  13560. ast_data_add_bool(data_authmethods, "md5", user->authmethods & IAX_AUTH_MD5);
  13561. ast_data_add_bool(data_authmethods, "plaintext", user->authmethods & IAX_AUTH_PLAINTEXT);
  13562. /* amaflags */
  13563. data_enum_node = ast_data_add_node(data_user, "amaflags");
  13564. if (!data_enum_node) {
  13565. ast_data_remove_node(data_root, data_user);
  13566. continue;
  13567. }
  13568. ast_data_add_int(data_enum_node, "value", user->amaflags);
  13569. ast_data_add_str(data_enum_node, "text", ast_cdr_flags2str(user->amaflags));
  13570. ast_data_add_bool(data_user, "access-control", ast_acl_list_is_empty(user->acl) ? 0 : 1);
  13571. if (ast_test_flag64(user, IAX_CODEC_NOCAP)) {
  13572. pstr = "REQ only";
  13573. } else if (ast_test_flag64(user, IAX_CODEC_NOPREFS)) {
  13574. pstr = "disabled";
  13575. } else {
  13576. pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "caller" : "host";
  13577. }
  13578. ast_data_add_str(data_user, "codec-preferences", pstr);
  13579. if (!ast_data_search_match(search, data_user)) {
  13580. ast_data_remove_node(data_root, data_user);
  13581. }
  13582. }
  13583. ao2_iterator_destroy(&i);
  13584. return 0;
  13585. }
  13586. static const struct ast_data_handler peers_data_provider = {
  13587. .version = AST_DATA_HANDLER_VERSION,
  13588. .get = peers_data_provider_get
  13589. };
  13590. static const struct ast_data_handler users_data_provider = {
  13591. .version = AST_DATA_HANDLER_VERSION,
  13592. .get = users_data_provider_get
  13593. };
  13594. static const struct ast_data_entry iax2_data_providers[] = {
  13595. AST_DATA_ENTRY("asterisk/channel/iax2/peers", &peers_data_provider),
  13596. AST_DATA_ENTRY("asterisk/channel/iax2/users", &users_data_provider),
  13597. };
  13598. /*! \brief Load IAX2 module, load configuraiton ---*/
  13599. static int load_module(void)
  13600. {
  13601. static const char config[] = "iax.conf";
  13602. int x = 0;
  13603. struct iax2_registry *reg = NULL;
  13604. if (!(iax2_tech.capabilities = ast_format_cap_alloc())) {
  13605. return AST_MODULE_LOAD_FAILURE;
  13606. }
  13607. ast_format_cap_add_all(iax2_tech.capabilities);
  13608. if (load_objects()) {
  13609. return AST_MODULE_LOAD_FAILURE;
  13610. }
  13611. memset(iaxs, 0, sizeof(iaxs));
  13612. for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
  13613. ast_mutex_init(&iaxsl[x]);
  13614. }
  13615. if (!(sched = ast_sched_context_create())) {
  13616. ast_log(LOG_ERROR, "Failed to create scheduler thread\n");
  13617. return AST_MODULE_LOAD_FAILURE;
  13618. }
  13619. if (ast_sched_start_thread(sched)) {
  13620. ast_sched_context_destroy(sched);
  13621. sched = NULL;
  13622. return AST_MODULE_LOAD_FAILURE;
  13623. }
  13624. if (!(io = io_context_create())) {
  13625. ast_log(LOG_ERROR, "Failed to create I/O context\n");
  13626. ast_sched_context_destroy(sched);
  13627. sched = NULL;
  13628. return AST_MODULE_LOAD_FAILURE;
  13629. }
  13630. if (!(netsock = ast_netsock_list_alloc())) {
  13631. ast_log(LOG_ERROR, "Failed to create netsock list\n");
  13632. io_context_destroy(io);
  13633. ast_sched_context_destroy(sched);
  13634. sched = NULL;
  13635. return AST_MODULE_LOAD_FAILURE;
  13636. }
  13637. ast_netsock_init(netsock);
  13638. outsock = ast_netsock_list_alloc();
  13639. if (!outsock) {
  13640. ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
  13641. io_context_destroy(io);
  13642. ast_sched_context_destroy(sched);
  13643. sched = NULL;
  13644. return AST_MODULE_LOAD_FAILURE;
  13645. }
  13646. ast_netsock_init(outsock);
  13647. randomcalltokendata = ast_random();
  13648. iax_set_output(iax_debug_output);
  13649. iax_set_error(iax_error_output);
  13650. jb_setoutput(jb_error_output, jb_warning_output, NULL);
  13651. if ((timer = ast_timer_open())) {
  13652. ast_timer_set_rate(timer, 1000 / trunkfreq);
  13653. }
  13654. if (set_config(config, 0, 0) == -1) {
  13655. if (timer) {
  13656. ast_timer_close(timer);
  13657. timer = NULL;
  13658. }
  13659. return AST_MODULE_LOAD_DECLINE;
  13660. }
  13661. #ifdef TEST_FRAMEWORK
  13662. AST_TEST_REGISTER(test_iax2_peers_get);
  13663. AST_TEST_REGISTER(test_iax2_users_get);
  13664. #endif
  13665. /* Register AstData providers */
  13666. ast_data_register_multiple(iax2_data_providers, ARRAY_LEN(iax2_data_providers));
  13667. ast_cli_register_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
  13668. ast_register_application_xml(papp, iax2_prov_app);
  13669. ast_custom_function_register(&iaxpeer_function);
  13670. ast_custom_function_register(&iaxvar_function);
  13671. ast_manager_register_xml("IAXpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peers);
  13672. ast_manager_register_xml("IAXpeerlist", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peer_list);
  13673. ast_manager_register_xml("IAXnetstats", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_netstats);
  13674. ast_manager_register_xml("IAXregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_registry);
  13675. if (ast_channel_register(&iax2_tech)) {
  13676. ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
  13677. __unload_module();
  13678. return AST_MODULE_LOAD_FAILURE;
  13679. }
  13680. if (ast_register_switch(&iax2_switch)) {
  13681. ast_log(LOG_ERROR, "Unable to register IAX switch\n");
  13682. }
  13683. if (start_network_thread()) {
  13684. ast_log(LOG_ERROR, "Unable to start network thread\n");
  13685. __unload_module();
  13686. return AST_MODULE_LOAD_FAILURE;
  13687. } else {
  13688. ast_verb(2, "IAX Ready and Listening\n");
  13689. }
  13690. AST_LIST_LOCK(&registrations);
  13691. AST_LIST_TRAVERSE(&registrations, reg, entry)
  13692. iax2_do_register(reg);
  13693. AST_LIST_UNLOCK(&registrations);
  13694. ao2_callback(peers, 0, peer_set_sock_cb, NULL);
  13695. ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
  13696. reload_firmware(0);
  13697. iax_provision_reload(0);
  13698. ast_realtime_require_field("iaxpeers", "name", RQ_CHAR, 10, "ipaddr", RQ_CHAR, 15, "port", RQ_UINTEGER2, 5, "regseconds", RQ_UINTEGER2, 6, SENTINEL);
  13699. network_change_event_subscribe();
  13700. return AST_MODULE_LOAD_SUCCESS;
  13701. }
  13702. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Inter Asterisk eXchange (Ver 2)",
  13703. .load = load_module,
  13704. .unload = unload_module,
  13705. .reload = reload,
  13706. .load_pri = AST_MODPRI_CHANNEL_DRIVER,
  13707. .nonoptreq = "res_crypto",
  13708. );