chan_iax2.c 435 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693
  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. /*** MODULEINFO
  31. <use>dahdi</use>
  32. <use>crypto</use>
  33. ***/
  34. #include "asterisk.h"
  35. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  36. #include <sys/mman.h>
  37. #include <dirent.h>
  38. #include <sys/socket.h>
  39. #include <netinet/in.h>
  40. #include <arpa/inet.h>
  41. #include <netinet/in_systm.h>
  42. #include <netinet/ip.h>
  43. #include <sys/time.h>
  44. #include <sys/signal.h>
  45. #include <signal.h>
  46. #include <strings.h>
  47. #include <netdb.h>
  48. #include <fcntl.h>
  49. #include <sys/stat.h>
  50. #include <regex.h>
  51. #include <sys/ioctl.h>
  52. #if defined(HAVE_DAHDI)
  53. #include <dahdi/user.h>
  54. #endif
  55. #include "asterisk/paths.h" /* need ast_config_AST_DATA_DIR for firmware */
  56. #include "asterisk/lock.h"
  57. #include "asterisk/frame.h"
  58. #include "asterisk/channel.h"
  59. #include "asterisk/module.h"
  60. #include "asterisk/pbx.h"
  61. #include "asterisk/sched.h"
  62. #include "asterisk/io.h"
  63. #include "asterisk/config.h"
  64. #include "asterisk/cli.h"
  65. #include "asterisk/translate.h"
  66. #include "asterisk/md5.h"
  67. #include "asterisk/cdr.h"
  68. #include "asterisk/crypto.h"
  69. #include "asterisk/acl.h"
  70. #include "asterisk/manager.h"
  71. #include "asterisk/callerid.h"
  72. #include "asterisk/app.h"
  73. #include "asterisk/astdb.h"
  74. #include "asterisk/musiconhold.h"
  75. #include "asterisk/features.h"
  76. #include "asterisk/utils.h"
  77. #include "asterisk/causes.h"
  78. #include "asterisk/localtime.h"
  79. #include "asterisk/aes.h"
  80. #include "asterisk/dnsmgr.h"
  81. #include "asterisk/devicestate.h"
  82. #include "asterisk/netsock.h"
  83. #include "asterisk/stringfields.h"
  84. #include "asterisk/linkedlists.h"
  85. #include "asterisk/event.h"
  86. #include "asterisk/astobj2.h"
  87. #include "iax2.h"
  88. #include "iax2-parser.h"
  89. #include "iax2-provision.h"
  90. #include "jitterbuf.h"
  91. /* Define SCHED_MULTITHREADED to run the scheduler in a special
  92. multithreaded mode. */
  93. #define SCHED_MULTITHREADED
  94. /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
  95. thread is actually doing. */
  96. #define DEBUG_SCHED_MULTITHREAD
  97. #ifdef SO_NO_CHECK
  98. static int nochecksums = 0;
  99. #endif
  100. #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
  101. #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
  102. #define DEFAULT_THREAD_COUNT 10
  103. #define DEFAULT_MAX_THREAD_COUNT 100
  104. #define DEFAULT_RETRY_TIME 1000
  105. #define MEMORY_SIZE 100
  106. #define DEFAULT_DROP 3
  107. #define DEBUG_SUPPORT
  108. #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
  109. /* Sample over last 100 units to determine historic jitter */
  110. #define GAMMA (0.01)
  111. static struct ast_codec_pref prefs;
  112. static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
  113. /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
  114. fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
  115. #define MAX_TRUNK_MTU 1240
  116. static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
  117. static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
  118. static char context[80] = "default";
  119. static char language[MAX_LANGUAGE] = "";
  120. static char regcontext[AST_MAX_CONTEXT] = "";
  121. static int maxauthreq = 3;
  122. static int max_retries = 4;
  123. static int ping_time = 21;
  124. static int lagrq_time = 10;
  125. static int maxjitterbuffer=1000;
  126. static int resyncthreshold=1000;
  127. static int maxjitterinterps=10;
  128. static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
  129. #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
  130. static int trunkfreq = 20;
  131. static int trunkmaxsize = MAX_TRUNKDATA;
  132. static int authdebug = 1;
  133. static int autokill = 0;
  134. static int iaxcompat = 0;
  135. static int last_authmethod = 0;
  136. static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
  137. static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
  138. static unsigned int tos = 0;
  139. static unsigned int cos = 0;
  140. static int min_reg_expire;
  141. static int max_reg_expire;
  142. static int srvlookup = 0;
  143. static int timingfd = -1; /* Timing file descriptor */
  144. static struct ast_netsock_list *netsock;
  145. static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
  146. static int defaultsockfd = -1;
  147. int (*iax2_regfunk)(const char *username, int onoff) = NULL;
  148. /* Ethernet, etc */
  149. #define IAX_CAPABILITY_FULLBANDWIDTH (0xFFFF & ~AST_FORMAT_AUDIO_UNDEFINED)
  150. /* T1, maybe ISDN */
  151. #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
  152. ~AST_FORMAT_SLINEAR & \
  153. ~AST_FORMAT_SLINEAR16 & \
  154. ~AST_FORMAT_ULAW & \
  155. ~AST_FORMAT_ALAW & \
  156. ~AST_FORMAT_G722)
  157. /* A modem */
  158. #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
  159. ~AST_FORMAT_G726 & \
  160. ~AST_FORMAT_G726_AAL2 & \
  161. ~AST_FORMAT_ADPCM)
  162. #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
  163. ~AST_FORMAT_G723_1)
  164. #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
  165. #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
  166. #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
  167. static struct io_context *io;
  168. static struct sched_context *sched;
  169. static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
  170. static int iaxdebug = 0;
  171. static int iaxtrunkdebug = 0;
  172. static int test_losspct = 0;
  173. #ifdef IAXTESTS
  174. static int test_late = 0;
  175. static int test_resync = 0;
  176. static int test_jit = 0;
  177. static int test_jitpct = 0;
  178. #endif /* IAXTESTS */
  179. static char accountcode[AST_MAX_ACCOUNT_CODE];
  180. static char mohinterpret[MAX_MUSICCLASS];
  181. static char mohsuggest[MAX_MUSICCLASS];
  182. static int amaflags = 0;
  183. static int adsi = 0;
  184. static int delayreject = 0;
  185. static int iax2_encryption = 0;
  186. static struct ast_flags globalflags = { 0 };
  187. static pthread_t netthreadid = AST_PTHREADT_NULL;
  188. static pthread_t schedthreadid = AST_PTHREADT_NULL;
  189. AST_MUTEX_DEFINE_STATIC(sched_lock);
  190. static ast_cond_t sched_cond;
  191. enum iax2_state {
  192. IAX_STATE_STARTED = (1 << 0),
  193. IAX_STATE_AUTHENTICATED = (1 << 1),
  194. IAX_STATE_TBD = (1 << 2),
  195. };
  196. struct iax2_context {
  197. char context[AST_MAX_CONTEXT];
  198. struct iax2_context *next;
  199. };
  200. enum iax2_flags {
  201. IAX_HASCALLERID = (1 << 0), /*!< CallerID has been specified */
  202. IAX_DELME = (1 << 1), /*!< Needs to be deleted */
  203. IAX_TEMPONLY = (1 << 2), /*!< Temporary (realtime) */
  204. IAX_TRUNK = (1 << 3), /*!< Treat as a trunk */
  205. IAX_NOTRANSFER = (1 << 4), /*!< Don't native bridge */
  206. IAX_USEJITTERBUF = (1 << 5), /*!< Use jitter buffer */
  207. IAX_DYNAMIC = (1 << 6), /*!< dynamic peer */
  208. IAX_SENDANI = (1 << 7), /*!< Send ANI along with CallerID */
  209. /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
  210. IAX_ALREADYGONE = (1 << 9), /*!< Already disconnected */
  211. IAX_PROVISION = (1 << 10), /*!< This is a provisioning request */
  212. IAX_QUELCH = (1 << 11), /*!< Whether or not we quelch audio */
  213. IAX_ENCRYPTED = (1 << 12), /*!< Whether we should assume encrypted tx/rx */
  214. IAX_KEYPOPULATED = (1 << 13), /*!< Whether we have a key populated */
  215. IAX_CODEC_USER_FIRST = (1 << 14), /*!< are we willing to let the other guy choose the codec? */
  216. IAX_CODEC_NOPREFS = (1 << 15), /*!< Force old behaviour by turning off prefs */
  217. IAX_CODEC_NOCAP = (1 << 16), /*!< only consider requested format and ignore capabilities*/
  218. IAX_RTCACHEFRIENDS = (1 << 17), /*!< let realtime stay till your reload */
  219. IAX_RTUPDATE = (1 << 18), /*!< Send a realtime update */
  220. IAX_RTAUTOCLEAR = (1 << 19), /*!< erase me on expire */
  221. IAX_FORCEJITTERBUF = (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
  222. IAX_RTIGNOREREGEXPIRE = (1 << 21), /*!< When using realtime, ignore registration expiration */
  223. IAX_TRUNKTIMESTAMPS = (1 << 22), /*!< Send trunk timestamps */
  224. IAX_TRANSFERMEDIA = (1 << 23), /*!< When doing IAX2 transfers, transfer media only */
  225. IAX_MAXAUTHREQ = (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */
  226. IAX_DELAYPBXSTART = (1 << 25), /*!< Don't start a PBX on the channel until the peer sends us a
  227. response, so that we've achieved a three-way handshake with
  228. them before sending voice or anything else*/
  229. IAX_ALLOWFWDOWNLOAD = (1 << 26), /*!< Allow the FWDOWNL command? */
  230. IAX_SHRINKCALLERID = (1 << 27), /*!< Turn on and off caller id shrinking */
  231. };
  232. static int global_rtautoclear = 120;
  233. static int reload_config(void);
  234. /*!
  235. * \brief Call token validation settings.
  236. */
  237. enum calltoken_peer_enum {
  238. /*! \brief Default calltoken required unless the ip is in the ignorelist */
  239. CALLTOKEN_DEFAULT = 0,
  240. /*! \brief Require call token validation. */
  241. CALLTOKEN_YES = 1,
  242. /*! \brief Require call token validation after a successful registration
  243. * using call token validation occurs. */
  244. CALLTOKEN_AUTO = 2,
  245. /*! \brief Do not require call token validation. */
  246. CALLTOKEN_NO = 3,
  247. };
  248. struct iax2_user {
  249. AST_DECLARE_STRING_FIELDS(
  250. AST_STRING_FIELD(name);
  251. AST_STRING_FIELD(secret);
  252. AST_STRING_FIELD(dbsecret);
  253. AST_STRING_FIELD(accountcode);
  254. AST_STRING_FIELD(mohinterpret);
  255. AST_STRING_FIELD(mohsuggest);
  256. AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
  257. AST_STRING_FIELD(language);
  258. AST_STRING_FIELD(cid_num);
  259. AST_STRING_FIELD(cid_name);
  260. );
  261. int authmethods;
  262. int encmethods;
  263. int amaflags;
  264. int adsi;
  265. unsigned int flags;
  266. int capability;
  267. int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
  268. int curauthreq; /*!< Current number of outstanding AUTHREQs */
  269. struct ast_codec_pref prefs;
  270. struct ast_ha *ha;
  271. struct iax2_context *contexts;
  272. struct ast_variable *vars;
  273. enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
  274. };
  275. struct iax2_peer {
  276. AST_DECLARE_STRING_FIELDS(
  277. AST_STRING_FIELD(name);
  278. AST_STRING_FIELD(username);
  279. AST_STRING_FIELD(secret);
  280. AST_STRING_FIELD(dbsecret);
  281. AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
  282. AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
  283. AST_STRING_FIELD(context); /*!< For transfers only */
  284. AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
  285. AST_STRING_FIELD(mailbox); /*!< Mailbox */
  286. AST_STRING_FIELD(mohinterpret);
  287. AST_STRING_FIELD(mohsuggest);
  288. AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
  289. /* Suggested caller id if registering */
  290. AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
  291. AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
  292. AST_STRING_FIELD(zonetag); /*!< Time Zone */
  293. );
  294. struct ast_codec_pref prefs;
  295. struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
  296. struct sockaddr_in addr;
  297. int formats;
  298. int sockfd; /*!< Socket to use for transmission */
  299. struct in_addr mask;
  300. int adsi;
  301. unsigned int flags;
  302. /* Dynamic Registration fields */
  303. struct sockaddr_in defaddr; /*!< Default address if there is one */
  304. int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
  305. int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
  306. int expire; /*!< Schedule entry for expiry */
  307. int expiry; /*!< How soon to expire */
  308. int capability; /*!< Capability */
  309. /* Qualification */
  310. int callno; /*!< Call number of POKE request */
  311. int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
  312. int lastms; /*!< How long last response took (in ms), or -1 for no response */
  313. int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
  314. int pokefreqok; /*!< How often to check if the host is up */
  315. int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
  316. int historicms; /*!< How long recent average responses took */
  317. int smoothing; /*!< Sample over how many units to determine historic ms */
  318. uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
  319. struct ast_event_sub *mwi_event_sub;
  320. struct ast_ha *ha;
  321. enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
  322. };
  323. #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
  324. struct iax2_trunk_peer {
  325. ast_mutex_t lock;
  326. int sockfd;
  327. struct sockaddr_in addr;
  328. struct timeval txtrunktime; /*!< Transmit trunktime */
  329. struct timeval rxtrunktime; /*!< Receive trunktime */
  330. struct timeval lasttxtime; /*!< Last transmitted trunktime */
  331. struct timeval trunkact; /*!< Last trunk activity */
  332. unsigned int lastsent; /*!< Last sent time */
  333. /* Trunk data and length */
  334. unsigned char *trunkdata;
  335. unsigned int trunkdatalen;
  336. unsigned int trunkdataalloc;
  337. int trunkmaxmtu;
  338. int trunkerror;
  339. int calls;
  340. AST_LIST_ENTRY(iax2_trunk_peer) list;
  341. };
  342. static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
  343. struct iax_firmware {
  344. AST_LIST_ENTRY(iax_firmware) list;
  345. int fd;
  346. int mmaplen;
  347. int dead;
  348. struct ast_iax2_firmware_header *fwh;
  349. unsigned char *buf;
  350. };
  351. enum iax_reg_state {
  352. REG_STATE_UNREGISTERED = 0,
  353. REG_STATE_REGSENT,
  354. REG_STATE_AUTHSENT,
  355. REG_STATE_REGISTERED,
  356. REG_STATE_REJECTED,
  357. REG_STATE_TIMEOUT,
  358. REG_STATE_NOAUTH
  359. };
  360. enum iax_transfer_state {
  361. TRANSFER_NONE = 0,
  362. TRANSFER_BEGIN,
  363. TRANSFER_READY,
  364. TRANSFER_RELEASED,
  365. TRANSFER_PASSTHROUGH,
  366. TRANSFER_MBEGIN,
  367. TRANSFER_MREADY,
  368. TRANSFER_MRELEASED,
  369. TRANSFER_MPASSTHROUGH,
  370. TRANSFER_MEDIA,
  371. TRANSFER_MEDIAPASS
  372. };
  373. struct iax2_registry {
  374. struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
  375. char username[80];
  376. char secret[80]; /*!< Password or key name in []'s */
  377. int expire; /*!< Sched ID of expiration */
  378. int refresh; /*!< How often to refresh */
  379. enum iax_reg_state regstate;
  380. int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
  381. int callno; /*!< Associated call number if applicable */
  382. struct sockaddr_in us; /*!< Who the server thinks we are */
  383. struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
  384. AST_LIST_ENTRY(iax2_registry) entry;
  385. };
  386. static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
  387. /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
  388. #define MIN_RETRY_TIME 100
  389. #define MAX_RETRY_TIME 10000
  390. #define MAX_JITTER_BUFFER 50
  391. #define MIN_JITTER_BUFFER 10
  392. #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
  393. #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
  394. /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
  395. #define TS_GAP_FOR_JB_RESYNC 5000
  396. /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
  397. #define MARK_IAX_SUBCLASS_TX 0x8000
  398. static int iaxthreadcount = DEFAULT_THREAD_COUNT;
  399. static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
  400. static int iaxdynamicthreadcount = 0;
  401. static int iaxdynamicthreadnum = 0;
  402. static int iaxactivethreadcount = 0;
  403. struct iax_rr {
  404. int jitter;
  405. int losspct;
  406. int losscnt;
  407. int packets;
  408. int delay;
  409. int dropped;
  410. int ooo;
  411. };
  412. struct iax2_pvt_ref;
  413. struct chan_iax2_pvt {
  414. /*! Socket to send/receive on for this call */
  415. int sockfd;
  416. /*! Last received voice format */
  417. int voiceformat;
  418. /*! Last received video format */
  419. int videoformat;
  420. /*! Last sent voice format */
  421. int svoiceformat;
  422. /*! Last sent video format */
  423. int svideoformat;
  424. /*! What we are capable of sending */
  425. int capability;
  426. /*! Last received timestamp */
  427. unsigned int last;
  428. /*! Last sent timestamp - never send the same timestamp twice in a single call */
  429. unsigned int lastsent;
  430. /*! Timestamp of the last video frame sent */
  431. unsigned int lastvsent;
  432. /*! Next outgoing timestamp if everything is good */
  433. unsigned int nextpred;
  434. /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
  435. int first_iax_message;
  436. /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
  437. int last_iax_message;
  438. /*! True if the last voice we transmitted was not silence/CNG */
  439. unsigned int notsilenttx:1;
  440. /*! Ping time */
  441. unsigned int pingtime;
  442. /*! Max time for initial response */
  443. int maxtime;
  444. /*! Peer Address */
  445. struct sockaddr_in addr;
  446. /*! Actual used codec preferences */
  447. struct ast_codec_pref prefs;
  448. /*! Requested codec preferences */
  449. struct ast_codec_pref rprefs;
  450. /*! Our call number */
  451. unsigned short callno;
  452. /*! Our callno_entry entry */
  453. struct callno_entry *callno_entry;
  454. /*! Peer callno */
  455. unsigned short peercallno;
  456. /*! Negotiated format, this is only used to remember what format was
  457. chosen for an unauthenticated call so that the channel can get
  458. created later using the right format */
  459. int chosenformat;
  460. /*! Peer selected format */
  461. int peerformat;
  462. /*! Peer capability */
  463. int peercapability;
  464. /*! timeval that we base our transmission on */
  465. struct timeval offset;
  466. /*! timeval that we base our delivery on */
  467. struct timeval rxcore;
  468. /*! The jitterbuffer */
  469. jitterbuf *jb;
  470. /*! active jb read scheduler id */
  471. int jbid;
  472. /*! LAG */
  473. int lag;
  474. /*! Error, as discovered by the manager */
  475. int error;
  476. /*! Owner if we have one */
  477. struct ast_channel *owner;
  478. /*! What's our state? */
  479. struct ast_flags state;
  480. /*! Expiry (optional) */
  481. int expiry;
  482. /*! Next outgoing sequence number */
  483. unsigned char oseqno;
  484. /*! Next sequence number they have not yet acknowledged */
  485. unsigned char rseqno;
  486. /*! Next incoming sequence number */
  487. unsigned char iseqno;
  488. /*! Last incoming sequence number we have acknowledged */
  489. unsigned char aseqno;
  490. AST_DECLARE_STRING_FIELDS(
  491. /*! Peer name */
  492. AST_STRING_FIELD(peer);
  493. /*! Default Context */
  494. AST_STRING_FIELD(context);
  495. /*! Caller ID if available */
  496. AST_STRING_FIELD(cid_num);
  497. AST_STRING_FIELD(cid_name);
  498. /*! Hidden Caller ID (i.e. ANI) if appropriate */
  499. AST_STRING_FIELD(ani);
  500. /*! DNID */
  501. AST_STRING_FIELD(dnid);
  502. /*! RDNIS */
  503. AST_STRING_FIELD(rdnis);
  504. /*! Requested Extension */
  505. AST_STRING_FIELD(exten);
  506. /*! Expected Username */
  507. AST_STRING_FIELD(username);
  508. /*! Expected Secret */
  509. AST_STRING_FIELD(secret);
  510. /*! MD5 challenge */
  511. AST_STRING_FIELD(challenge);
  512. /*! Public keys permitted keys for incoming authentication */
  513. AST_STRING_FIELD(inkeys);
  514. /*! Private key for outgoing authentication */
  515. AST_STRING_FIELD(outkey);
  516. /*! Preferred language */
  517. AST_STRING_FIELD(language);
  518. /*! Hostname/peername for naming purposes */
  519. AST_STRING_FIELD(host);
  520. AST_STRING_FIELD(dproot);
  521. AST_STRING_FIELD(accountcode);
  522. AST_STRING_FIELD(mohinterpret);
  523. AST_STRING_FIELD(mohsuggest);
  524. /*! received OSP token */
  525. AST_STRING_FIELD(osptoken);
  526. );
  527. /*! AUTHREJ all AUTHREP frames */
  528. int authrej;
  529. /*! permitted authentication methods */
  530. int authmethods;
  531. /*! permitted encryption methods */
  532. int encmethods;
  533. /*! Encryption AES-128 Key */
  534. ast_aes_encrypt_key ecx;
  535. /*! Decryption AES-128 Key corresponding to ecx */
  536. ast_aes_decrypt_key mydcx;
  537. /*! Decryption AES-128 Key used to decrypt peer frames */
  538. ast_aes_decrypt_key dcx;
  539. /*! 32 bytes of semi-random data */
  540. unsigned char semirand[32];
  541. /*! Associated registry */
  542. struct iax2_registry *reg;
  543. /*! Associated peer for poking */
  544. struct iax2_peer *peerpoke;
  545. /*! IAX_ flags */
  546. unsigned int flags;
  547. int adsi;
  548. /*! Transferring status */
  549. enum iax_transfer_state transferring;
  550. /*! Transfer identifier */
  551. int transferid;
  552. /*! Who we are IAX transferring to */
  553. struct sockaddr_in transfer;
  554. /*! What's the new call number for the transfer */
  555. unsigned short transfercallno;
  556. /*! Transfer encrypt AES-128 Key */
  557. ast_aes_encrypt_key tdcx;
  558. /*! Status of knowledge of peer ADSI capability */
  559. int peeradsicpe;
  560. /*! Who we are bridged to */
  561. unsigned short bridgecallno;
  562. int pingid; /*!< Transmit PING request */
  563. int lagid; /*!< Retransmit lag request */
  564. int autoid; /*!< Auto hangup for Dialplan requestor */
  565. int authid; /*!< Authentication rejection ID */
  566. int authfail; /*!< Reason to report failure */
  567. int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
  568. int calling_ton;
  569. int calling_tns;
  570. int calling_pres;
  571. int amaflags;
  572. AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
  573. /*! variables inherited from the user definition */
  574. struct ast_variable *vars;
  575. /*! variables transmitted in a NEW packet */
  576. struct ast_variable *iaxvars;
  577. /*! last received remote rr */
  578. struct iax_rr remote_rr;
  579. /*! Current base time: (just for stats) */
  580. int min;
  581. /*! Dropped frame count: (just for stats) */
  582. int frames_dropped;
  583. /*! received frame count: (just for stats) */
  584. int frames_received;
  585. /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
  586. unsigned char calltoken_ie_len;
  587. /*! hold all signaling frames from the pbx thread until we have a destination callno */
  588. char hold_signaling;
  589. /*! frame queue for signaling frames from pbx thread waiting for destination callno */
  590. AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
  591. };
  592. struct signaling_queue_entry {
  593. struct ast_frame f;
  594. AST_LIST_ENTRY(signaling_queue_entry) next;
  595. };
  596. /*! table of available call numbers */
  597. static struct ao2_container *callno_pool;
  598. /*! table of available trunk call numbers */
  599. static struct ao2_container *callno_pool_trunk;
  600. static const unsigned int CALLNO_POOL_BUCKETS = 2699;
  601. /*!
  602. * \brief a list of frames that may need to be retransmitted
  603. *
  604. * \note The contents of this list do not need to be explicitly destroyed
  605. * on module unload. This is because all active calls are destroyed, and
  606. * all frames in this queue will get destroyed as a part of that process.
  607. */
  608. static AST_LIST_HEAD_STATIC(frame_queue, iax_frame);
  609. static int randomcalltokendata;
  610. static const time_t MAX_CALLTOKEN_DELAY = 10;
  611. /*!
  612. * This module will get much higher performance when doing a lot of
  613. * user and peer lookups if the number of buckets is increased from 1.
  614. * However, to maintain old behavior for Asterisk 1.4, these are set to
  615. * 1 by default. When using multiple buckets, search order through these
  616. * containers is considered random, so you will not be able to depend on
  617. * the order the entires are specified in iax.conf for matching order. */
  618. #ifdef LOW_MEMORY
  619. #define MAX_PEER_BUCKETS 17
  620. #else
  621. #define MAX_PEER_BUCKETS 563
  622. #endif
  623. static struct ao2_container *peers;
  624. #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
  625. static struct ao2_container *users;
  626. /*! Table containing peercnt objects for every ip address consuming a callno */
  627. static struct ao2_container *peercnts;
  628. /*! Table containing custom callno limit rules for a range of ip addresses. */
  629. static struct ao2_container *callno_limits;
  630. /*! Table containing ip addresses not requiring calltoken validation */
  631. static struct ao2_container *calltoken_ignores;
  632. static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
  633. static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
  634. static uint16_t global_maxcallno;
  635. /*! Total num of call numbers allowed to be allocated without calltoken validation */
  636. static uint16_t global_maxcallno_nonval;
  637. static uint16_t total_nonval_callno_used = 0;
  638. /*! peer connection private, keeps track of all the call numbers
  639. * consumed by a single ip address */
  640. struct peercnt {
  641. /*! ip address consuming call numbers */
  642. unsigned long addr;
  643. /*! Number of call numbers currently used by this ip address */
  644. uint16_t cur;
  645. /*! Max call numbers allowed for this ip address */
  646. uint16_t limit;
  647. /*! Specifies whether limit is set by a registration or not, if so normal
  648. * limit setting rules do not apply to this address. */
  649. unsigned char reg;
  650. };
  651. /*! used by both callno_limits and calltoken_ignores containers */
  652. struct addr_range {
  653. /*! ip address range for custom callno limit rule */
  654. struct ast_ha ha;
  655. /*! callno limit for this ip address range, only used in callno_limits container */
  656. uint16_t limit;
  657. /*! delete me marker for reloads */
  658. unsigned char delme;
  659. };
  660. struct callno_entry {
  661. /*! callno used for this entry */
  662. uint16_t callno;
  663. /*! was this callno calltoken validated or not */
  664. unsigned char validated;
  665. };
  666. static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
  667. enum {
  668. /*! Extension exists */
  669. CACHE_FLAG_EXISTS = (1 << 0),
  670. /*! Extension is nonexistent */
  671. CACHE_FLAG_NONEXISTENT = (1 << 1),
  672. /*! Extension can exist */
  673. CACHE_FLAG_CANEXIST = (1 << 2),
  674. /*! Waiting to hear back response */
  675. CACHE_FLAG_PENDING = (1 << 3),
  676. /*! Timed out */
  677. CACHE_FLAG_TIMEOUT = (1 << 4),
  678. /*! Request transmitted */
  679. CACHE_FLAG_TRANSMITTED = (1 << 5),
  680. /*! Timeout */
  681. CACHE_FLAG_UNKNOWN = (1 << 6),
  682. /*! Matchmore */
  683. CACHE_FLAG_MATCHMORE = (1 << 7),
  684. };
  685. struct iax2_dpcache {
  686. char peercontext[AST_MAX_CONTEXT];
  687. char exten[AST_MAX_EXTENSION];
  688. struct timeval orig;
  689. struct timeval expiry;
  690. int flags;
  691. unsigned short callno;
  692. int waiters[256];
  693. AST_LIST_ENTRY(iax2_dpcache) cache_list;
  694. AST_LIST_ENTRY(iax2_dpcache) peer_list;
  695. };
  696. static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
  697. static void reg_source_db(struct iax2_peer *p);
  698. static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
  699. static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
  700. static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
  701. static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state);
  702. static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
  703. enum iax2_thread_iostate {
  704. IAX_IOSTATE_IDLE,
  705. IAX_IOSTATE_READY,
  706. IAX_IOSTATE_PROCESSING,
  707. IAX_IOSTATE_SCHEDREADY,
  708. };
  709. enum iax2_thread_type {
  710. IAX_THREAD_TYPE_POOL,
  711. IAX_THREAD_TYPE_DYNAMIC,
  712. };
  713. struct iax2_pkt_buf {
  714. AST_LIST_ENTRY(iax2_pkt_buf) entry;
  715. size_t len;
  716. unsigned char buf[1];
  717. };
  718. struct iax2_thread {
  719. AST_LIST_ENTRY(iax2_thread) list;
  720. enum iax2_thread_type type;
  721. enum iax2_thread_iostate iostate;
  722. #ifdef SCHED_MULTITHREADED
  723. void (*schedfunc)(const void *);
  724. const void *scheddata;
  725. #endif
  726. #ifdef DEBUG_SCHED_MULTITHREAD
  727. char curfunc[80];
  728. #endif
  729. int actions;
  730. pthread_t threadid;
  731. int threadnum;
  732. struct sockaddr_in iosin;
  733. unsigned char readbuf[4096];
  734. unsigned char *buf;
  735. ssize_t buf_len;
  736. size_t buf_size;
  737. int iofd;
  738. time_t checktime;
  739. ast_mutex_t lock;
  740. ast_cond_t cond;
  741. unsigned int ready_for_signal:1;
  742. /*! if this thread is processing a full frame,
  743. some information about that frame will be stored
  744. here, so we can avoid dispatching any more full
  745. frames for that callno to other threads */
  746. struct {
  747. unsigned short callno;
  748. struct sockaddr_in sin;
  749. unsigned char type;
  750. unsigned char csub;
  751. } ffinfo;
  752. /*! Queued up full frames for processing. If more full frames arrive for
  753. * a call which this thread is already processing a full frame for, they
  754. * are queued up here. */
  755. AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
  756. };
  757. /* Thread lists */
  758. static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
  759. static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
  760. static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
  761. static void *iax2_process_thread(void *data);
  762. static void iax2_destroy(int callno);
  763. static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
  764. {
  765. ast_mutex_lock(lock);
  766. ast_cond_signal(cond);
  767. ast_mutex_unlock(lock);
  768. }
  769. static void iax_debug_output(const char *data)
  770. {
  771. if (iaxdebug)
  772. ast_verbose("%s", data);
  773. }
  774. static void iax_error_output(const char *data)
  775. {
  776. ast_log(LOG_WARNING, "%s", data);
  777. }
  778. static void __attribute__((format (printf, 1, 2))) jb_error_output(const char *fmt, ...)
  779. {
  780. va_list args;
  781. char buf[1024];
  782. va_start(args, fmt);
  783. vsnprintf(buf, sizeof(buf), fmt, args);
  784. va_end(args);
  785. ast_log(LOG_ERROR, "%s", buf);
  786. }
  787. static void __attribute__((format (printf, 1, 2))) jb_warning_output(const char *fmt, ...)
  788. {
  789. va_list args;
  790. char buf[1024];
  791. va_start(args, fmt);
  792. vsnprintf(buf, sizeof(buf), fmt, args);
  793. va_end(args);
  794. ast_log(LOG_WARNING, "%s", buf);
  795. }
  796. static void __attribute__((format (printf, 1, 2))) jb_debug_output(const char *fmt, ...)
  797. {
  798. va_list args;
  799. char buf[1024];
  800. va_start(args, fmt);
  801. vsnprintf(buf, sizeof(buf), fmt, args);
  802. va_end(args);
  803. ast_verbose("%s", buf);
  804. }
  805. /*!
  806. * \brief an array of iax2 pvt structures
  807. *
  808. * The container for active chan_iax2_pvt structures is implemented as an
  809. * array for extremely quick direct access to the correct pvt structure
  810. * based on the local call number. The local call number is used as the
  811. * index into the array where the associated pvt structure is stored.
  812. */
  813. static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS + 1];
  814. /*!
  815. * \brief Another container of iax2_pvt structures
  816. *
  817. * Active IAX2 pvt structs are also stored in this container, if they are a part
  818. * of an active call where we know the remote side's call number. The reason
  819. * for this is that incoming media frames do not contain our call number. So,
  820. * instead of having to iterate the entire iaxs array, we use this container to
  821. * look up calls where the remote side is using a given call number.
  822. */
  823. static struct ao2_container *iax_peercallno_pvts;
  824. /*!
  825. * \brief chan_iax2_pvt structure locks
  826. *
  827. * These locks are used when accessing a pvt structure in the iaxs array.
  828. * The index used here is the same as used in the iaxs array. It is the
  829. * local call number for the associated pvt struct.
  830. */
  831. static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
  832. /*!
  833. * * \brief Another container of iax2_pvt structures
  834. *
  835. * Active IAX2 pvt stucts used during transfering a call are stored here.
  836. */
  837. static struct ao2_container *iax_transfercallno_pvts;
  838. /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
  839. but keeps the division between trunked and non-trunked better. */
  840. #define TRUNK_CALL_START IAX_MAX_CALLS / 2
  841. static int maxtrunkcall = TRUNK_CALL_START;
  842. static int maxnontrunkcall = 1;
  843. 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);
  844. static int expire_registry(const void *data);
  845. static int iax2_answer(struct ast_channel *c);
  846. static int iax2_call(struct ast_channel *c, char *dest, int timeout);
  847. static int iax2_devicestate(void *data);
  848. static int iax2_digit_begin(struct ast_channel *c, char digit);
  849. static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
  850. static int iax2_do_register(struct iax2_registry *reg);
  851. static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
  852. static int iax2_hangup(struct ast_channel *c);
  853. static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
  854. static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
  855. static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
  856. static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
  857. static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
  858. static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
  859. static int iax2_sendtext(struct ast_channel *c, const char *text);
  860. static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
  861. static int iax2_transfer(struct ast_channel *c, const char *dest);
  862. static int iax2_write(struct ast_channel *c, struct ast_frame *f);
  863. static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
  864. static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
  865. static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
  866. static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
  867. static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
  868. static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
  869. static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
  870. static struct ast_frame *iax2_read(struct ast_channel *c);
  871. static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
  872. static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
  873. static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
  874. static void *iax2_dup_variable_datastore(void *);
  875. static void prune_peers(void);
  876. static void prune_users(void);
  877. static void iax2_free_variable_datastore(void *);
  878. static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
  879. static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
  880. static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
  881. static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
  882. static void build_rand_pad(unsigned char *buf, ssize_t len);
  883. static struct callno_entry *get_unused_callno(int trunk, int validated);
  884. static int replace_callno(const void *obj);
  885. static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
  886. static const struct ast_channel_tech iax2_tech = {
  887. .type = "IAX2",
  888. .description = tdesc,
  889. .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
  890. .properties = AST_CHAN_TP_WANTSJITTER,
  891. .requester = iax2_request,
  892. .devicestate = iax2_devicestate,
  893. .send_digit_begin = iax2_digit_begin,
  894. .send_digit_end = iax2_digit_end,
  895. .send_text = iax2_sendtext,
  896. .send_image = iax2_sendimage,
  897. .send_html = iax2_sendhtml,
  898. .call = iax2_call,
  899. .hangup = iax2_hangup,
  900. .answer = iax2_answer,
  901. .read = iax2_read,
  902. .write = iax2_write,
  903. .write_video = iax2_write,
  904. .indicate = iax2_indicate,
  905. .setoption = iax2_setoption,
  906. .bridge = iax2_bridge,
  907. .transfer = iax2_transfer,
  908. .fixup = iax2_fixup,
  909. .func_channel_read = acf_channel_read,
  910. };
  911. static void mwi_event_cb(const struct ast_event *event, void *userdata)
  912. {
  913. /* The MWI subscriptions exist just so the core knows we care about those
  914. * mailboxes. However, we just grab the events out of the cache when it
  915. * is time to send MWI, since it is only sent with a REGACK. */
  916. }
  917. /*! \brief Send manager event at call setup to link between Asterisk channel name
  918. and IAX2 call identifiers */
  919. static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
  920. {
  921. manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
  922. "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
  923. pvt->owner ? pvt->owner->name : "",
  924. pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
  925. }
  926. static struct ast_datastore_info iax2_variable_datastore_info = {
  927. .type = "IAX2_VARIABLE",
  928. .duplicate = iax2_dup_variable_datastore,
  929. .destroy = iax2_free_variable_datastore,
  930. };
  931. static void *iax2_dup_variable_datastore(void *old)
  932. {
  933. AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
  934. struct ast_var_t *oldvar, *newvar;
  935. newlist = ast_calloc(sizeof(*newlist), 1);
  936. if (!newlist) {
  937. ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
  938. return NULL;
  939. }
  940. AST_LIST_HEAD_INIT(newlist);
  941. AST_LIST_LOCK(oldlist);
  942. AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
  943. newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
  944. if (newvar)
  945. AST_LIST_INSERT_TAIL(newlist, newvar, entries);
  946. else
  947. ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
  948. }
  949. AST_LIST_UNLOCK(oldlist);
  950. return newlist;
  951. }
  952. static void iax2_free_variable_datastore(void *old)
  953. {
  954. AST_LIST_HEAD(, ast_var_t) *oldlist = old;
  955. struct ast_var_t *oldvar;
  956. AST_LIST_LOCK(oldlist);
  957. while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
  958. ast_free(oldvar);
  959. }
  960. AST_LIST_UNLOCK(oldlist);
  961. AST_LIST_HEAD_DESTROY(oldlist);
  962. ast_free(oldlist);
  963. }
  964. /* WARNING: insert_idle_thread should only ever be called within the
  965. * context of an iax2_process_thread() thread.
  966. */
  967. static void insert_idle_thread(struct iax2_thread *thread)
  968. {
  969. if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
  970. AST_LIST_LOCK(&dynamic_list);
  971. AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
  972. AST_LIST_UNLOCK(&dynamic_list);
  973. } else {
  974. AST_LIST_LOCK(&idle_list);
  975. AST_LIST_INSERT_TAIL(&idle_list, thread, list);
  976. AST_LIST_UNLOCK(&idle_list);
  977. }
  978. return;
  979. }
  980. static struct iax2_thread *find_idle_thread(void)
  981. {
  982. struct iax2_thread *thread = NULL;
  983. /* Pop the head of the idle list off */
  984. AST_LIST_LOCK(&idle_list);
  985. thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
  986. AST_LIST_UNLOCK(&idle_list);
  987. /* If we popped a thread off the idle list, just return it */
  988. if (thread) {
  989. memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
  990. return thread;
  991. }
  992. /* Pop the head of the dynamic list off */
  993. AST_LIST_LOCK(&dynamic_list);
  994. thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
  995. AST_LIST_UNLOCK(&dynamic_list);
  996. /* If we popped a thread off the dynamic list, just return it */
  997. if (thread) {
  998. memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
  999. return thread;
  1000. }
  1001. /* If we can't create a new dynamic thread for any reason, return no thread at all */
  1002. if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
  1003. return NULL;
  1004. /* Set default values */
  1005. ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
  1006. thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
  1007. thread->type = IAX_THREAD_TYPE_DYNAMIC;
  1008. /* Initialize lock and condition */
  1009. ast_mutex_init(&thread->lock);
  1010. ast_cond_init(&thread->cond, NULL);
  1011. /* Create thread and send it on it's way */
  1012. if (ast_pthread_create_detached_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
  1013. ast_cond_destroy(&thread->cond);
  1014. ast_mutex_destroy(&thread->lock);
  1015. ast_free(thread);
  1016. return NULL;
  1017. }
  1018. /* this thread is not processing a full frame (since it is idle),
  1019. so ensure that the field for the full frame call number is empty */
  1020. memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
  1021. /* Wait for the thread to be ready before returning it to the caller */
  1022. while (!thread->ready_for_signal)
  1023. usleep(1);
  1024. return thread;
  1025. }
  1026. #ifdef SCHED_MULTITHREADED
  1027. static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
  1028. {
  1029. struct iax2_thread *thread = NULL;
  1030. static time_t lasterror;
  1031. static time_t t;
  1032. thread = find_idle_thread();
  1033. if (thread != NULL) {
  1034. thread->schedfunc = func;
  1035. thread->scheddata = data;
  1036. thread->iostate = IAX_IOSTATE_SCHEDREADY;
  1037. #ifdef DEBUG_SCHED_MULTITHREAD
  1038. ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
  1039. #endif
  1040. signal_condition(&thread->lock, &thread->cond);
  1041. return 0;
  1042. }
  1043. time(&t);
  1044. if (t != lasterror)
  1045. ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
  1046. lasterror = t;
  1047. return -1;
  1048. }
  1049. #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
  1050. #endif
  1051. static int iax2_sched_replace(int id, struct sched_context *con, int when, ast_sched_cb callback, const void *data)
  1052. {
  1053. AST_SCHED_REPLACE(id, con, when, callback, data);
  1054. signal_condition(&sched_lock, &sched_cond);
  1055. return id;
  1056. }
  1057. static int iax2_sched_add(struct sched_context *con, int when, ast_sched_cb callback, const void *data)
  1058. {
  1059. int res;
  1060. res = ast_sched_add(con, when, callback, data);
  1061. signal_condition(&sched_lock, &sched_cond);
  1062. return res;
  1063. }
  1064. static int send_ping(const void *data);
  1065. static void __send_ping(const void *data)
  1066. {
  1067. int callno = (long) data;
  1068. ast_mutex_lock(&iaxsl[callno]);
  1069. if (iaxs[callno]) {
  1070. if (iaxs[callno]->peercallno) {
  1071. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
  1072. iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
  1073. } else {
  1074. /* I am the schedule, so I'm allowed to do this */
  1075. iaxs[callno]->pingid = -1;
  1076. }
  1077. } else {
  1078. ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
  1079. }
  1080. ast_mutex_unlock(&iaxsl[callno]);
  1081. }
  1082. static int send_ping(const void *data)
  1083. {
  1084. #ifdef SCHED_MULTITHREADED
  1085. if (schedule_action(__send_ping, data))
  1086. #endif
  1087. __send_ping(data);
  1088. return 0;
  1089. }
  1090. static int get_encrypt_methods(const char *s)
  1091. {
  1092. int e;
  1093. if (!strcasecmp(s, "aes128"))
  1094. e = IAX_ENCRYPT_AES128;
  1095. else if (ast_true(s))
  1096. e = IAX_ENCRYPT_AES128;
  1097. else
  1098. e = 0;
  1099. return e;
  1100. }
  1101. static int send_lagrq(const void *data);
  1102. static void __send_lagrq(const void *data)
  1103. {
  1104. int callno = (long) data;
  1105. ast_mutex_lock(&iaxsl[callno]);
  1106. if (iaxs[callno]) {
  1107. if (iaxs[callno]->peercallno) {
  1108. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
  1109. iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
  1110. } else {
  1111. /* I am the schedule, so I'm allowed to do this */
  1112. iaxs[callno]->lagid = -1;
  1113. }
  1114. } else {
  1115. ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
  1116. }
  1117. ast_mutex_unlock(&iaxsl[callno]);
  1118. }
  1119. static int send_lagrq(const void *data)
  1120. {
  1121. #ifdef SCHED_MULTITHREADED
  1122. if (schedule_action(__send_lagrq, data))
  1123. #endif
  1124. __send_lagrq(data);
  1125. return 0;
  1126. }
  1127. static unsigned char compress_subclass(int subclass)
  1128. {
  1129. int x;
  1130. int power=-1;
  1131. /* If it's 128 or smaller, just return it */
  1132. if (subclass < IAX_FLAG_SC_LOG)
  1133. return subclass;
  1134. /* Otherwise find its power */
  1135. for (x = 0; x < IAX_MAX_SHIFT; x++) {
  1136. if (subclass & (1 << x)) {
  1137. if (power > -1) {
  1138. ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
  1139. return 0;
  1140. } else
  1141. power = x;
  1142. }
  1143. }
  1144. return power | IAX_FLAG_SC_LOG;
  1145. }
  1146. static int uncompress_subclass(unsigned char csub)
  1147. {
  1148. /* If the SC_LOG flag is set, return 2^csub otherwise csub */
  1149. if (csub & IAX_FLAG_SC_LOG) {
  1150. /* special case for 'compressed' -1 */
  1151. if (csub == 0xff)
  1152. return -1;
  1153. else
  1154. return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
  1155. }
  1156. else
  1157. return csub;
  1158. }
  1159. /*!
  1160. * \note The only member of the peer passed here guaranteed to be set is the name field
  1161. */
  1162. static int peer_hash_cb(const void *obj, const int flags)
  1163. {
  1164. const struct iax2_peer *peer = obj;
  1165. return ast_str_hash(peer->name);
  1166. }
  1167. /*!
  1168. * \note The only member of the peer passed here guaranteed to be set is the name field
  1169. */
  1170. static int peer_cmp_cb(void *obj, void *arg, int flags)
  1171. {
  1172. struct iax2_peer *peer = obj, *peer2 = arg;
  1173. return !strcmp(peer->name, peer2->name) ? CMP_MATCH : 0;
  1174. }
  1175. /*!
  1176. * \note The only member of the user passed here guaranteed to be set is the name field
  1177. */
  1178. static int user_hash_cb(const void *obj, const int flags)
  1179. {
  1180. const struct iax2_user *user = obj;
  1181. return ast_str_hash(user->name);
  1182. }
  1183. /*!
  1184. * \note The only member of the user passed here guaranteed to be set is the name field
  1185. */
  1186. static int user_cmp_cb(void *obj, void *arg, int flags)
  1187. {
  1188. struct iax2_user *user = obj, *user2 = arg;
  1189. return !strcmp(user->name, user2->name) ? CMP_MATCH : 0;
  1190. }
  1191. /*!
  1192. * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
  1193. * so do not call it with a pvt lock held.
  1194. */
  1195. static struct iax2_peer *find_peer(const char *name, int realtime)
  1196. {
  1197. struct iax2_peer *peer = NULL;
  1198. struct iax2_peer tmp_peer = {
  1199. .name = name,
  1200. };
  1201. peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
  1202. /* Now go for realtime if applicable */
  1203. if(!peer && realtime)
  1204. peer = realtime_peer(name, NULL);
  1205. return peer;
  1206. }
  1207. static struct iax2_peer *peer_ref(struct iax2_peer *peer)
  1208. {
  1209. ao2_ref(peer, +1);
  1210. return peer;
  1211. }
  1212. static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
  1213. {
  1214. ao2_ref(peer, -1);
  1215. return NULL;
  1216. }
  1217. static struct iax2_user *find_user(const char *name)
  1218. {
  1219. struct iax2_user tmp_user = {
  1220. .name = name,
  1221. };
  1222. return ao2_find(users, &tmp_user, OBJ_POINTER);
  1223. }
  1224. static inline struct iax2_user *user_ref(struct iax2_user *user)
  1225. {
  1226. ao2_ref(user, +1);
  1227. return user;
  1228. }
  1229. static inline struct iax2_user *user_unref(struct iax2_user *user)
  1230. {
  1231. ao2_ref(user, -1);
  1232. return NULL;
  1233. }
  1234. static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
  1235. {
  1236. struct iax2_peer *peer = NULL;
  1237. int res = 0;
  1238. struct ao2_iterator i;
  1239. i = ao2_iterator_init(peers, 0);
  1240. while ((peer = ao2_iterator_next(&i))) {
  1241. if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
  1242. (peer->addr.sin_port == sin.sin_port)) {
  1243. ast_copy_string(host, peer->name, len);
  1244. peer_unref(peer);
  1245. res = 1;
  1246. break;
  1247. }
  1248. peer_unref(peer);
  1249. }
  1250. ao2_iterator_destroy(&i);
  1251. if (!peer) {
  1252. peer = realtime_peer(NULL, &sin);
  1253. if (peer) {
  1254. ast_copy_string(host, peer->name, len);
  1255. peer_unref(peer);
  1256. res = 1;
  1257. }
  1258. }
  1259. return res;
  1260. }
  1261. static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
  1262. {
  1263. /* Decrement AUTHREQ count if needed */
  1264. if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
  1265. struct iax2_user *user;
  1266. struct iax2_user tmp_user = {
  1267. .name = pvt->username,
  1268. };
  1269. user = ao2_find(users, &tmp_user, OBJ_POINTER);
  1270. if (user) {
  1271. ast_atomic_fetchadd_int(&user->curauthreq, -1);
  1272. user_unref(user);
  1273. }
  1274. ast_clear_flag(pvt, IAX_MAXAUTHREQ);
  1275. }
  1276. /* No more pings or lagrq's */
  1277. AST_SCHED_DEL(sched, pvt->pingid);
  1278. AST_SCHED_DEL(sched, pvt->lagid);
  1279. AST_SCHED_DEL(sched, pvt->autoid);
  1280. AST_SCHED_DEL(sched, pvt->authid);
  1281. AST_SCHED_DEL(sched, pvt->initid);
  1282. AST_SCHED_DEL(sched, pvt->jbid);
  1283. }
  1284. static void iax2_frame_free(struct iax_frame *fr)
  1285. {
  1286. AST_SCHED_DEL(sched, fr->retrans);
  1287. iax_frame_free(fr);
  1288. }
  1289. static int scheduled_destroy(const void *vid)
  1290. {
  1291. unsigned short callno = PTR_TO_CALLNO(vid);
  1292. ast_mutex_lock(&iaxsl[callno]);
  1293. if (iaxs[callno]) {
  1294. if (option_debug) {
  1295. ast_log(LOG_DEBUG, "Really destroying %d now...\n", callno);
  1296. }
  1297. iax2_destroy(callno);
  1298. }
  1299. ast_mutex_unlock(&iaxsl[callno]);
  1300. return 0;
  1301. }
  1302. static void free_signaling_queue_entry(struct signaling_queue_entry *s)
  1303. {
  1304. ast_free(s->f.data);
  1305. ast_free(s);
  1306. }
  1307. /*! \brief This function must be called once we are sure the other side has
  1308. * given us a call number. All signaling is held here until that point. */
  1309. static void send_signaling(struct chan_iax2_pvt *pvt)
  1310. {
  1311. struct signaling_queue_entry *s = NULL;
  1312. while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
  1313. iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
  1314. free_signaling_queue_entry(s);
  1315. }
  1316. pvt->hold_signaling = 0;
  1317. }
  1318. /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
  1319. * we have received a destination call number. */
  1320. static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
  1321. {
  1322. struct signaling_queue_entry *new;
  1323. if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
  1324. return 1; /* do not queue this frame */
  1325. } else if (!(new = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
  1326. return -1; /* out of memory */
  1327. }
  1328. memcpy(&new->f, f, sizeof(new->f)); /* copy ast_frame into our queue entry */
  1329. if (new->f.datalen) { /* if there is data in this frame copy it over as well */
  1330. if (!(new->f.data = ast_calloc(1, new->f.datalen))) {
  1331. free_signaling_queue_entry(new);
  1332. return -1;
  1333. }
  1334. memcpy(new->f.data, f->data, sizeof(*new->f.data));
  1335. }
  1336. AST_LIST_INSERT_TAIL(&pvt->signaling_queue, new, next);
  1337. return 0;
  1338. }
  1339. static void pvt_destructor(void *obj)
  1340. {
  1341. struct chan_iax2_pvt *pvt = obj;
  1342. struct iax_frame *cur = NULL;
  1343. struct signaling_queue_entry *s = NULL;
  1344. iax2_destroy_helper(pvt);
  1345. sched_delay_remove(&pvt->addr, pvt->callno_entry);
  1346. pvt->callno_entry = NULL;
  1347. /* Already gone */
  1348. ast_set_flag(pvt, IAX_ALREADYGONE);
  1349. AST_LIST_LOCK(&frame_queue);
  1350. AST_LIST_TRAVERSE(&frame_queue, cur, list) {
  1351. /* Cancel any pending transmissions */
  1352. if (cur->callno == pvt->callno) {
  1353. cur->retries = -1;
  1354. }
  1355. }
  1356. AST_LIST_UNLOCK(&frame_queue);
  1357. while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
  1358. free_signaling_queue_entry(s);
  1359. }
  1360. if (pvt->reg) {
  1361. pvt->reg->callno = 0;
  1362. }
  1363. if (!pvt->owner) {
  1364. jb_frame frame;
  1365. if (pvt->vars) {
  1366. ast_variables_destroy(pvt->vars);
  1367. pvt->vars = NULL;
  1368. }
  1369. while (jb_getall(pvt->jb, &frame) == JB_OK) {
  1370. iax2_frame_free(frame.data);
  1371. }
  1372. jb_destroy(pvt->jb);
  1373. ast_string_field_free_memory(pvt);
  1374. }
  1375. }
  1376. static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
  1377. {
  1378. struct chan_iax2_pvt *tmp;
  1379. jb_conf jbconf;
  1380. if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
  1381. return NULL;
  1382. }
  1383. if (ast_string_field_init(tmp, 32)) {
  1384. ao2_ref(tmp, -1);
  1385. tmp = NULL;
  1386. return NULL;
  1387. }
  1388. tmp->prefs = prefs;
  1389. tmp->pingid = -1;
  1390. tmp->lagid = -1;
  1391. tmp->autoid = -1;
  1392. tmp->authid = -1;
  1393. tmp->initid = -1;
  1394. ast_string_field_set(tmp,exten, "s");
  1395. ast_string_field_set(tmp,host, host);
  1396. tmp->jb = jb_new();
  1397. tmp->jbid = -1;
  1398. jbconf.max_jitterbuf = maxjitterbuffer;
  1399. jbconf.resync_threshold = resyncthreshold;
  1400. jbconf.max_contig_interp = maxjitterinterps;
  1401. jbconf.target_extra = jittertargetextra;
  1402. jb_setconf(tmp->jb,&jbconf);
  1403. AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
  1404. tmp->hold_signaling = 1;
  1405. AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
  1406. return tmp;
  1407. }
  1408. static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
  1409. {
  1410. struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
  1411. if (new) {
  1412. size_t afdatalen = new->afdatalen;
  1413. memcpy(new, fr, sizeof(*new));
  1414. iax_frame_wrap(new, &fr->af);
  1415. new->afdatalen = afdatalen;
  1416. new->data = NULL;
  1417. new->datalen = 0;
  1418. new->direction = DIRECTION_INGRESS;
  1419. new->retrans = -1;
  1420. }
  1421. return new;
  1422. }
  1423. /* keep these defined in this order. They are used in find_callno to
  1424. * determine whether or not a new call number should be allowed. */
  1425. enum {
  1426. /* do not allow a new call number, only search ones in use for match */
  1427. NEW_PREVENT = 0,
  1428. /* search for match first, then allow a new one to be allocated */
  1429. NEW_ALLOW = 1,
  1430. /* do not search for match, force a new call number */
  1431. NEW_FORCE = 2,
  1432. /* do not search for match, force a new call number. Signifies call number
  1433. * has been calltoken validated */
  1434. NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
  1435. };
  1436. static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
  1437. {
  1438. if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
  1439. (cur->addr.sin_port == sin->sin_port)) {
  1440. /* This is the main host */
  1441. if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
  1442. (check_dcallno ? dcallno == cur->callno : 1) ) {
  1443. /* That's us. Be sure we keep track of the peer call number */
  1444. return 1;
  1445. }
  1446. }
  1447. if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
  1448. (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
  1449. /* We're transferring */
  1450. if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
  1451. return 1;
  1452. }
  1453. return 0;
  1454. }
  1455. static void update_max_trunk(void)
  1456. {
  1457. int max = TRUNK_CALL_START;
  1458. int x;
  1459. /* XXX Prolly don't need locks here XXX */
  1460. for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
  1461. if (iaxs[x]) {
  1462. max = x + 1;
  1463. }
  1464. }
  1465. maxtrunkcall = max;
  1466. if (iaxdebug)
  1467. ast_debug(1, "New max trunk callno is %d\n", max);
  1468. }
  1469. static void update_max_nontrunk(void)
  1470. {
  1471. int max = 1;
  1472. int x;
  1473. /* XXX Prolly don't need locks here XXX */
  1474. for (x=1;x<TRUNK_CALL_START - 1; x++) {
  1475. if (iaxs[x])
  1476. max = x + 1;
  1477. }
  1478. maxnontrunkcall = max;
  1479. if (iaxdebug)
  1480. ast_debug(1, "New max nontrunk callno is %d\n", max);
  1481. }
  1482. static int make_trunk(unsigned short callno, int locked)
  1483. {
  1484. int x;
  1485. int res= 0;
  1486. struct callno_entry *callno_entry;
  1487. if (iaxs[callno]->oseqno) {
  1488. ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
  1489. return -1;
  1490. }
  1491. if (callno & TRUNK_CALL_START) {
  1492. ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
  1493. return -1;
  1494. }
  1495. if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
  1496. ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
  1497. return -1;
  1498. }
  1499. x = callno_entry->callno;
  1500. ast_mutex_lock(&iaxsl[x]);
  1501. /*!
  1502. * \note We delete these before switching the slot, because if
  1503. * they fire in the meantime, they will generate a warning.
  1504. */
  1505. AST_SCHED_DEL(sched, iaxs[callno]->pingid);
  1506. AST_SCHED_DEL(sched, iaxs[callno]->lagid);
  1507. iaxs[x] = iaxs[callno];
  1508. iaxs[x]->callno = x;
  1509. /* since we copied over the pvt from a different callno, make sure the old entry is replaced
  1510. * before assigning the new one */
  1511. if (iaxs[x]->callno_entry) {
  1512. iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
  1513. }
  1514. iaxs[x]->callno_entry = callno_entry;
  1515. iaxs[callno] = NULL;
  1516. /* Update the two timers that should have been started */
  1517. iaxs[x]->pingid = iax2_sched_add(sched,
  1518. ping_time * 1000, send_ping, (void *)(long)x);
  1519. iaxs[x]->lagid = iax2_sched_add(sched,
  1520. lagrq_time * 1000, send_lagrq, (void *)(long)x);
  1521. if (locked)
  1522. ast_mutex_unlock(&iaxsl[callno]);
  1523. res = x;
  1524. if (!locked)
  1525. ast_mutex_unlock(&iaxsl[x]);
  1526. ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
  1527. /* We move this call from a non-trunked to a trunked call */
  1528. update_max_trunk();
  1529. update_max_nontrunk();
  1530. return res;
  1531. }
  1532. static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
  1533. {
  1534. if (!pvt->transfercallno) {
  1535. ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
  1536. return;
  1537. }
  1538. ao2_link(iax_transfercallno_pvts, pvt);
  1539. }
  1540. static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
  1541. {
  1542. if (!pvt->transfercallno) {
  1543. ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
  1544. return;
  1545. }
  1546. ao2_unlink(iax_transfercallno_pvts, pvt);
  1547. }
  1548. static void store_by_peercallno(struct chan_iax2_pvt *pvt)
  1549. {
  1550. if (!pvt->peercallno) {
  1551. ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
  1552. return;
  1553. }
  1554. ao2_link(iax_peercallno_pvts, pvt);
  1555. }
  1556. static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
  1557. {
  1558. if (!pvt->peercallno) {
  1559. ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
  1560. return;
  1561. }
  1562. ao2_unlink(iax_peercallno_pvts, pvt);
  1563. }
  1564. static int addr_range_delme_cb(void *obj, void *arg, int flags)
  1565. {
  1566. struct addr_range *lim = obj;
  1567. lim->delme = 1;
  1568. return 0;
  1569. }
  1570. static int addr_range_hash_cb(const void *obj, const int flags)
  1571. {
  1572. const struct addr_range *lim = obj;
  1573. return abs((int) lim->ha.netaddr.s_addr);
  1574. }
  1575. static int addr_range_cmp_cb(void *obj, void *arg, int flags)
  1576. {
  1577. struct addr_range *lim1 = obj, *lim2 = arg;
  1578. return ((lim1->ha.netaddr.s_addr == lim2->ha.netaddr.s_addr) &&
  1579. (lim1->ha.netmask.s_addr == lim2->ha.netmask.s_addr)) ?
  1580. CMP_MATCH | CMP_STOP : 0;
  1581. }
  1582. static int peercnt_hash_cb(const void *obj, const int flags)
  1583. {
  1584. const struct peercnt *peercnt = obj;
  1585. return abs((int) peercnt->addr);
  1586. }
  1587. static int peercnt_cmp_cb(void *obj, void *arg, int flags)
  1588. {
  1589. struct peercnt *peercnt1 = obj, *peercnt2 = arg;
  1590. return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
  1591. }
  1592. static int addr_range_match_address_cb(void *obj, void *arg, int flags)
  1593. {
  1594. struct addr_range *addr_range = obj;
  1595. struct sockaddr_in *sin = arg;
  1596. if ((sin->sin_addr.s_addr & addr_range->ha.netmask.s_addr) == addr_range->ha.netaddr.s_addr) {
  1597. return CMP_MATCH | CMP_STOP;
  1598. }
  1599. return 0;
  1600. }
  1601. /*!
  1602. * \internal
  1603. *
  1604. * \brief compares sin to calltoken_ignores table to determine if validation is required.
  1605. */
  1606. static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
  1607. {
  1608. struct addr_range *addr_range;
  1609. struct iax2_peer *peer = NULL;
  1610. struct iax2_user *user = NULL;
  1611. /* if no username is given, check for guest accounts */
  1612. const char *find = S_OR(name, "guest");
  1613. int res = 1; /* required by default */
  1614. int optional = 0;
  1615. enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
  1616. /* There are only two cases in which calltoken validation is not required.
  1617. * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
  1618. * the peer definition has not set the requirecalltoken option.
  1619. * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
  1620. */
  1621. /* ----- Case 1 ----- */
  1622. if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
  1623. ao2_ref(addr_range, -1);
  1624. optional = 1;
  1625. }
  1626. /* ----- Case 2 ----- */
  1627. if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
  1628. calltoken_required = user->calltoken_required;
  1629. } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
  1630. calltoken_required = user->calltoken_required;
  1631. } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
  1632. calltoken_required = peer->calltoken_required;
  1633. } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
  1634. calltoken_required = peer->calltoken_required;
  1635. }
  1636. if (peer) {
  1637. peer_unref(peer);
  1638. }
  1639. if (user) {
  1640. user_unref(user);
  1641. }
  1642. ast_debug(1, "Determining if address %s with username %s requires calltoken validation. Optional = %d calltoken_required = %d \n", ast_inet_ntoa(sin->sin_addr), name, optional, calltoken_required);
  1643. if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
  1644. (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
  1645. res = 0;
  1646. }
  1647. return res;
  1648. }
  1649. /*!
  1650. * \internal
  1651. *
  1652. * \brief set peercnt callno limit.
  1653. *
  1654. * \details
  1655. * First looks in custom definitions. If not found, global limit
  1656. * is used. Entries marked as reg already have
  1657. * a custom limit set by a registration and are not modified.
  1658. */
  1659. static void set_peercnt_limit(struct peercnt *peercnt)
  1660. {
  1661. uint16_t limit = global_maxcallno;
  1662. struct addr_range *addr_range;
  1663. struct sockaddr_in sin = {
  1664. .sin_addr.s_addr = peercnt->addr,
  1665. };
  1666. if (peercnt->reg && peercnt->limit) {
  1667. return; /* this peercnt has a custom limit set by a registration */
  1668. }
  1669. if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
  1670. limit = addr_range->limit;
  1671. ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
  1672. ao2_ref(addr_range, -1);
  1673. }
  1674. peercnt->limit = limit;
  1675. }
  1676. /*!
  1677. * \internal
  1678. * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
  1679. */
  1680. static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
  1681. {
  1682. struct peercnt *peercnt = obj;
  1683. set_peercnt_limit(peercnt);
  1684. ast_debug(1, "Reset limits for peercnts table\n");
  1685. return 0;
  1686. }
  1687. /*!
  1688. * \internal
  1689. * \brief returns match if delme is set.
  1690. */
  1691. static int prune_addr_range_cb(void *obj, void *arg, int flags)
  1692. {
  1693. struct addr_range *addr_range = obj;
  1694. return addr_range->delme ? CMP_MATCH : 0;
  1695. }
  1696. /*!
  1697. * \internal
  1698. * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
  1699. */
  1700. static void peercnt_modify(unsigned char reg, uint16_t limit, struct sockaddr_in *sin)
  1701. {
  1702. /* this function turns off and on custom callno limits set by peer registration */
  1703. struct peercnt *peercnt;
  1704. struct peercnt tmp = {
  1705. .addr = sin->sin_addr.s_addr,
  1706. };
  1707. if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
  1708. peercnt->reg = reg;
  1709. if (limit) {
  1710. peercnt->limit = limit;
  1711. } else {
  1712. set_peercnt_limit(peercnt);
  1713. }
  1714. ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin->sin_addr), peercnt->limit, peercnt->reg);
  1715. ao2_ref(peercnt, -1); /* decrement ref from find */
  1716. }
  1717. }
  1718. /*!
  1719. * \internal
  1720. * \brief adds an ip to the peercnts table, increments connection count if it already exists
  1721. *
  1722. * \details First searches for the address in the peercnts table. If found
  1723. * the current count is incremented. If not found a new peercnt is allocated
  1724. * and linked into the peercnts table with a call number count of 1.
  1725. */
  1726. static int peercnt_add(struct sockaddr_in *sin)
  1727. {
  1728. struct peercnt *peercnt;
  1729. unsigned long addr = sin->sin_addr.s_addr;
  1730. int res = 0;
  1731. struct peercnt tmp = {
  1732. .addr = addr,
  1733. };
  1734. /* Reasoning for peercnts container lock: Two identical ip addresses
  1735. * could be added by different threads at the "same time". Without the container
  1736. * lock, both threads could alloc space for the same object and attempt
  1737. * to link to table. With the lock, one would create the object and link
  1738. * to table while the other would find the already created peercnt object
  1739. * rather than creating a new one. */
  1740. ao2_lock(peercnts);
  1741. if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
  1742. ao2_lock(peercnt);
  1743. } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
  1744. ao2_lock(peercnt);
  1745. /* create and set defaults */
  1746. peercnt->addr = addr;
  1747. set_peercnt_limit(peercnt);
  1748. /* guarantees it does not go away after unlocking table
  1749. * ao2_find automatically adds this */
  1750. ao2_link(peercnts, peercnt);
  1751. } else {
  1752. ao2_unlock(peercnts);
  1753. return -1;
  1754. }
  1755. /* check to see if the address has hit its callno limit. If not increment cur. */
  1756. if (peercnt->limit > peercnt->cur) {
  1757. peercnt->cur++;
  1758. ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
  1759. } else { /* max num call numbers for this peer has been reached! */
  1760. ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
  1761. res = -1;
  1762. }
  1763. /* clean up locks and ref count */
  1764. ao2_unlock(peercnt);
  1765. ao2_unlock(peercnts);
  1766. ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
  1767. return res;
  1768. }
  1769. /*!
  1770. * \internal
  1771. * \brief decrements a peercnts table entry
  1772. */
  1773. static void peercnt_remove(struct peercnt *peercnt)
  1774. {
  1775. struct sockaddr_in sin = {
  1776. .sin_addr.s_addr = peercnt->addr,
  1777. };
  1778. if (peercnt) {
  1779. /* Container locked here since peercnt may be unlinked from list. If left unlocked,
  1780. * peercnt_add could try and grab this entry from the table and modify it at the
  1781. * "same time" this thread attemps to unlink it.*/
  1782. ao2_lock(peercnts);
  1783. peercnt->cur--;
  1784. ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
  1785. /* if this was the last connection from the peer remove it from table */
  1786. if (peercnt->cur == 0) {
  1787. ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
  1788. }
  1789. ao2_unlock(peercnts);
  1790. }
  1791. }
  1792. /*!
  1793. * \internal
  1794. * \brief called by scheduler to decrement object
  1795. */
  1796. static int peercnt_remove_cb(const void *obj)
  1797. {
  1798. struct peercnt *peercnt = (struct peercnt *) obj;
  1799. peercnt_remove(peercnt);
  1800. ao2_ref(peercnt, -1); /* decrement ref from scheduler */
  1801. return 0;
  1802. }
  1803. /*!
  1804. * \internal
  1805. * \brief decrements peercnts connection count, finds by addr
  1806. */
  1807. static int peercnt_remove_by_addr(struct sockaddr_in *sin)
  1808. {
  1809. struct peercnt *peercnt;
  1810. struct peercnt tmp = {
  1811. .addr = sin->sin_addr.s_addr,
  1812. };
  1813. if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
  1814. peercnt_remove(peercnt);
  1815. ao2_ref(peercnt, -1); /* decrement ref from find */
  1816. }
  1817. return 0;
  1818. }
  1819. /*!
  1820. * \internal
  1821. * \brief Create callno_limit entry based on configuration
  1822. */
  1823. static void build_callno_limits(struct ast_variable *v)
  1824. {
  1825. struct addr_range *addr_range = NULL;
  1826. struct addr_range tmp;
  1827. struct ast_ha *ha;
  1828. int limit;
  1829. int error;
  1830. int found;
  1831. for (; v; v = v->next) {
  1832. limit = -1;
  1833. error = 0;
  1834. found = 0;
  1835. ha = ast_append_ha("permit", v->name, NULL, &error);
  1836. /* check for valid config information */
  1837. if (error) {
  1838. ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
  1839. continue;
  1840. } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
  1841. ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
  1842. ast_free_ha(ha);
  1843. continue;
  1844. }
  1845. ast_copy_ha(ha, &tmp.ha);
  1846. /* find or create the addr_range */
  1847. if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
  1848. ao2_lock(addr_range);
  1849. found = 1;
  1850. } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
  1851. ast_free_ha(ha);
  1852. return; /* out of memory */
  1853. }
  1854. /* copy over config data into addr_range object */
  1855. ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
  1856. ast_free_ha(ha); /* cleanup the tmp ha */
  1857. addr_range->limit = limit;
  1858. addr_range->delme = 0;
  1859. /* cleanup */
  1860. if (found) {
  1861. ao2_unlock(addr_range);
  1862. } else {
  1863. ao2_link(callno_limits, addr_range);
  1864. }
  1865. ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
  1866. }
  1867. }
  1868. /*!
  1869. * \internal
  1870. * \brief Create calltoken_ignores entry based on configuration
  1871. */
  1872. static int add_calltoken_ignore(const char *addr)
  1873. {
  1874. struct addr_range tmp;
  1875. struct addr_range *addr_range = NULL;
  1876. struct ast_ha *ha = NULL;
  1877. int error = 0;
  1878. if (ast_strlen_zero(addr)) {
  1879. ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
  1880. return -1;
  1881. }
  1882. ha = ast_append_ha("permit", addr, NULL, &error);
  1883. /* check for valid config information */
  1884. if (error) {
  1885. ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
  1886. return -1;
  1887. }
  1888. ast_copy_ha(ha, &tmp.ha);
  1889. /* find or create the addr_range */
  1890. if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
  1891. ao2_lock(addr_range);
  1892. addr_range->delme = 0;
  1893. ao2_unlock(addr_range);
  1894. } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
  1895. /* copy over config data into addr_range object */
  1896. ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
  1897. ao2_link(calltoken_ignores, addr_range);
  1898. } else {
  1899. ast_free_ha(ha);
  1900. return -1;
  1901. }
  1902. ast_free_ha(ha);
  1903. ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
  1904. return 0;
  1905. }
  1906. static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1907. {
  1908. struct ao2_iterator i;
  1909. struct peercnt *peercnt;
  1910. struct sockaddr_in sin;
  1911. int found = 0;
  1912. switch (cmd) {
  1913. case CLI_INIT:
  1914. e->command = "iax2 show callnumber usage";
  1915. e->usage =
  1916. "Usage: iax2 show callnumber usage <ip address (optional)>\n"
  1917. " Shows current ip addresses which are consuming iax2 call numbers\n";
  1918. return NULL;
  1919. case CLI_GENERATE:
  1920. return NULL;
  1921. case CLI_HANDLER:
  1922. if (a->argc < 4 || a->argc > 5)
  1923. return CLI_SHOWUSAGE;
  1924. ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
  1925. i = ao2_iterator_init(peercnts, 0);
  1926. while ((peercnt = ao2_iterator_next(&i))) {
  1927. sin.sin_addr.s_addr = peercnt->addr;
  1928. if (a->argc == 5 && (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr)))) {
  1929. ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
  1930. found = 1;
  1931. break;
  1932. } else {
  1933. ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
  1934. }
  1935. ao2_ref(peercnt, -1);
  1936. }
  1937. ao2_iterator_destroy(&i);
  1938. if (a->argc == 4) {
  1939. ast_cli(a->fd, "\nNon-CallToken Validation Limit: %d\nNon-CallToken Validated: %d\n", global_maxcallno_nonval, total_nonval_callno_used);
  1940. } else if (a->argc == 5 && !found) {
  1941. ast_cli(a->fd, "No callnumber table entries for %s found\n", a->argv[4] );
  1942. }
  1943. return CLI_SUCCESS;
  1944. default:
  1945. return NULL;
  1946. }
  1947. }
  1948. static struct callno_entry *get_unused_callno(int trunk, int validated)
  1949. {
  1950. struct callno_entry *callno_entry = NULL;
  1951. if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
  1952. ast_log(LOG_WARNING, "Out of CallNumbers\n");
  1953. /* Minor optimization for the extreme case. */
  1954. return NULL;
  1955. }
  1956. /* the callno_pool container is locked here primarily to ensure thread
  1957. * safety of the total_nonval_callno_used check and increment */
  1958. ao2_lock(callno_pool);
  1959. /* only a certain number of nonvalidated call numbers should be allocated.
  1960. * If there ever is an attack, this separates the calltoken validating
  1961. * users from the non calltoken validating users. */
  1962. if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
  1963. ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
  1964. ao2_unlock(callno_pool);
  1965. return NULL;
  1966. }
  1967. /* unlink the object from the container, taking over ownership
  1968. * of the reference the container had to the object */
  1969. callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
  1970. if (callno_entry) {
  1971. callno_entry->validated = validated;
  1972. if (!validated) {
  1973. total_nonval_callno_used++;
  1974. }
  1975. }
  1976. ao2_unlock(callno_pool);
  1977. return callno_entry;
  1978. }
  1979. static int replace_callno(const void *obj)
  1980. {
  1981. struct callno_entry *callno_entry = (struct callno_entry *) obj;
  1982. /* the callno_pool container is locked here primarily to ensure thread
  1983. * safety of the total_nonval_callno_used check and decrement */
  1984. ao2_lock(callno_pool);
  1985. if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
  1986. total_nonval_callno_used--;
  1987. } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
  1988. ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
  1989. }
  1990. if (callno_entry->callno < TRUNK_CALL_START) {
  1991. ao2_link(callno_pool, callno_entry);
  1992. } else {
  1993. ao2_link(callno_pool_trunk, callno_entry);
  1994. }
  1995. ao2_ref(callno_entry, -1); /* only container ref remains */
  1996. ao2_unlock(callno_pool);
  1997. return 0;
  1998. }
  1999. static int callno_hash(const void *obj, const int flags)
  2000. {
  2001. return abs(ast_random());
  2002. }
  2003. static int create_callno_pools(void)
  2004. {
  2005. uint16_t i;
  2006. if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
  2007. return -1;
  2008. }
  2009. if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
  2010. return -1;
  2011. }
  2012. /* start at 2, 0 and 1 are reserved */
  2013. for (i = 2; i <= IAX_MAX_CALLS; i++) {
  2014. struct callno_entry *callno_entry;
  2015. if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
  2016. return -1;
  2017. }
  2018. callno_entry->callno = i;
  2019. if (i < TRUNK_CALL_START) {
  2020. ao2_link(callno_pool, callno_entry);
  2021. } else {
  2022. ao2_link(callno_pool_trunk, callno_entry);
  2023. }
  2024. ao2_ref(callno_entry, -1);
  2025. }
  2026. return 0;
  2027. }
  2028. /*!
  2029. * \internal
  2030. * \brief Schedules delayed removal of iax2_pvt call number data
  2031. *
  2032. * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
  2033. * avaliable again, and the address from the previous connection must be decremented
  2034. * from the peercnts table. This function schedules these operations to take place.
  2035. */
  2036. static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
  2037. {
  2038. int i;
  2039. struct peercnt *peercnt;
  2040. struct peercnt tmp = {
  2041. .addr = sin->sin_addr.s_addr,
  2042. };
  2043. if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
  2044. /* refcount is incremented with ao2_find. keep that ref for the scheduler */
  2045. ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
  2046. i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
  2047. if (i == -1) {
  2048. ao2_ref(peercnt, -1);
  2049. }
  2050. }
  2051. iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
  2052. }
  2053. /*!
  2054. * \internal
  2055. * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
  2056. *
  2057. * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
  2058. * a new callno.
  2059. */
  2060. static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
  2061. {
  2062. if (frametype != AST_FRAME_IAX) {
  2063. return 0;
  2064. }
  2065. switch (subclass) {
  2066. case IAX_COMMAND_NEW:
  2067. case IAX_COMMAND_REGREQ:
  2068. case IAX_COMMAND_FWDOWNL:
  2069. case IAX_COMMAND_REGREL:
  2070. return 1;
  2071. case IAX_COMMAND_POKE:
  2072. if (!inbound) {
  2073. return 1;
  2074. }
  2075. break;
  2076. }
  2077. return 0;
  2078. }
  2079. /*
  2080. * \note Calling this function while holding another pvt lock can cause a deadlock.
  2081. */
  2082. static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
  2083. {
  2084. int res = 0;
  2085. int x;
  2086. /* this call is calltoken validated as long as it is either NEW_FORCE
  2087. * or NEW_ALLOW_CALLTOKEN_VALIDATED */
  2088. int validated = (new > NEW_ALLOW) ? 1 : 0;
  2089. char host[80];
  2090. if (new <= NEW_ALLOW) {
  2091. if (callno) {
  2092. struct chan_iax2_pvt *pvt;
  2093. struct chan_iax2_pvt tmp_pvt = {
  2094. .callno = dcallno,
  2095. .peercallno = callno,
  2096. .transfercallno = callno,
  2097. /* hack!! */
  2098. .frames_received = check_dcallno,
  2099. };
  2100. memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
  2101. /* this works for finding normal call numbers not involving transfering */
  2102. if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
  2103. if (return_locked) {
  2104. ast_mutex_lock(&iaxsl[pvt->callno]);
  2105. }
  2106. res = pvt->callno;
  2107. ao2_ref(pvt, -1);
  2108. pvt = NULL;
  2109. return res;
  2110. }
  2111. /* this searches for transfer call numbers that might not get caught otherwise */
  2112. memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
  2113. memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
  2114. if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
  2115. if (return_locked) {
  2116. ast_mutex_lock(&iaxsl[pvt->callno]);
  2117. }
  2118. res = pvt->callno;
  2119. ao2_ref(pvt, -1);
  2120. pvt = NULL;
  2121. return res;
  2122. }
  2123. }
  2124. /* This will occur on the first response to a message that we initiated,
  2125. * such as a PING. */
  2126. if (dcallno) {
  2127. ast_mutex_lock(&iaxsl[dcallno]);
  2128. }
  2129. if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
  2130. iaxs[dcallno]->peercallno = callno;
  2131. res = dcallno;
  2132. store_by_peercallno(iaxs[dcallno]);
  2133. if (!res || !return_locked) {
  2134. ast_mutex_unlock(&iaxsl[dcallno]);
  2135. }
  2136. return res;
  2137. }
  2138. if (dcallno) {
  2139. ast_mutex_unlock(&iaxsl[dcallno]);
  2140. }
  2141. #ifdef IAX_OLD_FIND
  2142. /* If we get here, we SHOULD NOT find a call structure for this
  2143. callno; if we do, it means that there is a call structure that
  2144. has a peer callno but did NOT get entered into the hash table,
  2145. which is bad.
  2146. If we find a call structure using this old, slow method, output a log
  2147. message so we'll know about it. After a few months of leaving this in
  2148. place, if we don't hear about people seeing these messages, we can
  2149. remove this code for good.
  2150. */
  2151. for (x = 1; !res && x < maxnontrunkcall; x++) {
  2152. ast_mutex_lock(&iaxsl[x]);
  2153. if (iaxs[x]) {
  2154. /* Look for an exact match */
  2155. if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
  2156. res = x;
  2157. }
  2158. }
  2159. if (!res || !return_locked)
  2160. ast_mutex_unlock(&iaxsl[x]);
  2161. }
  2162. for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
  2163. ast_mutex_lock(&iaxsl[x]);
  2164. if (iaxs[x]) {
  2165. /* Look for an exact match */
  2166. if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
  2167. res = x;
  2168. }
  2169. }
  2170. if (!res || !return_locked)
  2171. ast_mutex_unlock(&iaxsl[x]);
  2172. }
  2173. #endif
  2174. }
  2175. if (!res && (new >= NEW_ALLOW)) {
  2176. struct callno_entry *callno_entry;
  2177. /* It may seem odd that we look through the peer list for a name for
  2178. * this *incoming* call. Well, it is weird. However, users don't
  2179. * have an IP address/port number that we can match against. So,
  2180. * this is just checking for a peer that has that IP/port and
  2181. * assuming that we have a user of the same name. This isn't always
  2182. * correct, but it will be changed if needed after authentication. */
  2183. if (!iax2_getpeername(*sin, host, sizeof(host)))
  2184. snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
  2185. if (peercnt_add(sin)) {
  2186. /* This address has hit its callnumber limit. When the limit
  2187. * is reached, the connection is not added to the peercnts table.*/
  2188. return 0;
  2189. }
  2190. if (!(callno_entry = get_unused_callno(0, validated))) {
  2191. /* since we ran out of space, remove the peercnt
  2192. * entry we added earlier */
  2193. peercnt_remove_by_addr(sin);
  2194. ast_log(LOG_WARNING, "No more space\n");
  2195. return 0;
  2196. }
  2197. x = callno_entry->callno;
  2198. ast_mutex_lock(&iaxsl[x]);
  2199. iaxs[x] = new_iax(sin, host);
  2200. update_max_nontrunk();
  2201. if (iaxs[x]) {
  2202. if (iaxdebug)
  2203. ast_debug(1, "Creating new call structure %d\n", x);
  2204. iaxs[x]->callno_entry = callno_entry;
  2205. iaxs[x]->sockfd = sockfd;
  2206. iaxs[x]->addr.sin_port = sin->sin_port;
  2207. iaxs[x]->addr.sin_family = sin->sin_family;
  2208. iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
  2209. iaxs[x]->peercallno = callno;
  2210. iaxs[x]->callno = x;
  2211. iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
  2212. iaxs[x]->expiry = min_reg_expire;
  2213. iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
  2214. iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
  2215. iaxs[x]->amaflags = amaflags;
  2216. ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
  2217. ast_string_field_set(iaxs[x], accountcode, accountcode);
  2218. ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
  2219. ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
  2220. if (iaxs[x]->peercallno) {
  2221. store_by_peercallno(iaxs[x]);
  2222. }
  2223. } else {
  2224. ast_log(LOG_WARNING, "Out of resources\n");
  2225. ast_mutex_unlock(&iaxsl[x]);
  2226. replace_callno(callno_entry);
  2227. return 0;
  2228. }
  2229. if (!return_locked)
  2230. ast_mutex_unlock(&iaxsl[x]);
  2231. res = x;
  2232. }
  2233. return res;
  2234. }
  2235. static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
  2236. return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
  2237. }
  2238. static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
  2239. return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
  2240. }
  2241. /*!
  2242. * \brief Queue a frame to a call's owning asterisk channel
  2243. *
  2244. * \pre This function assumes that iaxsl[callno] is locked when called.
  2245. *
  2246. * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
  2247. * was valid before calling it, it may no longer be valid after calling it.
  2248. * This function may unlock and lock the mutex associated with this callno,
  2249. * meaning that another thread may grab it and destroy the call.
  2250. */
  2251. static int iax2_queue_frame(int callno, struct ast_frame *f)
  2252. {
  2253. for (;;) {
  2254. if (iaxs[callno] && iaxs[callno]->owner) {
  2255. if (ast_channel_trylock(iaxs[callno]->owner)) {
  2256. /* Avoid deadlock by pausing and trying again */
  2257. DEADLOCK_AVOIDANCE(&iaxsl[callno]);
  2258. } else {
  2259. ast_queue_frame(iaxs[callno]->owner, f);
  2260. ast_channel_unlock(iaxs[callno]->owner);
  2261. break;
  2262. }
  2263. } else
  2264. break;
  2265. }
  2266. return 0;
  2267. }
  2268. /*!
  2269. * \brief Queue a hangup frame on the ast_channel owner
  2270. *
  2271. * This function queues a hangup frame on the owner of the IAX2 pvt struct that
  2272. * is active for the given call number.
  2273. *
  2274. * \pre Assumes lock for callno is already held.
  2275. *
  2276. * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
  2277. * was valid before calling it, it may no longer be valid after calling it.
  2278. * This function may unlock and lock the mutex associated with this callno,
  2279. * meaning that another thread may grab it and destroy the call.
  2280. */
  2281. static int iax2_queue_hangup(int callno)
  2282. {
  2283. for (;;) {
  2284. if (iaxs[callno] && iaxs[callno]->owner) {
  2285. if (ast_channel_trylock(iaxs[callno]->owner)) {
  2286. /* Avoid deadlock by pausing and trying again */
  2287. DEADLOCK_AVOIDANCE(&iaxsl[callno]);
  2288. } else {
  2289. ast_queue_hangup(iaxs[callno]->owner);
  2290. ast_channel_unlock(iaxs[callno]->owner);
  2291. break;
  2292. }
  2293. } else
  2294. break;
  2295. }
  2296. return 0;
  2297. }
  2298. /*!
  2299. * \brief Queue a control frame on the ast_channel owner
  2300. *
  2301. * This function queues a control frame on the owner of the IAX2 pvt struct that
  2302. * is active for the given call number.
  2303. *
  2304. * \pre Assumes lock for callno is already held.
  2305. *
  2306. * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
  2307. * was valid before calling it, it may no longer be valid after calling it.
  2308. * This function may unlock and lock the mutex associated with this callno,
  2309. * meaning that another thread may grab it and destroy the call.
  2310. */
  2311. static int iax2_queue_control_data(int callno,
  2312. enum ast_control_frame_type control, const void *data, size_t datalen)
  2313. {
  2314. for (;;) {
  2315. if (iaxs[callno] && iaxs[callno]->owner) {
  2316. if (ast_channel_trylock(iaxs[callno]->owner)) {
  2317. /* Avoid deadlock by pausing and trying again */
  2318. DEADLOCK_AVOIDANCE(&iaxsl[callno]);
  2319. } else {
  2320. ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
  2321. ast_channel_unlock(iaxs[callno]->owner);
  2322. break;
  2323. }
  2324. } else
  2325. break;
  2326. }
  2327. return 0;
  2328. }
  2329. static void destroy_firmware(struct iax_firmware *cur)
  2330. {
  2331. /* Close firmware */
  2332. if (cur->fwh) {
  2333. munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
  2334. }
  2335. close(cur->fd);
  2336. ast_free(cur);
  2337. }
  2338. static int try_firmware(char *s)
  2339. {
  2340. struct stat stbuf;
  2341. struct iax_firmware *cur = NULL;
  2342. int ifd, fd, res, len, chunk;
  2343. struct ast_iax2_firmware_header *fwh, fwh2;
  2344. struct MD5Context md5;
  2345. unsigned char sum[16], buf[1024];
  2346. char *s2, *last;
  2347. if (!(s2 = alloca(strlen(s) + 100))) {
  2348. ast_log(LOG_WARNING, "Alloca failed!\n");
  2349. return -1;
  2350. }
  2351. last = strrchr(s, '/');
  2352. if (last)
  2353. last++;
  2354. else
  2355. last = s;
  2356. snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
  2357. if ((res = stat(s, &stbuf) < 0)) {
  2358. ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
  2359. return -1;
  2360. }
  2361. /* Make sure it's not a directory */
  2362. if (S_ISDIR(stbuf.st_mode))
  2363. return -1;
  2364. ifd = open(s, O_RDONLY);
  2365. if (ifd < 0) {
  2366. ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
  2367. return -1;
  2368. }
  2369. fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
  2370. if (fd < 0) {
  2371. ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
  2372. close(ifd);
  2373. return -1;
  2374. }
  2375. /* Unlink our newly created file */
  2376. unlink(s2);
  2377. /* Now copy the firmware into it */
  2378. len = stbuf.st_size;
  2379. while(len) {
  2380. chunk = len;
  2381. if (chunk > sizeof(buf))
  2382. chunk = sizeof(buf);
  2383. res = read(ifd, buf, chunk);
  2384. if (res != chunk) {
  2385. ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
  2386. close(ifd);
  2387. close(fd);
  2388. return -1;
  2389. }
  2390. res = write(fd, buf, chunk);
  2391. if (res != chunk) {
  2392. ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
  2393. close(ifd);
  2394. close(fd);
  2395. return -1;
  2396. }
  2397. len -= chunk;
  2398. }
  2399. close(ifd);
  2400. /* Return to the beginning */
  2401. lseek(fd, 0, SEEK_SET);
  2402. if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
  2403. ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
  2404. close(fd);
  2405. return -1;
  2406. }
  2407. if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
  2408. ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
  2409. close(fd);
  2410. return -1;
  2411. }
  2412. if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
  2413. ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
  2414. close(fd);
  2415. return -1;
  2416. }
  2417. if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
  2418. ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
  2419. close(fd);
  2420. return -1;
  2421. }
  2422. fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
  2423. if (fwh == MAP_FAILED) {
  2424. ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
  2425. close(fd);
  2426. return -1;
  2427. }
  2428. MD5Init(&md5);
  2429. MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
  2430. MD5Final(sum, &md5);
  2431. if (memcmp(sum, fwh->chksum, sizeof(sum))) {
  2432. ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
  2433. munmap((void*)fwh, stbuf.st_size);
  2434. close(fd);
  2435. return -1;
  2436. }
  2437. AST_LIST_TRAVERSE(&firmwares, cur, list) {
  2438. if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
  2439. /* Found a candidate */
  2440. if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
  2441. /* The version we have on loaded is older, load this one instead */
  2442. break;
  2443. /* This version is no newer than what we have. Don't worry about it.
  2444. We'll consider it a proper load anyhow though */
  2445. munmap((void*)fwh, stbuf.st_size);
  2446. close(fd);
  2447. return 0;
  2448. }
  2449. }
  2450. if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
  2451. cur->fd = -1;
  2452. AST_LIST_INSERT_TAIL(&firmwares, cur, list);
  2453. }
  2454. if (cur) {
  2455. if (cur->fwh)
  2456. munmap((void*)cur->fwh, cur->mmaplen);
  2457. if (cur->fd > -1)
  2458. close(cur->fd);
  2459. cur->fwh = fwh;
  2460. cur->fd = fd;
  2461. cur->mmaplen = stbuf.st_size;
  2462. cur->dead = 0;
  2463. }
  2464. return 0;
  2465. }
  2466. static int iax_check_version(char *dev)
  2467. {
  2468. int res = 0;
  2469. struct iax_firmware *cur = NULL;
  2470. if (ast_strlen_zero(dev))
  2471. return 0;
  2472. AST_LIST_LOCK(&firmwares);
  2473. AST_LIST_TRAVERSE(&firmwares, cur, list) {
  2474. if (!strcmp(dev, (char *)cur->fwh->devname)) {
  2475. res = ntohs(cur->fwh->version);
  2476. break;
  2477. }
  2478. }
  2479. AST_LIST_UNLOCK(&firmwares);
  2480. return res;
  2481. }
  2482. static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
  2483. {
  2484. int res = -1;
  2485. unsigned int bs = desc & 0xff;
  2486. unsigned int start = (desc >> 8) & 0xffffff;
  2487. unsigned int bytes;
  2488. struct iax_firmware *cur;
  2489. if (ast_strlen_zero((char *)dev) || !bs)
  2490. return -1;
  2491. start *= bs;
  2492. AST_LIST_LOCK(&firmwares);
  2493. AST_LIST_TRAVERSE(&firmwares, cur, list) {
  2494. if (strcmp((char *)dev, (char *)cur->fwh->devname))
  2495. continue;
  2496. iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
  2497. if (start < ntohl(cur->fwh->datalen)) {
  2498. bytes = ntohl(cur->fwh->datalen) - start;
  2499. if (bytes > bs)
  2500. bytes = bs;
  2501. iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
  2502. } else {
  2503. bytes = 0;
  2504. iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
  2505. }
  2506. if (bytes == bs)
  2507. res = 0;
  2508. else
  2509. res = 1;
  2510. break;
  2511. }
  2512. AST_LIST_UNLOCK(&firmwares);
  2513. return res;
  2514. }
  2515. static void reload_firmware(int unload)
  2516. {
  2517. struct iax_firmware *cur = NULL;
  2518. DIR *fwd;
  2519. struct dirent *de;
  2520. char dir[256], fn[256];
  2521. AST_LIST_LOCK(&firmwares);
  2522. /* Mark all as dead */
  2523. AST_LIST_TRAVERSE(&firmwares, cur, list)
  2524. cur->dead = 1;
  2525. /* Now that we have marked them dead... load new ones */
  2526. if (!unload) {
  2527. snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
  2528. fwd = opendir(dir);
  2529. if (fwd) {
  2530. while((de = readdir(fwd))) {
  2531. if (de->d_name[0] != '.') {
  2532. snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
  2533. if (!try_firmware(fn)) {
  2534. ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
  2535. }
  2536. }
  2537. }
  2538. closedir(fwd);
  2539. } else
  2540. ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
  2541. }
  2542. /* Clean up leftovers */
  2543. AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
  2544. if (!cur->dead)
  2545. continue;
  2546. AST_LIST_REMOVE_CURRENT(list);
  2547. destroy_firmware(cur);
  2548. }
  2549. AST_LIST_TRAVERSE_SAFE_END;
  2550. AST_LIST_UNLOCK(&firmwares);
  2551. }
  2552. /*!
  2553. * \note This function assumes that iaxsl[callno] is locked when called.
  2554. *
  2555. * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
  2556. * was valid before calling it, it may no longer be valid after calling it.
  2557. * This function calls iax2_queue_frame(), which may unlock and lock the mutex
  2558. * associated with this callno, meaning that another thread may grab it and destroy the call.
  2559. */
  2560. static int __do_deliver(void *data)
  2561. {
  2562. /* Just deliver the packet by using queueing. This is called by
  2563. the IAX thread with the iaxsl lock held. */
  2564. struct iax_frame *fr = data;
  2565. fr->retrans = -1;
  2566. ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
  2567. if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
  2568. iax2_queue_frame(fr->callno, &fr->af);
  2569. /* Free our iax frame */
  2570. iax2_frame_free(fr);
  2571. /* And don't run again */
  2572. return 0;
  2573. }
  2574. static int handle_error(void)
  2575. {
  2576. /* XXX Ideally we should figure out why an error occurred and then abort those
  2577. rather than continuing to try. Unfortunately, the published interface does
  2578. not seem to work XXX */
  2579. #if 0
  2580. struct sockaddr_in *sin;
  2581. int res;
  2582. struct msghdr m;
  2583. struct sock_extended_err e;
  2584. m.msg_name = NULL;
  2585. m.msg_namelen = 0;
  2586. m.msg_iov = NULL;
  2587. m.msg_control = &e;
  2588. m.msg_controllen = sizeof(e);
  2589. m.msg_flags = 0;
  2590. res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
  2591. if (res < 0)
  2592. ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
  2593. else {
  2594. if (m.msg_controllen) {
  2595. sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
  2596. if (sin)
  2597. ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
  2598. else
  2599. ast_log(LOG_WARNING, "No address detected??\n");
  2600. } else {
  2601. ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
  2602. }
  2603. }
  2604. #endif
  2605. return 0;
  2606. }
  2607. static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
  2608. {
  2609. int res;
  2610. res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
  2611. sizeof(*sin));
  2612. if (res < 0) {
  2613. ast_debug(1, "Received error: %s\n", strerror(errno));
  2614. handle_error();
  2615. } else
  2616. res = 0;
  2617. return res;
  2618. }
  2619. static int send_packet(struct iax_frame *f)
  2620. {
  2621. int res;
  2622. int callno = f->callno;
  2623. /* Don't send if there was an error, but return error instead */
  2624. if (!callno || !iaxs[callno] || iaxs[callno]->error)
  2625. return -1;
  2626. /* Called with iaxsl held */
  2627. if (iaxdebug)
  2628. ast_debug(3, "Sending %d 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));
  2629. if (f->transfer) {
  2630. if (iaxdebug)
  2631. iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
  2632. res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
  2633. sizeof(iaxs[callno]->transfer));
  2634. } else {
  2635. if (iaxdebug)
  2636. iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
  2637. res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
  2638. sizeof(iaxs[callno]->addr));
  2639. }
  2640. if (res < 0) {
  2641. if (iaxdebug)
  2642. ast_debug(1, "Received error: %s\n", strerror(errno));
  2643. handle_error();
  2644. } else
  2645. res = 0;
  2646. return res;
  2647. }
  2648. /*!
  2649. * \note Since this function calls iax2_queue_hangup(), the pvt struct
  2650. * for the given call number may disappear during its execution.
  2651. */
  2652. static int iax2_predestroy(int callno)
  2653. {
  2654. struct ast_channel *c = NULL;
  2655. struct chan_iax2_pvt *pvt = iaxs[callno];
  2656. if (!pvt)
  2657. return -1;
  2658. if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
  2659. iax2_destroy_helper(pvt);
  2660. ast_set_flag(pvt, IAX_ALREADYGONE);
  2661. }
  2662. if ((c = pvt->owner)) {
  2663. c->tech_pvt = NULL;
  2664. iax2_queue_hangup(callno);
  2665. pvt->owner = NULL;
  2666. ast_module_unref(ast_module_info->self);
  2667. }
  2668. return 0;
  2669. }
  2670. static void iax2_destroy(int callno)
  2671. {
  2672. struct chan_iax2_pvt *pvt = NULL;
  2673. struct ast_channel *owner = NULL;
  2674. retry:
  2675. pvt = iaxs[callno];
  2676. owner = pvt ? pvt->owner : NULL;
  2677. if (owner) {
  2678. if (ast_channel_trylock(owner)) {
  2679. ast_debug(3, "Avoiding IAX destroy deadlock\n");
  2680. ast_mutex_unlock(&iaxsl[callno]);
  2681. usleep(1);
  2682. ast_mutex_lock(&iaxsl[callno]);
  2683. goto retry;
  2684. }
  2685. }
  2686. if (!owner) {
  2687. iaxs[callno] = NULL;
  2688. }
  2689. if (pvt) {
  2690. if (!owner) {
  2691. pvt->owner = NULL;
  2692. } else {
  2693. /* If there's an owner, prod it to give up */
  2694. /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
  2695. * because we already hold the owner channel lock. */
  2696. ast_queue_hangup(owner);
  2697. }
  2698. if (pvt->peercallno) {
  2699. remove_by_peercallno(pvt);
  2700. }
  2701. if (pvt->transfercallno) {
  2702. remove_by_transfercallno(pvt);
  2703. }
  2704. if (!owner) {
  2705. ao2_ref(pvt, -1);
  2706. pvt = NULL;
  2707. }
  2708. }
  2709. if (owner) {
  2710. ast_channel_unlock(owner);
  2711. }
  2712. if (callno & 0x4000) {
  2713. update_max_trunk();
  2714. }
  2715. }
  2716. static int update_packet(struct iax_frame *f)
  2717. {
  2718. /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
  2719. struct ast_iax2_full_hdr *fh = f->data;
  2720. struct ast_frame af;
  2721. /* if frame is encrypted. decrypt before updating it. */
  2722. if (f->encmethods) {
  2723. decode_frame(&f->mydcx, fh, &af, &f->datalen);
  2724. }
  2725. /* Mark this as a retransmission */
  2726. fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
  2727. /* Update iseqno */
  2728. f->iseqno = iaxs[f->callno]->iseqno;
  2729. fh->iseqno = f->iseqno;
  2730. /* Now re-encrypt the frame */
  2731. if (f->encmethods) {
  2732. /* since this is a retransmit frame, create a new random padding
  2733. * before re-encrypting. */
  2734. build_rand_pad(f->semirand, sizeof(f->semirand));
  2735. encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
  2736. }
  2737. return 0;
  2738. }
  2739. static int attempt_transmit(const void *data);
  2740. static void __attempt_transmit(const void *data)
  2741. {
  2742. /* Attempt to transmit the frame to the remote peer...
  2743. Called without iaxsl held. */
  2744. struct iax_frame *f = (struct iax_frame *)data;
  2745. int freeme = 0;
  2746. int callno = f->callno;
  2747. /* Make sure this call is still active */
  2748. if (callno)
  2749. ast_mutex_lock(&iaxsl[callno]);
  2750. if (callno && iaxs[callno]) {
  2751. if ((f->retries < 0) /* Already ACK'd */ ||
  2752. (f->retries >= max_retries) /* Too many attempts */) {
  2753. /* Record an error if we've transmitted too many times */
  2754. if (f->retries >= max_retries) {
  2755. if (f->transfer) {
  2756. /* Transfer timeout */
  2757. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
  2758. } else if (f->final) {
  2759. if (f->final)
  2760. iax2_destroy(callno);
  2761. } else {
  2762. if (iaxs[callno]->owner)
  2763. ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
  2764. iaxs[callno]->error = ETIMEDOUT;
  2765. if (iaxs[callno]->owner) {
  2766. struct ast_frame fr = { 0, };
  2767. /* Hangup the fd */
  2768. fr.frametype = AST_FRAME_CONTROL;
  2769. fr.subclass = AST_CONTROL_HANGUP;
  2770. iax2_queue_frame(callno, &fr); /* XXX */
  2771. /* Remember, owner could disappear */
  2772. if (iaxs[callno] && iaxs[callno]->owner)
  2773. iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
  2774. } else {
  2775. if (iaxs[callno]->reg) {
  2776. memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
  2777. iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
  2778. iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
  2779. }
  2780. iax2_destroy(callno);
  2781. }
  2782. }
  2783. }
  2784. freeme = 1;
  2785. } else {
  2786. /* Update it if it needs it */
  2787. update_packet(f);
  2788. /* Attempt transmission */
  2789. send_packet(f);
  2790. f->retries++;
  2791. /* Try again later after 10 times as long */
  2792. f->retrytime *= 10;
  2793. if (f->retrytime > MAX_RETRY_TIME)
  2794. f->retrytime = MAX_RETRY_TIME;
  2795. /* Transfer messages max out at one second */
  2796. if (f->transfer && (f->retrytime > 1000))
  2797. f->retrytime = 1000;
  2798. f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
  2799. }
  2800. } else {
  2801. /* Make sure it gets freed */
  2802. f->retries = -1;
  2803. freeme = 1;
  2804. }
  2805. if (callno)
  2806. ast_mutex_unlock(&iaxsl[callno]);
  2807. /* Do not try again */
  2808. if (freeme) {
  2809. /* Don't attempt delivery, just remove it from the queue */
  2810. AST_LIST_LOCK(&frame_queue);
  2811. AST_LIST_REMOVE(&frame_queue, f, list);
  2812. AST_LIST_UNLOCK(&frame_queue);
  2813. f->retrans = -1; /* this is safe because this is the scheduled function */
  2814. /* Free the IAX frame */
  2815. iax2_frame_free(f);
  2816. }
  2817. }
  2818. static int attempt_transmit(const void *data)
  2819. {
  2820. #ifdef SCHED_MULTITHREADED
  2821. if (schedule_action(__attempt_transmit, data))
  2822. #endif
  2823. __attempt_transmit(data);
  2824. return 0;
  2825. }
  2826. static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2827. {
  2828. struct iax2_peer *peer = NULL;
  2829. struct iax2_user *user = NULL;
  2830. switch (cmd) {
  2831. case CLI_INIT:
  2832. e->command = "iax2 prune realtime";
  2833. e->usage =
  2834. "Usage: iax2 prune realtime [<peername>|all]\n"
  2835. " Prunes object(s) from the cache\n";
  2836. return NULL;
  2837. case CLI_GENERATE:
  2838. return complete_iax2_show_peer(a->line, a->word, a->pos, a->n);
  2839. }
  2840. if (a->argc != 4)
  2841. return CLI_SHOWUSAGE;
  2842. if (!strcmp(a->argv[3], "all")) {
  2843. prune_users();
  2844. prune_peers();
  2845. ast_cli(a->fd, "Cache flushed successfully.\n");
  2846. return CLI_SUCCESS;
  2847. }
  2848. peer = find_peer(a->argv[3], 0);
  2849. user = find_user(a->argv[3]);
  2850. if (peer || user) {
  2851. if (peer) {
  2852. if (ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
  2853. ast_set_flag(peer, IAX_RTAUTOCLEAR);
  2854. expire_registry(peer_ref(peer));
  2855. ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
  2856. } else {
  2857. ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
  2858. }
  2859. peer_unref(peer);
  2860. }
  2861. if (user) {
  2862. if (ast_test_flag(user, IAX_RTCACHEFRIENDS)) {
  2863. ast_set_flag(user, IAX_RTAUTOCLEAR);
  2864. ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
  2865. } else {
  2866. ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
  2867. }
  2868. ao2_unlink(users,user);
  2869. user_unref(user);
  2870. }
  2871. } else {
  2872. ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
  2873. }
  2874. return CLI_SUCCESS;
  2875. }
  2876. static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2877. {
  2878. switch (cmd) {
  2879. case CLI_INIT:
  2880. e->command = "iax2 test losspct";
  2881. e->usage =
  2882. "Usage: iax2 test losspct <percentage>\n"
  2883. " For testing, throws away <percentage> percent of incoming packets\n";
  2884. return NULL;
  2885. case CLI_GENERATE:
  2886. return NULL;
  2887. }
  2888. if (a->argc != 4)
  2889. return CLI_SHOWUSAGE;
  2890. test_losspct = atoi(a->argv[3]);
  2891. return CLI_SUCCESS;
  2892. }
  2893. #ifdef IAXTESTS
  2894. static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2895. {
  2896. switch (cmd) {
  2897. case CLI_INIT:
  2898. e->command = "iax2 test late";
  2899. e->usage =
  2900. "Usage: iax2 test late <ms>\n"
  2901. " For testing, count the next frame as <ms> ms late\n";
  2902. return NULL;
  2903. case CLI_GENERATE:
  2904. return NULL;
  2905. }
  2906. if (a->argc != 4)
  2907. return CLI_SHOWUSAGE;
  2908. test_late = atoi(a->argv[3]);
  2909. return CLI_SUCCESS;
  2910. }
  2911. static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2912. {
  2913. switch (cmd) {
  2914. case CLI_INIT:
  2915. e->command = "iax2 test resync";
  2916. e->usage =
  2917. "Usage: iax2 test resync <ms>\n"
  2918. " For testing, adjust all future frames by <ms> ms\n";
  2919. return NULL;
  2920. case CLI_GENERATE:
  2921. return NULL;
  2922. }
  2923. if (a->argc != 4)
  2924. return CLI_SHOWUSAGE;
  2925. test_resync = atoi(a->argv[3]);
  2926. return CLI_SUCCESS;
  2927. }
  2928. static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2929. {
  2930. switch (cmd) {
  2931. case CLI_INIT:
  2932. e->command = "iax2 test jitter";
  2933. e->usage =
  2934. "Usage: iax2 test jitter <ms> <pct>\n"
  2935. " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
  2936. " percentage of packets. If <pct> is not specified, adds\n"
  2937. " jitter to all packets.\n";
  2938. return NULL;
  2939. case CLI_GENERATE:
  2940. return NULL;
  2941. }
  2942. if (a->argc < 4 || a->argc > 5)
  2943. return CLI_SHOWUSAGE;
  2944. test_jit = atoi(a->argv[3]);
  2945. if (a->argc == 5)
  2946. test_jitpct = atoi(a->argv[4]);
  2947. return CLI_SUCCESS;
  2948. }
  2949. #endif /* IAXTESTS */
  2950. /*! \brief peer_status: Report Peer status in character string */
  2951. /* returns 1 if peer is online, -1 if unmonitored */
  2952. static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
  2953. {
  2954. int res = 0;
  2955. if (peer->maxms) {
  2956. if (peer->lastms < 0) {
  2957. ast_copy_string(status, "UNREACHABLE", statuslen);
  2958. } else if (peer->lastms > peer->maxms) {
  2959. snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
  2960. res = 1;
  2961. } else if (peer->lastms) {
  2962. snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
  2963. res = 1;
  2964. } else {
  2965. ast_copy_string(status, "UNKNOWN", statuslen);
  2966. }
  2967. } else {
  2968. ast_copy_string(status, "Unmonitored", statuslen);
  2969. res = -1;
  2970. }
  2971. return res;
  2972. }
  2973. /*! \brief Show one peer in detail */
  2974. static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2975. {
  2976. char status[30];
  2977. char cbuf[256];
  2978. struct iax2_peer *peer;
  2979. char codec_buf[512];
  2980. int x = 0, codec = 0, load_realtime = 0;
  2981. switch (cmd) {
  2982. case CLI_INIT:
  2983. e->command = "iax2 show peer";
  2984. e->usage =
  2985. "Usage: iax2 show peer <name>\n"
  2986. " Display details on specific IAX peer\n";
  2987. return NULL;
  2988. case CLI_GENERATE:
  2989. return complete_iax2_show_peer(a->line, a->word, a->pos, a->n);
  2990. }
  2991. if (a->argc < 4)
  2992. return CLI_SHOWUSAGE;
  2993. load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
  2994. peer = find_peer(a->argv[3], load_realtime);
  2995. if (peer) {
  2996. ast_cli(a->fd, "\n\n");
  2997. ast_cli(a->fd, " * Name : %s\n", peer->name);
  2998. ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
  2999. ast_cli(a->fd, " Context : %s\n", peer->context);
  3000. ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
  3001. ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes" : "No");
  3002. ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
  3003. ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
  3004. ast_cli(a->fd, " Trunk : %s\n", ast_test_flag(peer, IAX_TRUNK) ? "Yes" : "No");
  3005. ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
  3006. ast_cli(a->fd, " Expire : %d\n", peer->expire);
  3007. ast_cli(a->fd, " ACL : %s\n", (peer->ha ? "Yes" : "No"));
  3008. 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));
  3009. ast_cli(a->fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
  3010. ast_cli(a->fd, " Username : %s\n", peer->username);
  3011. ast_cli(a->fd, " Codecs : ");
  3012. ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
  3013. ast_cli(a->fd, "%s\n", codec_buf);
  3014. ast_cli(a->fd, " Codec Order : (");
  3015. for(x = 0; x < 32 ; x++) {
  3016. codec = ast_codec_pref_index(&peer->prefs,x);
  3017. if(!codec)
  3018. break;
  3019. ast_cli(a->fd, "%s", ast_getformatname(codec));
  3020. if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
  3021. ast_cli(a->fd, "|");
  3022. }
  3023. if (!x)
  3024. ast_cli(a->fd, "none");
  3025. ast_cli(a->fd, ")\n");
  3026. ast_cli(a->fd, " Status : ");
  3027. peer_status(peer, status, sizeof(status));
  3028. ast_cli(a->fd, "%s\n",status);
  3029. 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");
  3030. ast_cli(a->fd, "\n");
  3031. peer_unref(peer);
  3032. } else {
  3033. ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
  3034. ast_cli(a->fd, "\n");
  3035. }
  3036. return CLI_SUCCESS;
  3037. }
  3038. static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
  3039. {
  3040. int which = 0;
  3041. struct iax2_peer *peer;
  3042. char *res = NULL;
  3043. int wordlen = strlen(word);
  3044. struct ao2_iterator i;
  3045. /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
  3046. if (pos != 3)
  3047. return NULL;
  3048. i = ao2_iterator_init(peers, 0);
  3049. while ((peer = ao2_iterator_next(&i))) {
  3050. if (!strncasecmp(peer->name, word, wordlen) && ++which > state) {
  3051. res = ast_strdup(peer->name);
  3052. peer_unref(peer);
  3053. break;
  3054. }
  3055. peer_unref(peer);
  3056. }
  3057. ao2_iterator_destroy(&i);
  3058. return res;
  3059. }
  3060. static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3061. {
  3062. struct iax_frame *cur;
  3063. int cnt = 0, dead = 0, final = 0;
  3064. switch (cmd) {
  3065. case CLI_INIT:
  3066. e->command = "iax2 show stats";
  3067. e->usage =
  3068. "Usage: iax2 show stats\n"
  3069. " Display statistics on IAX channel driver.\n";
  3070. return NULL;
  3071. case CLI_GENERATE:
  3072. return NULL;
  3073. }
  3074. if (a->argc != 3)
  3075. return CLI_SHOWUSAGE;
  3076. AST_LIST_LOCK(&frame_queue);
  3077. AST_LIST_TRAVERSE(&frame_queue, cur, list) {
  3078. if (cur->retries < 0)
  3079. dead++;
  3080. if (cur->final)
  3081. final++;
  3082. cnt++;
  3083. }
  3084. AST_LIST_UNLOCK(&frame_queue);
  3085. ast_cli(a->fd, " IAX Statistics\n");
  3086. ast_cli(a->fd, "---------------------\n");
  3087. ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
  3088. ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
  3089. trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
  3090. ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
  3091. trunk_timed = trunk_untimed = 0;
  3092. if (trunk_maxmtu > trunk_nmaxmtu)
  3093. trunk_nmaxmtu = trunk_maxmtu;
  3094. return CLI_SUCCESS;
  3095. }
  3096. /*! \brief Set trunk MTU from CLI */
  3097. static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3098. {
  3099. int mtuv;
  3100. switch (cmd) {
  3101. case CLI_INIT:
  3102. e->command = "iax2 set mtu";
  3103. e->usage =
  3104. "Usage: iax2 set mtu <value>\n"
  3105. " Set the system-wide IAX IP mtu to <value> bytes net or\n"
  3106. " zero to disable. Disabling means that the operating system\n"
  3107. " must handle fragmentation of UDP packets when the IAX2 trunk\n"
  3108. " packet exceeds the UDP payload size. This is substantially\n"
  3109. " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
  3110. " greater for G.711 samples.\n";
  3111. return NULL;
  3112. case CLI_GENERATE:
  3113. return NULL;
  3114. }
  3115. if (a->argc != 4)
  3116. return CLI_SHOWUSAGE;
  3117. if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
  3118. mtuv = MAX_TRUNK_MTU;
  3119. else
  3120. mtuv = atoi(a->argv[3]);
  3121. if (mtuv == 0) {
  3122. ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
  3123. global_max_trunk_mtu = 0;
  3124. return CLI_SUCCESS;
  3125. }
  3126. if (mtuv < 172 || mtuv > 4000) {
  3127. ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
  3128. return CLI_SHOWUSAGE;
  3129. }
  3130. ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
  3131. global_max_trunk_mtu = mtuv;
  3132. return CLI_SUCCESS;
  3133. }
  3134. static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3135. {
  3136. struct iax2_dpcache *dp = NULL;
  3137. char tmp[1024], *pc = NULL;
  3138. int s, x, y;
  3139. struct timeval tv = ast_tvnow();
  3140. switch (cmd) {
  3141. case CLI_INIT:
  3142. e->command = "iax2 show cache";
  3143. e->usage =
  3144. "Usage: iax2 show cache\n"
  3145. " Display currently cached IAX Dialplan results.\n";
  3146. return NULL;
  3147. case CLI_GENERATE:
  3148. return NULL;
  3149. }
  3150. AST_LIST_LOCK(&dpcache);
  3151. ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
  3152. AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
  3153. s = dp->expiry.tv_sec - tv.tv_sec;
  3154. tmp[0] = '\0';
  3155. if (dp->flags & CACHE_FLAG_EXISTS)
  3156. strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
  3157. if (dp->flags & CACHE_FLAG_NONEXISTENT)
  3158. strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
  3159. if (dp->flags & CACHE_FLAG_CANEXIST)
  3160. strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
  3161. if (dp->flags & CACHE_FLAG_PENDING)
  3162. strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
  3163. if (dp->flags & CACHE_FLAG_TIMEOUT)
  3164. strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
  3165. if (dp->flags & CACHE_FLAG_TRANSMITTED)
  3166. strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
  3167. if (dp->flags & CACHE_FLAG_MATCHMORE)
  3168. strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
  3169. if (dp->flags & CACHE_FLAG_UNKNOWN)
  3170. strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
  3171. /* Trim trailing pipe */
  3172. if (!ast_strlen_zero(tmp)) {
  3173. tmp[strlen(tmp) - 1] = '\0';
  3174. } else {
  3175. ast_copy_string(tmp, "(none)", sizeof(tmp));
  3176. }
  3177. y = 0;
  3178. pc = strchr(dp->peercontext, '@');
  3179. if (!pc) {
  3180. pc = dp->peercontext;
  3181. } else {
  3182. pc++;
  3183. }
  3184. for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
  3185. if (dp->waiters[x] > -1)
  3186. y++;
  3187. }
  3188. if (s > 0) {
  3189. ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
  3190. } else {
  3191. ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
  3192. }
  3193. }
  3194. AST_LIST_UNLOCK(&dpcache);
  3195. return CLI_SUCCESS;
  3196. }
  3197. static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
  3198. static void unwrap_timestamp(struct iax_frame *fr)
  3199. {
  3200. /* Video mini frames only encode the lower 15 bits of the session
  3201. * timestamp, but other frame types (e.g. audio) encode 16 bits. */
  3202. const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
  3203. const int lower_mask = (1 << ts_shift) - 1;
  3204. const int upper_mask = ~lower_mask;
  3205. const int last_upper = iaxs[fr->callno]->last & upper_mask;
  3206. if ( (fr->ts & upper_mask) == last_upper ) {
  3207. const int x = fr->ts - iaxs[fr->callno]->last;
  3208. const int threshold = (ts_shift == 15) ? 25000 : 50000;
  3209. if (x < -threshold) {
  3210. /* Sudden big jump backwards in timestamp:
  3211. What likely happened here is that miniframe timestamp has circled but we haven't
  3212. gotten the update from the main packet. We'll just pretend that we did, and
  3213. update the timestamp appropriately. */
  3214. fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
  3215. if (iaxdebug)
  3216. ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
  3217. } else if (x > threshold) {
  3218. /* Sudden apparent big jump forwards in timestamp:
  3219. What's likely happened is this is an old miniframe belonging to the previous
  3220. top 15 or 16-bit timestamp that has turned up out of order.
  3221. Adjust the timestamp appropriately. */
  3222. fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
  3223. if (iaxdebug)
  3224. ast_debug(1, "schedule_delivery: pushed back timestamp\n");
  3225. }
  3226. }
  3227. }
  3228. static int get_from_jb(const void *p);
  3229. static void update_jbsched(struct chan_iax2_pvt *pvt)
  3230. {
  3231. int when;
  3232. when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
  3233. when = jb_next(pvt->jb) - when;
  3234. if (when <= 0) {
  3235. /* XXX should really just empty until when > 0.. */
  3236. when = 1;
  3237. }
  3238. pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
  3239. CALLNO_TO_PTR(pvt->callno));
  3240. }
  3241. static void __get_from_jb(const void *p)
  3242. {
  3243. int callno = PTR_TO_CALLNO(p);
  3244. struct chan_iax2_pvt *pvt = NULL;
  3245. struct iax_frame *fr;
  3246. jb_frame frame;
  3247. int ret;
  3248. long now;
  3249. long next;
  3250. struct timeval tv = ast_tvnow();
  3251. /* Make sure we have a valid private structure before going on */
  3252. ast_mutex_lock(&iaxsl[callno]);
  3253. pvt = iaxs[callno];
  3254. if (!pvt) {
  3255. /* No go! */
  3256. ast_mutex_unlock(&iaxsl[callno]);
  3257. return;
  3258. }
  3259. pvt->jbid = -1;
  3260. /* round up a millisecond since ast_sched_runq does; */
  3261. /* prevents us from spinning while waiting for our now */
  3262. /* to catch up with runq's now */
  3263. tv.tv_usec += 1000;
  3264. now = ast_tvdiff_ms(tv, pvt->rxcore);
  3265. if(now >= (next = jb_next(pvt->jb))) {
  3266. ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
  3267. switch(ret) {
  3268. case JB_OK:
  3269. fr = frame.data;
  3270. __do_deliver(fr);
  3271. /* __do_deliver() can cause the call to disappear */
  3272. pvt = iaxs[callno];
  3273. break;
  3274. case JB_INTERP:
  3275. {
  3276. struct ast_frame af = { 0, };
  3277. /* create an interpolation frame */
  3278. af.frametype = AST_FRAME_VOICE;
  3279. af.subclass = pvt->voiceformat;
  3280. af.samples = frame.ms * (ast_format_rate(pvt->voiceformat) / 1000);
  3281. af.src = "IAX2 JB interpolation";
  3282. af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
  3283. af.offset = AST_FRIENDLY_OFFSET;
  3284. /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
  3285. * which we'd need to malloc, and then it would free it. That seems like a drag */
  3286. if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) {
  3287. iax2_queue_frame(callno, &af);
  3288. /* iax2_queue_frame() could cause the call to disappear */
  3289. pvt = iaxs[callno];
  3290. }
  3291. }
  3292. break;
  3293. case JB_DROP:
  3294. iax2_frame_free(frame.data);
  3295. break;
  3296. case JB_NOFRAME:
  3297. case JB_EMPTY:
  3298. /* do nothing */
  3299. break;
  3300. default:
  3301. /* shouldn't happen */
  3302. break;
  3303. }
  3304. }
  3305. if (pvt)
  3306. update_jbsched(pvt);
  3307. ast_mutex_unlock(&iaxsl[callno]);
  3308. }
  3309. static int get_from_jb(const void *data)
  3310. {
  3311. #ifdef SCHED_MULTITHREADED
  3312. if (schedule_action(__get_from_jb, data))
  3313. #endif
  3314. __get_from_jb(data);
  3315. return 0;
  3316. }
  3317. /*!
  3318. * \note This function assumes fr->callno is locked
  3319. *
  3320. * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
  3321. * was valid before calling it, it may no longer be valid after calling it.
  3322. */
  3323. static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
  3324. {
  3325. int type, len;
  3326. int ret;
  3327. int needfree = 0;
  3328. struct ast_channel *owner = NULL;
  3329. struct ast_channel *bridge = NULL;
  3330. /* Attempt to recover wrapped timestamps */
  3331. unwrap_timestamp(fr);
  3332. /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
  3333. if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
  3334. fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
  3335. else {
  3336. #if 0
  3337. ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
  3338. #endif
  3339. fr->af.delivery = ast_tv(0,0);
  3340. }
  3341. type = JB_TYPE_CONTROL;
  3342. len = 0;
  3343. if(fr->af.frametype == AST_FRAME_VOICE) {
  3344. type = JB_TYPE_VOICE;
  3345. len = ast_codec_get_samples(&fr->af) / (ast_format_rate(fr->af.subclass) / 1000);
  3346. } else if(fr->af.frametype == AST_FRAME_CNG) {
  3347. type = JB_TYPE_SILENCE;
  3348. }
  3349. if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
  3350. if (tsout)
  3351. *tsout = fr->ts;
  3352. __do_deliver(fr);
  3353. return -1;
  3354. }
  3355. if ((owner = iaxs[fr->callno]->owner))
  3356. bridge = ast_bridged_channel(owner);
  3357. /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
  3358. * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
  3359. if ( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
  3360. jb_frame frame;
  3361. /* deliver any frames in the jb */
  3362. while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
  3363. __do_deliver(frame.data);
  3364. /* __do_deliver() can make the call disappear */
  3365. if (!iaxs[fr->callno])
  3366. return -1;
  3367. }
  3368. jb_reset(iaxs[fr->callno]->jb);
  3369. AST_SCHED_DEL(sched, iaxs[fr->callno]->jbid);
  3370. /* deliver this frame now */
  3371. if (tsout)
  3372. *tsout = fr->ts;
  3373. __do_deliver(fr);
  3374. return -1;
  3375. }
  3376. /* insert into jitterbuffer */
  3377. /* TODO: Perhaps we could act immediately if it's not droppable and late */
  3378. ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
  3379. calc_rxstamp(iaxs[fr->callno],fr->ts));
  3380. if (ret == JB_DROP) {
  3381. needfree++;
  3382. } else if (ret == JB_SCHED) {
  3383. update_jbsched(iaxs[fr->callno]);
  3384. }
  3385. if (tsout)
  3386. *tsout = fr->ts;
  3387. if (needfree) {
  3388. /* Free our iax frame */
  3389. iax2_frame_free(fr);
  3390. return -1;
  3391. }
  3392. return 0;
  3393. }
  3394. static int iax2_transmit(struct iax_frame *fr)
  3395. {
  3396. /* Lock the queue and place this packet at the end */
  3397. /* By setting this to 0, the network thread will send it for us, and
  3398. queue retransmission if necessary */
  3399. fr->sentyet = 0;
  3400. AST_LIST_LOCK(&frame_queue);
  3401. AST_LIST_INSERT_TAIL(&frame_queue, fr, list);
  3402. AST_LIST_UNLOCK(&frame_queue);
  3403. /* Wake up the network and scheduler thread */
  3404. if (netthreadid != AST_PTHREADT_NULL)
  3405. pthread_kill(netthreadid, SIGURG);
  3406. signal_condition(&sched_lock, &sched_cond);
  3407. return 0;
  3408. }
  3409. static int iax2_digit_begin(struct ast_channel *c, char digit)
  3410. {
  3411. return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
  3412. }
  3413. static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
  3414. {
  3415. return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
  3416. }
  3417. static int iax2_sendtext(struct ast_channel *c, const char *text)
  3418. {
  3419. return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
  3420. 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
  3421. }
  3422. static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
  3423. {
  3424. return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
  3425. }
  3426. static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
  3427. {
  3428. return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
  3429. }
  3430. static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
  3431. {
  3432. unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
  3433. ast_mutex_lock(&iaxsl[callno]);
  3434. if (iaxs[callno])
  3435. iaxs[callno]->owner = newchan;
  3436. else
  3437. ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
  3438. ast_mutex_unlock(&iaxsl[callno]);
  3439. return 0;
  3440. }
  3441. /*!
  3442. * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
  3443. * so do not call this with a pvt lock held.
  3444. */
  3445. static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
  3446. {
  3447. struct ast_variable *var = NULL;
  3448. struct ast_variable *tmp;
  3449. struct iax2_peer *peer=NULL;
  3450. time_t regseconds = 0, nowtime;
  3451. int dynamic=0;
  3452. if (peername) {
  3453. var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", NULL);
  3454. if (!var && sin)
  3455. var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
  3456. } else if (sin) {
  3457. char porta[25];
  3458. sprintf(porta, "%d", ntohs(sin->sin_port));
  3459. var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
  3460. if (var) {
  3461. /* We'll need the peer name in order to build the structure! */
  3462. for (tmp = var; tmp; tmp = tmp->next) {
  3463. if (!strcasecmp(tmp->name, "name"))
  3464. peername = tmp->value;
  3465. }
  3466. }
  3467. }
  3468. if (!var && peername) { /* Last ditch effort */
  3469. var = ast_load_realtime("iaxpeers", "name", peername, NULL);
  3470. /*!\note
  3471. * If this one loaded something, then we need to ensure that the host
  3472. * field matched. The only reason why we can't have this as a criteria
  3473. * is because we only have the IP address and the host field might be
  3474. * set as a name (and the reverse PTR might not match).
  3475. */
  3476. if (var && sin) {
  3477. for (tmp = var; tmp; tmp = tmp->next) {
  3478. if (!strcasecmp(tmp->name, "host")) {
  3479. struct ast_hostent ahp;
  3480. struct hostent *hp;
  3481. if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
  3482. /* No match */
  3483. ast_variables_destroy(var);
  3484. var = NULL;
  3485. }
  3486. break;
  3487. }
  3488. }
  3489. }
  3490. }
  3491. if (!var)
  3492. return NULL;
  3493. peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
  3494. if (!peer) {
  3495. ast_variables_destroy(var);
  3496. return NULL;
  3497. }
  3498. for (tmp = var; tmp; tmp = tmp->next) {
  3499. /* Make sure it's not a user only... */
  3500. if (!strcasecmp(tmp->name, "type")) {
  3501. if (strcasecmp(tmp->value, "friend") &&
  3502. strcasecmp(tmp->value, "peer")) {
  3503. /* Whoops, we weren't supposed to exist! */
  3504. peer = peer_unref(peer);
  3505. break;
  3506. }
  3507. } else if (!strcasecmp(tmp->name, "regseconds")) {
  3508. ast_get_time_t(tmp->value, &regseconds, 0, NULL);
  3509. } else if (!strcasecmp(tmp->name, "ipaddr")) {
  3510. inet_aton(tmp->value, &(peer->addr.sin_addr));
  3511. } else if (!strcasecmp(tmp->name, "port")) {
  3512. peer->addr.sin_port = htons(atoi(tmp->value));
  3513. } else if (!strcasecmp(tmp->name, "host")) {
  3514. if (!strcasecmp(tmp->value, "dynamic"))
  3515. dynamic = 1;
  3516. }
  3517. }
  3518. ast_variables_destroy(var);
  3519. if (!peer)
  3520. return NULL;
  3521. if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
  3522. ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
  3523. if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
  3524. if (peer->expire > -1) {
  3525. if (!ast_sched_del(sched, peer->expire)) {
  3526. peer->expire = -1;
  3527. peer_unref(peer);
  3528. }
  3529. }
  3530. peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
  3531. if (peer->expire == -1)
  3532. peer_unref(peer);
  3533. }
  3534. ao2_link(peers, peer);
  3535. if (ast_test_flag(peer, IAX_DYNAMIC))
  3536. reg_source_db(peer);
  3537. } else {
  3538. ast_set_flag(peer, IAX_TEMPONLY);
  3539. }
  3540. if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
  3541. time(&nowtime);
  3542. if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
  3543. memset(&peer->addr, 0, sizeof(peer->addr));
  3544. realtime_update_peer(peer->name, &peer->addr, 0);
  3545. ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
  3546. peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
  3547. }
  3548. else {
  3549. ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
  3550. peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
  3551. }
  3552. }
  3553. return peer;
  3554. }
  3555. static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
  3556. {
  3557. struct ast_variable *var;
  3558. struct ast_variable *tmp;
  3559. struct iax2_user *user=NULL;
  3560. var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", NULL);
  3561. if (!var)
  3562. var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), NULL);
  3563. if (!var && sin) {
  3564. char porta[6];
  3565. snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
  3566. var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
  3567. if (!var)
  3568. var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
  3569. }
  3570. if (!var) { /* Last ditch effort */
  3571. var = ast_load_realtime("iaxusers", "name", username, NULL);
  3572. /*!\note
  3573. * If this one loaded something, then we need to ensure that the host
  3574. * field matched. The only reason why we can't have this as a criteria
  3575. * is because we only have the IP address and the host field might be
  3576. * set as a name (and the reverse PTR might not match).
  3577. */
  3578. if (var) {
  3579. for (tmp = var; tmp; tmp = tmp->next) {
  3580. if (!strcasecmp(tmp->name, "host")) {
  3581. struct ast_hostent ahp;
  3582. struct hostent *hp;
  3583. if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
  3584. /* No match */
  3585. ast_variables_destroy(var);
  3586. var = NULL;
  3587. }
  3588. break;
  3589. }
  3590. }
  3591. }
  3592. }
  3593. if (!var)
  3594. return NULL;
  3595. tmp = var;
  3596. while(tmp) {
  3597. /* Make sure it's not a peer only... */
  3598. if (!strcasecmp(tmp->name, "type")) {
  3599. if (strcasecmp(tmp->value, "friend") &&
  3600. strcasecmp(tmp->value, "user")) {
  3601. return NULL;
  3602. }
  3603. }
  3604. tmp = tmp->next;
  3605. }
  3606. user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
  3607. ast_variables_destroy(var);
  3608. if (!user)
  3609. return NULL;
  3610. if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
  3611. ast_set_flag(user, IAX_RTCACHEFRIENDS);
  3612. ao2_link(users, user);
  3613. } else {
  3614. ast_set_flag(user, IAX_TEMPONLY);
  3615. }
  3616. return user;
  3617. }
  3618. static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
  3619. {
  3620. char port[10];
  3621. char regseconds[20];
  3622. snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
  3623. snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
  3624. ast_update_realtime("iaxpeers", "name", peername,
  3625. "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port,
  3626. "regseconds", regseconds, NULL);
  3627. }
  3628. struct create_addr_info {
  3629. int capability;
  3630. unsigned int flags;
  3631. int maxtime;
  3632. int encmethods;
  3633. int found;
  3634. int sockfd;
  3635. int adsi;
  3636. char username[80];
  3637. char secret[80];
  3638. char outkey[80];
  3639. char timezone[80];
  3640. char prefs[32];
  3641. char context[AST_MAX_CONTEXT];
  3642. char peercontext[AST_MAX_CONTEXT];
  3643. char mohinterpret[MAX_MUSICCLASS];
  3644. char mohsuggest[MAX_MUSICCLASS];
  3645. };
  3646. static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
  3647. {
  3648. struct iax2_peer *peer;
  3649. int res = -1;
  3650. struct ast_codec_pref ourprefs;
  3651. ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
  3652. cai->sockfd = defaultsockfd;
  3653. cai->maxtime = 0;
  3654. sin->sin_family = AF_INET;
  3655. if (!(peer = find_peer(peername, 1))) {
  3656. cai->found = 0;
  3657. if (ast_get_ip_or_srv(sin, peername, srvlookup ? "_iax._udp" : NULL)) {
  3658. ast_log(LOG_WARNING, "No such host: %s\n", peername);
  3659. return -1;
  3660. }
  3661. sin->sin_port = htons(IAX_DEFAULT_PORTNO);
  3662. /* use global iax prefs for unknown peer/user */
  3663. /* But move the calling channel's native codec to the top of the preference list */
  3664. memcpy(&ourprefs, &prefs, sizeof(ourprefs));
  3665. if (c)
  3666. ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
  3667. ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
  3668. return 0;
  3669. }
  3670. cai->found = 1;
  3671. /* if the peer has no address (current or default), return failure */
  3672. if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr))
  3673. goto return_unref;
  3674. /* if the peer is being monitored and is currently unreachable, return failure */
  3675. if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
  3676. goto return_unref;
  3677. ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
  3678. cai->maxtime = peer->maxms;
  3679. cai->capability = peer->capability;
  3680. cai->encmethods = peer->encmethods;
  3681. cai->sockfd = peer->sockfd;
  3682. cai->adsi = peer->adsi;
  3683. memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
  3684. /* Move the calling channel's native codec to the top of the preference list */
  3685. if (c) {
  3686. ast_debug(1, "prepending %x to prefs\n", c->nativeformats);
  3687. ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
  3688. }
  3689. ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
  3690. ast_copy_string(cai->context, peer->context, sizeof(cai->context));
  3691. ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
  3692. ast_copy_string(cai->username, peer->username, sizeof(cai->username));
  3693. ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
  3694. ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
  3695. ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
  3696. ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
  3697. if (ast_strlen_zero(peer->dbsecret)) {
  3698. ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
  3699. } else {
  3700. char *family;
  3701. char *key = NULL;
  3702. family = ast_strdupa(peer->dbsecret);
  3703. key = strchr(family, '/');
  3704. if (key)
  3705. *key++ = '\0';
  3706. if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
  3707. ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
  3708. goto return_unref;
  3709. }
  3710. }
  3711. if (peer->addr.sin_addr.s_addr) {
  3712. sin->sin_addr = peer->addr.sin_addr;
  3713. sin->sin_port = peer->addr.sin_port;
  3714. } else {
  3715. sin->sin_addr = peer->defaddr.sin_addr;
  3716. sin->sin_port = peer->defaddr.sin_port;
  3717. }
  3718. res = 0;
  3719. return_unref:
  3720. peer_unref(peer);
  3721. return res;
  3722. }
  3723. static void __auto_congest(const void *nothing)
  3724. {
  3725. int callno = PTR_TO_CALLNO(nothing);
  3726. struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
  3727. ast_mutex_lock(&iaxsl[callno]);
  3728. if (iaxs[callno]) {
  3729. iaxs[callno]->initid = -1;
  3730. iax2_queue_frame(callno, &f);
  3731. ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
  3732. }
  3733. ast_mutex_unlock(&iaxsl[callno]);
  3734. }
  3735. static int auto_congest(const void *data)
  3736. {
  3737. #ifdef SCHED_MULTITHREADED
  3738. if (schedule_action(__auto_congest, data))
  3739. #endif
  3740. __auto_congest(data);
  3741. return 0;
  3742. }
  3743. static unsigned int iax2_datetime(const char *tz)
  3744. {
  3745. struct timeval t = ast_tvnow();
  3746. struct ast_tm tm;
  3747. unsigned int tmp;
  3748. ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
  3749. tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
  3750. tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
  3751. tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
  3752. tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
  3753. tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
  3754. tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
  3755. return tmp;
  3756. }
  3757. struct parsed_dial_string {
  3758. char *username;
  3759. char *password;
  3760. char *key;
  3761. char *peer;
  3762. char *port;
  3763. char *exten;
  3764. char *context;
  3765. char *options;
  3766. };
  3767. static int send_apathetic_reply(unsigned short callno, unsigned short dcallno,
  3768. struct sockaddr_in *sin, int command, int ts, unsigned char seqno,
  3769. int sockfd, struct iax_ie_data *ied)
  3770. {
  3771. struct {
  3772. struct ast_iax2_full_hdr f;
  3773. struct iax_ie_data ied;
  3774. } data;
  3775. size_t size = sizeof(struct ast_iax2_full_hdr);
  3776. if (ied) {
  3777. size += ied->pos;
  3778. memcpy(&data.ied, ied->buf, ied->pos);
  3779. }
  3780. data.f.scallno = htons(0x8000 | callno);
  3781. data.f.dcallno = htons(dcallno);
  3782. data.f.ts = htonl(ts);
  3783. data.f.iseqno = seqno;
  3784. data.f.oseqno = 0;
  3785. data.f.type = AST_FRAME_IAX;
  3786. data.f.csub = compress_subclass(command);
  3787. return sendto(sockfd, &data, size, 0, (struct sockaddr *)sin, sizeof(*sin));
  3788. }
  3789. static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
  3790. {
  3791. /* first make sure their are two empty bytes left in ied->buf */
  3792. if (pvt && ied && (2 < ((int) sizeof(ied->buf) - ied->pos))) {
  3793. ied->buf[ied->pos++] = IAX_IE_CALLTOKEN; /* type */
  3794. ied->buf[ied->pos++] = 0; /* data size, ZERO in this case */
  3795. pvt->calltoken_ie_len = 2;
  3796. }
  3797. }
  3798. static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
  3799. {
  3800. struct chan_iax2_pvt *pvt = iaxs[callno];
  3801. int frametype = f->af.frametype;
  3802. int subclass = f->af.subclass;
  3803. struct {
  3804. struct ast_iax2_full_hdr fh;
  3805. struct iax_ie_data ied;
  3806. } data = {
  3807. .ied.buf = { 0 },
  3808. .ied.pos = 0,
  3809. };
  3810. /* total len - header len gives us the frame's IE len */
  3811. int ie_data_pos = f->datalen - sizeof(struct ast_iax2_full_hdr);
  3812. if (!pvt) {
  3813. return; /* this should not be possible if called from socket_process() */
  3814. }
  3815. /*
  3816. * Check to make sure last frame sent is valid for call token resend
  3817. * 1. Frame should _NOT_ be encrypted since it starts the IAX dialog
  3818. * 2. Frame should _NOT_ already have a destination callno
  3819. * 3. Frame must be a valid iax_frame subclass capable of starting dialog
  3820. * 4. Pvt must have a calltoken_ie_len which represents the number of
  3821. * bytes at the end of the frame used for the previous calltoken ie.
  3822. * 5. Pvt's calltoken_ie_len must be _LESS_ than the total IE length
  3823. * 6. Total length of f->data must be _LESS_ than size of our data struct
  3824. * because f->data must be able to fit within data.
  3825. */
  3826. if (f->encmethods || f->dcallno || !iax2_allow_new(frametype, subclass, 0)
  3827. || !pvt->calltoken_ie_len || (pvt->calltoken_ie_len > ie_data_pos) ||
  3828. (f->datalen > sizeof(data))) {
  3829. return; /* ignore resend, token was not valid for the dialog */
  3830. }
  3831. /* token is valid
  3832. * 1. Copy frame data over
  3833. * 2. Redo calltoken IE, it will always be the last ie in the frame.
  3834. * NOTE: Having the ie always be last is not protocol specified,
  3835. * it is only an implementation choice. Since we only expect the ie to
  3836. * be last for frames we have sent, this can no way be affected by
  3837. * another end point.
  3838. * 3. Remove frame from queue
  3839. * 4. Free old frame
  3840. * 5. Clear previous seqnos
  3841. * 6. Resend with CALLTOKEN ie.
  3842. */
  3843. /* ---1.--- */
  3844. memcpy(&data, f->data, f->datalen);
  3845. data.ied.pos = ie_data_pos;
  3846. /* ---2.--- */
  3847. /* move to the beginning of the calltoken ie so we can write over it */
  3848. data.ied.pos -= pvt->calltoken_ie_len;
  3849. iax_ie_append_str(&data.ied, IAX_IE_CALLTOKEN, newtoken);
  3850. /* make sure to update token length incase it ever has to be stripped off again */
  3851. pvt->calltoken_ie_len = data.ied.pos - ie_data_pos; /* new pos minus old pos tells how big token ie is */
  3852. /* ---3.--- */
  3853. AST_LIST_LOCK(&frame_queue);
  3854. AST_LIST_REMOVE(&frame_queue, f, list);
  3855. AST_LIST_UNLOCK(&frame_queue);
  3856. /* ---4.--- */
  3857. iax2_frame_free(f);
  3858. /* ---5.--- */
  3859. pvt->oseqno = 0;
  3860. pvt->rseqno = 0;
  3861. pvt->iseqno = 0;
  3862. pvt->aseqno = 0;
  3863. if (pvt->peercallno) {
  3864. remove_by_peercallno(pvt);
  3865. pvt->peercallno = 0;
  3866. }
  3867. /* ---6.--- */
  3868. send_command(pvt, AST_FRAME_IAX, subclass, 0, data.ied.buf, data.ied.pos, -1);
  3869. }
  3870. static void requirecalltoken_mark_auto(const char *name, int subclass)
  3871. {
  3872. struct iax2_user *user = NULL;
  3873. struct iax2_peer *peer = NULL;
  3874. if (ast_strlen_zero(name)) {
  3875. return; /* no username given */
  3876. }
  3877. if ((subclass == IAX_COMMAND_NEW) && (user = find_user(name)) && (user->calltoken_required == CALLTOKEN_AUTO)) {
  3878. user->calltoken_required = CALLTOKEN_YES;
  3879. } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(name, 1)) && (peer->calltoken_required == CALLTOKEN_AUTO)) {
  3880. peer->calltoken_required = CALLTOKEN_YES;
  3881. }
  3882. if (peer) {
  3883. peer_unref(peer);
  3884. }
  3885. if (user) {
  3886. user_unref(user);
  3887. }
  3888. }
  3889. /*!
  3890. * \internal
  3891. *
  3892. * \brief handles calltoken logic for a received iax_frame.
  3893. *
  3894. * \note frametype must be AST_FRAME_IAX.
  3895. *
  3896. * \note
  3897. * Three different cases are possible here.
  3898. * Case 1. An empty calltoken is provided. This means the client supports
  3899. * calltokens but has not yet received one from us. In this case
  3900. * a full calltoken IE is created and sent in a calltoken fullframe.
  3901. * Case 2. A full calltoken is received and must be checked for validity.
  3902. * Case 3. No calltoken is received indicating that the client does not
  3903. * support calltokens. In this case it is up to the configuration
  3904. * to decide how this should be handled (reject or permit without calltoken)
  3905. */
  3906. static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies,
  3907. struct sockaddr_in *sin, int fd)
  3908. {
  3909. #define CALLTOKEN_HASH_FORMAT "%s%d%u%d" /* address + port + ts + randomcalldata */
  3910. #define CALLTOKEN_IE_FORMAT "%u?%s" /* time + ? + (40 char hash) */
  3911. struct ast_str *buf = ast_str_alloca(256);
  3912. time_t t = time(NULL);
  3913. char hash[41]; /* 40 char sha1 hash */
  3914. int subclass = uncompress_subclass(fh->csub);
  3915. /* ----- Case 1 ----- */
  3916. if (ies->calltoken && !ies->calltokendata) { /* empty calltoken is provided, client supports calltokens */
  3917. struct iax_ie_data ied = {
  3918. .buf = { 0 },
  3919. .pos = 0,
  3920. };
  3921. /* create the hash with their address data and our timestamp */
  3922. ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) t, randomcalltokendata);
  3923. ast_sha1_hash(hash, ast_str_buffer(buf));
  3924. ast_str_set(&buf, 0, CALLTOKEN_IE_FORMAT, (unsigned int) t, hash);
  3925. iax_ie_append_str(&ied, IAX_IE_CALLTOKEN, ast_str_buffer(buf));
  3926. send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_CALLTOKEN, ntohl(fh->ts), fh->iseqno + 1, fd, &ied);
  3927. return 1;
  3928. /* ----- Case 2 ----- */
  3929. } else if (ies->calltoken && ies->calltokendata) { /* calltoken received, check to see if it is valid */
  3930. char *rec_hash = NULL; /* the received hash, make sure it matches with ours. */
  3931. char *rec_ts = NULL; /* received timestamp */
  3932. unsigned int rec_time; /* received time_t */
  3933. /* split the timestamp from the hash data */
  3934. rec_hash = strchr((char *) ies->calltokendata, '?');
  3935. if (rec_hash) {
  3936. *rec_hash++ = '\0';
  3937. rec_ts = (char *) ies->calltokendata;
  3938. }
  3939. /* check that we have valid data before we do any comparisons */
  3940. if (!rec_hash || !rec_ts) {
  3941. goto reject;
  3942. } else if (sscanf(rec_ts, "%u", &rec_time) != 1) {
  3943. goto reject;
  3944. }
  3945. /* create a hash with their address and the _TOKEN'S_ timestamp */
  3946. ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) rec_time, randomcalltokendata);
  3947. ast_sha1_hash(hash, ast_str_buffer(buf));
  3948. /* compare hashes and then check timestamp delay */
  3949. if (strcmp(hash, rec_hash)) {
  3950. ast_log(LOG_WARNING, "Address %s failed CallToken hash inspection\n", ast_inet_ntoa(sin->sin_addr));
  3951. goto reject; /* received hash does not match ours, reject */
  3952. } else if ((t < rec_time) || ((t - rec_time) >= MAX_CALLTOKEN_DELAY)) {
  3953. ast_log(LOG_WARNING, "Too much delay in IAX2 calltoken timestamp from address %s\n", ast_inet_ntoa(sin->sin_addr));
  3954. goto reject; /* too much delay, reject */
  3955. }
  3956. /* at this point the call token is valid, returning 0
  3957. * will allow socket_process to continue as usual */
  3958. requirecalltoken_mark_auto(ies->username, subclass);
  3959. return 0;
  3960. /* ----- Case 3 ----- */
  3961. } else { /* calltokens are not supported for this client, how do we respond? */
  3962. if (calltoken_required(sin, ies->username, subclass)) {
  3963. 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"));
  3964. goto reject;
  3965. }
  3966. return 0; /* calltoken is not required for this addr, so permit it. */
  3967. }
  3968. reject:
  3969. /* received frame has failed calltoken inspection, send apathetic reject messages */
  3970. if (subclass == IAX_COMMAND_REGREQ || subclass == IAX_COMMAND_REGREL) {
  3971. send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
  3972. } else {
  3973. send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
  3974. }
  3975. return 1;
  3976. }
  3977. /*!
  3978. * \brief Parses an IAX dial string into its component parts.
  3979. * \param data the string to be parsed
  3980. * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
  3981. * \return nothing
  3982. *
  3983. * This function parses the string and fills the structure
  3984. * with pointers to its component parts. The input string
  3985. * will be modified.
  3986. *
  3987. * \note This function supports both plaintext passwords and RSA
  3988. * key names; if the password string is formatted as '[keyname]',
  3989. * then the keyname will be placed into the key field, and the
  3990. * password field will be set to NULL.
  3991. *
  3992. * \note The dial string format is:
  3993. * [username[:password]@]peer[:port][/exten[@@context]][/options]
  3994. */
  3995. static void parse_dial_string(char *data, struct parsed_dial_string *pds)
  3996. {
  3997. if (ast_strlen_zero(data))
  3998. return;
  3999. pds->peer = strsep(&data, "/");
  4000. pds->exten = strsep(&data, "/");
  4001. pds->options = data;
  4002. if (pds->exten) {
  4003. data = pds->exten;
  4004. pds->exten = strsep(&data, "@");
  4005. pds->context = data;
  4006. }
  4007. if (strchr(pds->peer, '@')) {
  4008. data = pds->peer;
  4009. pds->username = strsep(&data, "@");
  4010. pds->peer = data;
  4011. }
  4012. if (pds->username) {
  4013. data = pds->username;
  4014. pds->username = strsep(&data, ":");
  4015. pds->password = data;
  4016. }
  4017. data = pds->peer;
  4018. pds->peer = strsep(&data, ":");
  4019. pds->port = data;
  4020. /* check for a key name wrapped in [] in the secret position, if found,
  4021. move it to the key field instead
  4022. */
  4023. if (pds->password && (pds->password[0] == '[')) {
  4024. pds->key = ast_strip_quoted(pds->password, "[", "]");
  4025. pds->password = NULL;
  4026. }
  4027. }
  4028. static int iax2_call(struct ast_channel *c, char *dest, int timeout)
  4029. {
  4030. struct sockaddr_in sin;
  4031. char *l=NULL, *n=NULL, *tmpstr;
  4032. struct iax_ie_data ied;
  4033. char *defaultrdest = "s";
  4034. unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
  4035. struct parsed_dial_string pds;
  4036. struct create_addr_info cai;
  4037. struct ast_var_t *var;
  4038. struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
  4039. const char* osp_token_ptr;
  4040. unsigned int osp_token_length;
  4041. unsigned char osp_block_index;
  4042. unsigned int osp_block_length;
  4043. unsigned char osp_buffer[256];
  4044. if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
  4045. ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
  4046. return -1;
  4047. }
  4048. memset(&cai, 0, sizeof(cai));
  4049. cai.encmethods = iax2_encryption;
  4050. memset(&pds, 0, sizeof(pds));
  4051. tmpstr = ast_strdupa(dest);
  4052. parse_dial_string(tmpstr, &pds);
  4053. if (ast_strlen_zero(pds.peer)) {
  4054. ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
  4055. return -1;
  4056. }
  4057. if (!pds.exten) {
  4058. pds.exten = defaultrdest;
  4059. }
  4060. if (create_addr(pds.peer, c, &sin, &cai)) {
  4061. ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
  4062. return -1;
  4063. }
  4064. if (!pds.username && !ast_strlen_zero(cai.username))
  4065. pds.username = cai.username;
  4066. if (!pds.password && !ast_strlen_zero(cai.secret))
  4067. pds.password = cai.secret;
  4068. if (!pds.key && !ast_strlen_zero(cai.outkey))
  4069. pds.key = cai.outkey;
  4070. if (!pds.context && !ast_strlen_zero(cai.peercontext))
  4071. pds.context = cai.peercontext;
  4072. /* Keep track of the context for outgoing calls too */
  4073. ast_copy_string(c->context, cai.context, sizeof(c->context));
  4074. if (pds.port)
  4075. sin.sin_port = htons(atoi(pds.port));
  4076. l = c->cid.cid_num;
  4077. n = c->cid.cid_name;
  4078. /* Now build request */
  4079. memset(&ied, 0, sizeof(ied));
  4080. /* On new call, first IE MUST be IAX version of caller */
  4081. iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
  4082. iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
  4083. if (pds.options && strchr(pds.options, 'a')) {
  4084. /* Request auto answer */
  4085. iax_ie_append(&ied, IAX_IE_AUTOANSWER);
  4086. }
  4087. iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
  4088. if (l) {
  4089. iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
  4090. iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
  4091. } else {
  4092. if (n)
  4093. iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
  4094. else
  4095. iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
  4096. }
  4097. iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
  4098. iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
  4099. if (n)
  4100. iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
  4101. if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
  4102. iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
  4103. if (!ast_strlen_zero(c->language))
  4104. iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
  4105. if (!ast_strlen_zero(c->cid.cid_dnid))
  4106. iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
  4107. if (!ast_strlen_zero(c->cid.cid_rdnis))
  4108. iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
  4109. if (pds.context)
  4110. iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
  4111. if (pds.username)
  4112. iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
  4113. if (cai.encmethods)
  4114. iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
  4115. ast_mutex_lock(&iaxsl[callno]);
  4116. if (!ast_strlen_zero(c->context))
  4117. ast_string_field_set(iaxs[callno], context, c->context);
  4118. if (pds.username)
  4119. ast_string_field_set(iaxs[callno], username, pds.username);
  4120. iaxs[callno]->encmethods = cai.encmethods;
  4121. iaxs[callno]->adsi = cai.adsi;
  4122. ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
  4123. ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
  4124. if (pds.key)
  4125. ast_string_field_set(iaxs[callno], outkey, pds.key);
  4126. if (pds.password)
  4127. ast_string_field_set(iaxs[callno], secret, pds.password);
  4128. iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
  4129. iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
  4130. iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
  4131. iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
  4132. if (iaxs[callno]->maxtime) {
  4133. /* Initialize pingtime and auto-congest time */
  4134. iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
  4135. iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
  4136. } else if (autokill) {
  4137. iaxs[callno]->pingtime = autokill / 2;
  4138. iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
  4139. }
  4140. /* Check if there is an OSP token */
  4141. osp_token_ptr = pbx_builtin_getvar_helper(c, "IAX2OSPTOKEN");
  4142. if (!ast_strlen_zero(osp_token_ptr)) {
  4143. if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
  4144. osp_block_index = 0;
  4145. while (osp_token_length > 0) {
  4146. osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
  4147. osp_buffer[0] = osp_block_index;
  4148. memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
  4149. iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
  4150. osp_block_index++;
  4151. osp_token_ptr += osp_block_length;
  4152. osp_token_length -= osp_block_length;
  4153. }
  4154. } else
  4155. ast_log(LOG_WARNING, "OSP token is too long\n");
  4156. } else if (iaxdebug)
  4157. ast_debug(1, "OSP token is undefined\n");
  4158. /* send the command using the appropriate socket for this peer */
  4159. iaxs[callno]->sockfd = cai.sockfd;
  4160. /* Add remote vars */
  4161. if (variablestore) {
  4162. AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
  4163. ast_debug(1, "Found an IAX variable store on this channel\n");
  4164. AST_LIST_LOCK(variablelist);
  4165. AST_LIST_TRAVERSE(variablelist, var, entries) {
  4166. char tmp[256];
  4167. int i;
  4168. ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
  4169. /* Automatically divide the value up into sized chunks */
  4170. for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
  4171. snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
  4172. iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
  4173. }
  4174. }
  4175. AST_LIST_UNLOCK(variablelist);
  4176. }
  4177. /* Transmit the string in a "NEW" request */
  4178. add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
  4179. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
  4180. ast_mutex_unlock(&iaxsl[callno]);
  4181. ast_setstate(c, AST_STATE_RINGING);
  4182. return 0;
  4183. }
  4184. static int iax2_hangup(struct ast_channel *c)
  4185. {
  4186. unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
  4187. struct iax_ie_data ied;
  4188. int alreadygone;
  4189. memset(&ied, 0, sizeof(ied));
  4190. ast_mutex_lock(&iaxsl[callno]);
  4191. if (callno && iaxs[callno]) {
  4192. ast_debug(1, "We're hanging up %s now...\n", c->name);
  4193. alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
  4194. /* Send the hangup unless we have had a transmission error or are already gone */
  4195. iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
  4196. if (!iaxs[callno]->error && !alreadygone) {
  4197. if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
  4198. ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
  4199. }
  4200. if (!iaxs[callno]) {
  4201. ast_mutex_unlock(&iaxsl[callno]);
  4202. return 0;
  4203. }
  4204. }
  4205. /* Explicitly predestroy it */
  4206. iax2_predestroy(callno);
  4207. /* If we were already gone to begin with, destroy us now */
  4208. if (iaxs[callno] && alreadygone) {
  4209. ast_debug(1, "Really destroying %s now...\n", c->name);
  4210. iax2_destroy(callno);
  4211. } else if (iaxs[callno]) {
  4212. if (ast_sched_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
  4213. ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!! Destroying immediately.\n", callno);
  4214. iax2_destroy(callno);
  4215. }
  4216. }
  4217. } else if (c->tech_pvt) {
  4218. /* If this call no longer exists, but the channel still
  4219. * references it we need to set the channel's tech_pvt to null
  4220. * to avoid ast_channel_free() trying to free it.
  4221. */
  4222. c->tech_pvt = NULL;
  4223. }
  4224. ast_mutex_unlock(&iaxsl[callno]);
  4225. ast_verb(3, "Hungup '%s'\n", c->name);
  4226. return 0;
  4227. }
  4228. /*!
  4229. * \note expects the pvt to be locked
  4230. */
  4231. static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
  4232. {
  4233. unsigned short callno = pvt->callno;
  4234. if (!pvt->peercallno) {
  4235. /* We don't know the remote side's call number, yet. :( */
  4236. int count = 10;
  4237. while (count-- && pvt && !pvt->peercallno) {
  4238. DEADLOCK_AVOIDANCE(&iaxsl[callno]);
  4239. pvt = iaxs[callno];
  4240. }
  4241. if (!pvt->peercallno) {
  4242. return -1;
  4243. }
  4244. }
  4245. return 0;
  4246. }
  4247. static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
  4248. {
  4249. struct ast_option_header *h;
  4250. int res;
  4251. switch (option) {
  4252. case AST_OPTION_TXGAIN:
  4253. case AST_OPTION_RXGAIN:
  4254. /* these two cannot be sent, because they require a result */
  4255. errno = ENOSYS;
  4256. return -1;
  4257. default:
  4258. {
  4259. unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
  4260. struct chan_iax2_pvt *pvt;
  4261. ast_mutex_lock(&iaxsl[callno]);
  4262. pvt = iaxs[callno];
  4263. if (wait_for_peercallno(pvt)) {
  4264. ast_mutex_unlock(&iaxsl[callno]);
  4265. return -1;
  4266. }
  4267. ast_mutex_unlock(&iaxsl[callno]);
  4268. if (!(h = ast_malloc(datalen + sizeof(*h)))) {
  4269. return -1;
  4270. }
  4271. h->flag = AST_OPTION_FLAG_REQUEST;
  4272. h->option = htons(option);
  4273. memcpy(h->data, data, datalen);
  4274. res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
  4275. AST_CONTROL_OPTION, 0, (unsigned char *) h,
  4276. datalen + sizeof(*h), -1);
  4277. ast_free(h);
  4278. return res;
  4279. }
  4280. }
  4281. }
  4282. static struct ast_frame *iax2_read(struct ast_channel *c)
  4283. {
  4284. ast_log(LOG_NOTICE, "I should never be called!\n");
  4285. return &ast_null_frame;
  4286. }
  4287. static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
  4288. {
  4289. int res;
  4290. struct iax_ie_data ied0;
  4291. struct iax_ie_data ied1;
  4292. unsigned int transferid = (unsigned int)ast_random();
  4293. memset(&ied0, 0, sizeof(ied0));
  4294. iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
  4295. iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
  4296. iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
  4297. memset(&ied1, 0, sizeof(ied1));
  4298. iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
  4299. iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
  4300. iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
  4301. res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
  4302. if (res)
  4303. return -1;
  4304. res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
  4305. if (res)
  4306. return -1;
  4307. iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
  4308. iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
  4309. return 0;
  4310. }
  4311. static void lock_both(unsigned short callno0, unsigned short callno1)
  4312. {
  4313. ast_mutex_lock(&iaxsl[callno0]);
  4314. while (ast_mutex_trylock(&iaxsl[callno1])) {
  4315. DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
  4316. }
  4317. }
  4318. static void unlock_both(unsigned short callno0, unsigned short callno1)
  4319. {
  4320. ast_mutex_unlock(&iaxsl[callno1]);
  4321. ast_mutex_unlock(&iaxsl[callno0]);
  4322. }
  4323. 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)
  4324. {
  4325. struct ast_channel *cs[3];
  4326. struct ast_channel *who, *other;
  4327. int to = -1;
  4328. int res = -1;
  4329. int transferstarted=0;
  4330. struct ast_frame *f;
  4331. unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
  4332. unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
  4333. struct timeval waittimer = {0, 0}, tv;
  4334. /* We currently do not support native bridging if a timeoutms value has been provided */
  4335. if (timeoutms > 0) {
  4336. return AST_BRIDGE_FAILED;
  4337. }
  4338. timeoutms = -1;
  4339. lock_both(callno0, callno1);
  4340. if (!iaxs[callno0] || !iaxs[callno1]) {
  4341. unlock_both(callno0, callno1);
  4342. return AST_BRIDGE_FAILED;
  4343. }
  4344. /* Put them in native bridge mode */
  4345. if (!(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
  4346. iaxs[callno0]->bridgecallno = callno1;
  4347. iaxs[callno1]->bridgecallno = callno0;
  4348. }
  4349. /* If the bridge got retried, don't queue up more packets - the transfer request will be retransmitted as necessary */
  4350. if (iaxs[callno0]->transferring && iaxs[callno1]->transferring) {
  4351. transferstarted = 1;
  4352. }
  4353. unlock_both(callno0, callno1);
  4354. /* If not, try to bridge until we can execute a transfer, if we can */
  4355. cs[0] = c0;
  4356. cs[1] = c1;
  4357. for (/* ever */;;) {
  4358. /* Check in case we got masqueraded into */
  4359. if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
  4360. ast_verb(3, "Can't masquerade, we're different...\n");
  4361. /* Remove from native mode */
  4362. if (c0->tech == &iax2_tech) {
  4363. ast_mutex_lock(&iaxsl[callno0]);
  4364. iaxs[callno0]->bridgecallno = 0;
  4365. ast_mutex_unlock(&iaxsl[callno0]);
  4366. }
  4367. if (c1->tech == &iax2_tech) {
  4368. ast_mutex_lock(&iaxsl[callno1]);
  4369. iaxs[callno1]->bridgecallno = 0;
  4370. ast_mutex_unlock(&iaxsl[callno1]);
  4371. }
  4372. return AST_BRIDGE_FAILED_NOWARN;
  4373. }
  4374. if (c0->nativeformats != c1->nativeformats) {
  4375. char buf0[255];
  4376. char buf1[255];
  4377. ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
  4378. ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
  4379. ast_verb(3, "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
  4380. /* Remove from native mode */
  4381. lock_both(callno0, callno1);
  4382. if (iaxs[callno0])
  4383. iaxs[callno0]->bridgecallno = 0;
  4384. if (iaxs[callno1])
  4385. iaxs[callno1]->bridgecallno = 0;
  4386. unlock_both(callno0, callno1);
  4387. return AST_BRIDGE_FAILED_NOWARN;
  4388. }
  4389. /* check if transfered and if we really want native bridging */
  4390. if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) {
  4391. /* Try the transfer */
  4392. if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
  4393. ast_test_flag(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag(iaxs[callno1], IAX_TRANSFERMEDIA)))
  4394. ast_log(LOG_WARNING, "Unable to start the transfer\n");
  4395. transferstarted = 1;
  4396. }
  4397. if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
  4398. /* Call has been transferred. We're no longer involved */
  4399. tv = ast_tvnow();
  4400. if (ast_tvzero(waittimer)) {
  4401. waittimer = tv;
  4402. } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
  4403. c0->_softhangup |= AST_SOFTHANGUP_DEV;
  4404. c1->_softhangup |= AST_SOFTHANGUP_DEV;
  4405. *fo = NULL;
  4406. *rc = c0;
  4407. res = AST_BRIDGE_COMPLETE;
  4408. break;
  4409. }
  4410. }
  4411. to = 1000;
  4412. who = ast_waitfor_n(cs, 2, &to);
  4413. if (timeoutms > -1) {
  4414. timeoutms -= (1000 - to);
  4415. if (timeoutms < 0)
  4416. timeoutms = 0;
  4417. }
  4418. if (!who) {
  4419. if (!timeoutms) {
  4420. res = AST_BRIDGE_RETRY;
  4421. break;
  4422. }
  4423. if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
  4424. res = AST_BRIDGE_FAILED;
  4425. break;
  4426. }
  4427. continue;
  4428. }
  4429. f = ast_read(who);
  4430. if (!f) {
  4431. *fo = NULL;
  4432. *rc = who;
  4433. res = AST_BRIDGE_COMPLETE;
  4434. break;
  4435. }
  4436. if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS) && (f->subclass != AST_CONTROL_SRCUPDATE)) {
  4437. *fo = f;
  4438. *rc = who;
  4439. res = AST_BRIDGE_COMPLETE;
  4440. break;
  4441. }
  4442. other = (who == c0) ? c1 : c0; /* the 'other' channel */
  4443. if ((f->frametype == AST_FRAME_VOICE) ||
  4444. (f->frametype == AST_FRAME_TEXT) ||
  4445. (f->frametype == AST_FRAME_VIDEO) ||
  4446. (f->frametype == AST_FRAME_IMAGE) ||
  4447. (f->frametype == AST_FRAME_DTMF) ||
  4448. (f->frametype == AST_FRAME_CONTROL)) {
  4449. /* monitored dtmf take out of the bridge.
  4450. * check if we monitor the specific source.
  4451. */
  4452. int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
  4453. if (f->frametype == AST_FRAME_DTMF && (flags & monitored_source)) {
  4454. *rc = who;
  4455. *fo = f;
  4456. res = AST_BRIDGE_COMPLETE;
  4457. /* Remove from native mode */
  4458. break;
  4459. }
  4460. /* everything else goes to the other side */
  4461. ast_write(other, f);
  4462. }
  4463. ast_frfree(f);
  4464. /* Swap who gets priority */
  4465. cs[2] = cs[0];
  4466. cs[0] = cs[1];
  4467. cs[1] = cs[2];
  4468. }
  4469. lock_both(callno0, callno1);
  4470. if(iaxs[callno0])
  4471. iaxs[callno0]->bridgecallno = 0;
  4472. if(iaxs[callno1])
  4473. iaxs[callno1]->bridgecallno = 0;
  4474. unlock_both(callno0, callno1);
  4475. return res;
  4476. }
  4477. static int iax2_answer(struct ast_channel *c)
  4478. {
  4479. unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
  4480. ast_debug(1, "Answering IAX2 call\n");
  4481. ast_mutex_lock(&iaxsl[callno]);
  4482. if (iaxs[callno])
  4483. iax2_ami_channelupdate(iaxs[callno]);
  4484. ast_mutex_unlock(&iaxsl[callno]);
  4485. return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
  4486. }
  4487. static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
  4488. {
  4489. unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
  4490. struct chan_iax2_pvt *pvt;
  4491. int res = 0;
  4492. if (iaxdebug)
  4493. ast_debug(1, "Indicating condition %d\n", condition);
  4494. ast_mutex_lock(&iaxsl[callno]);
  4495. pvt = iaxs[callno];
  4496. if (wait_for_peercallno(pvt)) {
  4497. res = -1;
  4498. goto done;
  4499. }
  4500. switch (condition) {
  4501. case AST_CONTROL_HOLD:
  4502. if (strcasecmp(pvt->mohinterpret, "passthrough")) {
  4503. ast_moh_start(c, data, pvt->mohinterpret);
  4504. goto done;
  4505. }
  4506. break;
  4507. case AST_CONTROL_UNHOLD:
  4508. if (strcasecmp(pvt->mohinterpret, "passthrough")) {
  4509. ast_moh_stop(c);
  4510. goto done;
  4511. }
  4512. }
  4513. res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
  4514. done:
  4515. ast_mutex_unlock(&iaxsl[callno]);
  4516. return res;
  4517. }
  4518. static int iax2_transfer(struct ast_channel *c, const char *dest)
  4519. {
  4520. unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
  4521. struct iax_ie_data ied = { "", };
  4522. char tmp[256], *context;
  4523. ast_copy_string(tmp, dest, sizeof(tmp));
  4524. context = strchr(tmp, '@');
  4525. if (context) {
  4526. *context = '\0';
  4527. context++;
  4528. }
  4529. iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
  4530. if (context)
  4531. iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
  4532. ast_debug(1, "Transferring '%s' to '%s'\n", c->name, dest);
  4533. return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
  4534. }
  4535. static int iax2_getpeertrunk(struct sockaddr_in sin)
  4536. {
  4537. struct iax2_peer *peer;
  4538. int res = 0;
  4539. struct ao2_iterator i;
  4540. i = ao2_iterator_init(peers, 0);
  4541. while ((peer = ao2_iterator_next(&i))) {
  4542. if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
  4543. (peer->addr.sin_port == sin.sin_port)) {
  4544. res = ast_test_flag(peer, IAX_TRUNK);
  4545. peer_unref(peer);
  4546. break;
  4547. }
  4548. peer_unref(peer);
  4549. }
  4550. ao2_iterator_destroy(&i);
  4551. return res;
  4552. }
  4553. /*! \brief Create new call, interface with the PBX core */
  4554. static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
  4555. {
  4556. struct ast_channel *tmp;
  4557. struct chan_iax2_pvt *i;
  4558. struct ast_variable *v = NULL;
  4559. if (!(i = iaxs[callno])) {
  4560. ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
  4561. return NULL;
  4562. }
  4563. /* Don't hold call lock */
  4564. ast_mutex_unlock(&iaxsl[callno]);
  4565. tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, i->amaflags, "IAX2/%s-%d", i->host, i->callno);
  4566. ast_mutex_lock(&iaxsl[callno]);
  4567. if (i != iaxs[callno]) {
  4568. if (tmp) {
  4569. /* unlock and relock iaxsl[callno] to preserve locking order */
  4570. ast_mutex_unlock(&iaxsl[callno]);
  4571. ast_channel_free(tmp);
  4572. ast_mutex_lock(&iaxsl[callno]);
  4573. }
  4574. return NULL;
  4575. }
  4576. iax2_ami_channelupdate(i);
  4577. if (!tmp)
  4578. return NULL;
  4579. tmp->tech = &iax2_tech;
  4580. /* We can support any format by default, until we get restricted */
  4581. tmp->nativeformats = capability;
  4582. tmp->readformat = tmp->rawreadformat = ast_best_codec(capability);
  4583. tmp->writeformat = tmp->rawwriteformat = ast_best_codec(capability);
  4584. tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
  4585. /* Don't use ast_set_callerid() here because it will
  4586. * generate a NewCallerID event before the NewChannel event */
  4587. if (!ast_strlen_zero(i->ani))
  4588. tmp->cid.cid_ani = ast_strdup(i->ani);
  4589. else
  4590. tmp->cid.cid_ani = ast_strdup(i->cid_num);
  4591. tmp->cid.cid_dnid = ast_strdup(i->dnid);
  4592. tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
  4593. tmp->cid.cid_pres = i->calling_pres;
  4594. tmp->cid.cid_ton = i->calling_ton;
  4595. tmp->cid.cid_tns = i->calling_tns;
  4596. if (!ast_strlen_zero(i->language))
  4597. ast_string_field_set(tmp, language, i->language);
  4598. if (!ast_strlen_zero(i->accountcode))
  4599. ast_string_field_set(tmp, accountcode, i->accountcode);
  4600. if (i->amaflags)
  4601. tmp->amaflags = i->amaflags;
  4602. ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
  4603. ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
  4604. if (i->adsi)
  4605. tmp->adsicpe = i->peeradsicpe;
  4606. else
  4607. tmp->adsicpe = AST_ADSI_UNAVAILABLE;
  4608. i->owner = tmp;
  4609. i->capability = capability;
  4610. /* Set inherited variables */
  4611. if (i->vars) {
  4612. for (v = i->vars ; v ; v = v->next)
  4613. pbx_builtin_setvar_helper(tmp, v->name, v->value);
  4614. }
  4615. if (i->iaxvars) {
  4616. struct ast_datastore *variablestore;
  4617. struct ast_variable *var, *prev = NULL;
  4618. AST_LIST_HEAD(, ast_var_t) *varlist;
  4619. ast_debug(1, "Loading up the channel with IAXVARs\n");
  4620. varlist = ast_calloc(1, sizeof(*varlist));
  4621. variablestore = ast_channel_datastore_alloc(&iax2_variable_datastore_info, NULL);
  4622. if (variablestore && varlist) {
  4623. variablestore->data = varlist;
  4624. variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
  4625. AST_LIST_HEAD_INIT(varlist);
  4626. for (var = i->iaxvars; var; var = var->next) {
  4627. struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
  4628. if (prev)
  4629. ast_free(prev);
  4630. prev = var;
  4631. if (!newvar) {
  4632. /* Don't abort list traversal, as this would leave i->iaxvars in an inconsistent state. */
  4633. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  4634. } else {
  4635. AST_LIST_INSERT_TAIL(varlist, newvar, entries);
  4636. }
  4637. }
  4638. if (prev)
  4639. ast_free(prev);
  4640. i->iaxvars = NULL;
  4641. ast_channel_datastore_add(i->owner, variablestore);
  4642. } else {
  4643. if (variablestore) {
  4644. ast_channel_datastore_free(variablestore);
  4645. }
  4646. if (varlist) {
  4647. ast_free(varlist);
  4648. }
  4649. }
  4650. }
  4651. if (state != AST_STATE_DOWN) {
  4652. if (ast_pbx_start(tmp)) {
  4653. ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
  4654. ast_hangup(tmp);
  4655. i->owner = NULL;
  4656. return NULL;
  4657. }
  4658. }
  4659. ast_module_ref(ast_module_info->self);
  4660. return tmp;
  4661. }
  4662. static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
  4663. {
  4664. unsigned long int mssincetx; /* unsigned to handle overflows */
  4665. long int ms, pred;
  4666. tpeer->trunkact = *tv;
  4667. mssincetx = ast_tvdiff_ms(*tv, tpeer->lasttxtime);
  4668. if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
  4669. /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
  4670. tpeer->txtrunktime = *tv;
  4671. tpeer->lastsent = 999999;
  4672. }
  4673. /* Update last transmit time now */
  4674. tpeer->lasttxtime = *tv;
  4675. /* Calculate ms offset */
  4676. ms = ast_tvdiff_ms(*tv, tpeer->txtrunktime);
  4677. /* Predict from last value */
  4678. pred = tpeer->lastsent + sampms;
  4679. if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
  4680. ms = pred;
  4681. /* We never send the same timestamp twice, so fudge a little if we must */
  4682. if (ms == tpeer->lastsent)
  4683. ms = tpeer->lastsent + 1;
  4684. tpeer->lastsent = ms;
  4685. return ms;
  4686. }
  4687. static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
  4688. {
  4689. long ms; /* NOT unsigned */
  4690. if (ast_tvzero(iaxs[callno]->rxcore)) {
  4691. /* Initialize rxcore time if appropriate */
  4692. iaxs[callno]->rxcore = ast_tvnow();
  4693. /* Round to nearest 20ms so traces look pretty */
  4694. iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
  4695. }
  4696. /* Calculate difference between trunk and channel */
  4697. ms = ast_tvdiff_ms(*tv, iaxs[callno]->rxcore);
  4698. /* Return as the sum of trunk time and the difference between trunk and real time */
  4699. return ms + ts;
  4700. }
  4701. static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
  4702. {
  4703. int ms;
  4704. int voice = 0;
  4705. int genuine = 0;
  4706. int adjust;
  4707. int rate = ast_format_rate(f->subclass) / 1000;
  4708. struct timeval *delivery = NULL;
  4709. /* What sort of frame do we have?: voice is self-explanatory
  4710. "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
  4711. non-genuine frames are CONTROL frames [ringing etc], DTMF
  4712. The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
  4713. the others need a timestamp slaved to the voice frames so that they go in sequence
  4714. */
  4715. if (f) {
  4716. if (f->frametype == AST_FRAME_VOICE) {
  4717. voice = 1;
  4718. delivery = &f->delivery;
  4719. } else if (f->frametype == AST_FRAME_IAX) {
  4720. genuine = 1;
  4721. } else if (f->frametype == AST_FRAME_CNG) {
  4722. p->notsilenttx = 0;
  4723. }
  4724. }
  4725. if (ast_tvzero(p->offset)) {
  4726. p->offset = ast_tvnow();
  4727. /* Round to nearest 20ms for nice looking traces */
  4728. p->offset.tv_usec -= p->offset.tv_usec % 20000;
  4729. }
  4730. /* If the timestamp is specified, just send it as is */
  4731. if (ts)
  4732. return ts;
  4733. /* If we have a time that the frame arrived, always use it to make our timestamp */
  4734. if (delivery && !ast_tvzero(*delivery)) {
  4735. ms = ast_tvdiff_ms(*delivery, p->offset);
  4736. if (ms < 0) {
  4737. ms = 0;
  4738. }
  4739. if (iaxdebug)
  4740. ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
  4741. } else {
  4742. ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
  4743. if (ms < 0)
  4744. ms = 0;
  4745. if (voice) {
  4746. /* On a voice frame, use predicted values if appropriate */
  4747. if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
  4748. /* Adjust our txcore, keeping voice and non-voice synchronized */
  4749. /* AN EXPLANATION:
  4750. When we send voice, we usually send "calculated" timestamps worked out
  4751. on the basis of the number of samples sent. When we send other frames,
  4752. we usually send timestamps worked out from the real clock.
  4753. The problem is that they can tend to drift out of step because the
  4754. source channel's clock and our clock may not be exactly at the same rate.
  4755. We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
  4756. for this call. Moving it adjusts timestamps for non-voice frames.
  4757. We make the adjustment in the style of a moving average. Each time we
  4758. adjust p->offset by 10% of the difference between our clock-derived
  4759. timestamp and the predicted timestamp. That's why you see "10000"
  4760. below even though IAX2 timestamps are in milliseconds.
  4761. The use of a moving average avoids offset moving too radically.
  4762. Generally, "adjust" roams back and forth around 0, with offset hardly
  4763. changing at all. But if a consistent different starts to develop it
  4764. will be eliminated over the course of 10 frames (200-300msecs)
  4765. */
  4766. adjust = (ms - p->nextpred);
  4767. if (adjust < 0)
  4768. p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
  4769. else if (adjust > 0)
  4770. p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
  4771. if (!p->nextpred) {
  4772. p->nextpred = ms; /*f->samples / rate;*/
  4773. if (p->nextpred <= p->lastsent)
  4774. p->nextpred = p->lastsent + 3;
  4775. }
  4776. ms = p->nextpred;
  4777. } else {
  4778. /* in this case, just use the actual
  4779. * time, since we're either way off
  4780. * (shouldn't happen), or we're ending a
  4781. * silent period -- and seed the next
  4782. * predicted time. Also, round ms to the
  4783. * next multiple of frame size (so our
  4784. * silent periods are multiples of
  4785. * frame size too) */
  4786. if (iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
  4787. ast_debug(1, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
  4788. abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
  4789. if (f->samples >= rate) /* check to make sure we dont core dump */
  4790. {
  4791. int diff = ms % (f->samples / rate);
  4792. if (diff)
  4793. ms += f->samples/rate - diff;
  4794. }
  4795. p->nextpred = ms;
  4796. p->notsilenttx = 1;
  4797. }
  4798. } else if ( f->frametype == AST_FRAME_VIDEO ) {
  4799. /*
  4800. * IAX2 draft 03 says that timestamps MUST be in order.
  4801. * It does not say anything about several frames having the same timestamp
  4802. * When transporting video, we can have a frame that spans multiple iax packets
  4803. * (so called slices), so it would make sense to use the same timestamp for all of
  4804. * them
  4805. * We do want to make sure that frames don't go backwards though
  4806. */
  4807. if ( (unsigned int)ms < p->lastsent )
  4808. ms = p->lastsent;
  4809. } else {
  4810. /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
  4811. it's a genuine frame */
  4812. if (genuine) {
  4813. /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
  4814. if (ms <= p->lastsent)
  4815. ms = p->lastsent + 3;
  4816. } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
  4817. /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
  4818. ms = p->lastsent + 3;
  4819. }
  4820. }
  4821. }
  4822. p->lastsent = ms;
  4823. if (voice)
  4824. p->nextpred = p->nextpred + f->samples / rate;
  4825. return ms;
  4826. }
  4827. static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
  4828. {
  4829. /* Returns where in "receive time" we are. That is, how many ms
  4830. since we received (or would have received) the frame with timestamp 0 */
  4831. int ms;
  4832. #ifdef IAXTESTS
  4833. int jit;
  4834. #endif /* IAXTESTS */
  4835. /* Setup rxcore if necessary */
  4836. if (ast_tvzero(p->rxcore)) {
  4837. p->rxcore = ast_tvnow();
  4838. if (iaxdebug)
  4839. ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
  4840. p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
  4841. p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
  4842. #if 1
  4843. if (iaxdebug)
  4844. ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
  4845. p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
  4846. #endif
  4847. }
  4848. ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
  4849. #ifdef IAXTESTS
  4850. if (test_jit) {
  4851. if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
  4852. jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
  4853. if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
  4854. jit = -jit;
  4855. ms += jit;
  4856. }
  4857. }
  4858. if (test_late) {
  4859. ms += test_late;
  4860. test_late = 0;
  4861. }
  4862. #endif /* IAXTESTS */
  4863. return ms;
  4864. }
  4865. static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
  4866. {
  4867. struct iax2_trunk_peer *tpeer = NULL;
  4868. /* Finds and locks trunk peer */
  4869. AST_LIST_LOCK(&tpeers);
  4870. AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
  4871. if (!inaddrcmp(&tpeer->addr, sin)) {
  4872. ast_mutex_lock(&tpeer->lock);
  4873. break;
  4874. }
  4875. }
  4876. if (!tpeer) {
  4877. if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
  4878. ast_mutex_init(&tpeer->lock);
  4879. tpeer->lastsent = 9999;
  4880. memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
  4881. tpeer->trunkact = ast_tvnow();
  4882. ast_mutex_lock(&tpeer->lock);
  4883. tpeer->sockfd = fd;
  4884. #ifdef SO_NO_CHECK
  4885. setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
  4886. #endif
  4887. ast_debug(1, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
  4888. AST_LIST_INSERT_TAIL(&tpeers, tpeer, list);
  4889. }
  4890. }
  4891. AST_LIST_UNLOCK(&tpeers);
  4892. return tpeer;
  4893. }
  4894. static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
  4895. {
  4896. struct ast_frame *f;
  4897. struct iax2_trunk_peer *tpeer;
  4898. void *tmp, *ptr;
  4899. struct timeval now;
  4900. int res;
  4901. struct ast_iax2_meta_trunk_entry *met;
  4902. struct ast_iax2_meta_trunk_mini *mtm;
  4903. f = &fr->af;
  4904. tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
  4905. if (tpeer) {
  4906. if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
  4907. /* Need to reallocate space */
  4908. if (tpeer->trunkdataalloc < trunkmaxsize) {
  4909. if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
  4910. ast_mutex_unlock(&tpeer->lock);
  4911. return -1;
  4912. }
  4913. tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
  4914. tpeer->trunkdata = tmp;
  4915. ast_debug(1, "Expanded trunk '%s:%d' to %d bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), tpeer->trunkdataalloc);
  4916. } else {
  4917. 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));
  4918. ast_mutex_unlock(&tpeer->lock);
  4919. return -1;
  4920. }
  4921. }
  4922. /* Append to meta frame */
  4923. ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
  4924. if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS)) {
  4925. mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
  4926. mtm->len = htons(f->datalen);
  4927. mtm->mini.callno = htons(pvt->callno);
  4928. mtm->mini.ts = htons(0xffff & fr->ts);
  4929. ptr += sizeof(struct ast_iax2_meta_trunk_mini);
  4930. tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
  4931. } else {
  4932. met = (struct ast_iax2_meta_trunk_entry *)ptr;
  4933. /* Store call number and length in meta header */
  4934. met->callno = htons(pvt->callno);
  4935. met->len = htons(f->datalen);
  4936. /* Advance pointers/decrease length past trunk entry header */
  4937. ptr += sizeof(struct ast_iax2_meta_trunk_entry);
  4938. tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
  4939. }
  4940. /* Copy actual trunk data */
  4941. memcpy(ptr, f->data, f->datalen);
  4942. tpeer->trunkdatalen += f->datalen;
  4943. tpeer->calls++;
  4944. /* track the largest mtu we actually have sent */
  4945. if (tpeer->trunkdatalen + f->datalen + 4 > trunk_maxmtu)
  4946. trunk_maxmtu = tpeer->trunkdatalen + f->datalen + 4 ;
  4947. /* if we have enough for a full MTU, ship it now without waiting */
  4948. if (global_max_trunk_mtu > 0 && tpeer->trunkdatalen + f->datalen + 4 >= global_max_trunk_mtu) {
  4949. now = ast_tvnow();
  4950. res = send_trunk(tpeer, &now);
  4951. trunk_untimed ++;
  4952. }
  4953. ast_mutex_unlock(&tpeer->lock);
  4954. }
  4955. return 0;
  4956. }
  4957. /* IAX2 encryption requires 16 to 32 bytes of random padding to be present
  4958. * before the encryption data. This function randomizes that data. */
  4959. static void build_rand_pad(unsigned char *buf, ssize_t len)
  4960. {
  4961. long tmp;
  4962. for (tmp = ast_random(); len > 0; tmp = ast_random()) {
  4963. memcpy(buf, (unsigned char *) &tmp, (len > sizeof(tmp)) ? sizeof(tmp) : len);
  4964. buf += sizeof(tmp);
  4965. len -= sizeof(tmp);
  4966. }
  4967. }
  4968. static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
  4969. {
  4970. build_ecx_key(digest, pvt);
  4971. ast_aes_decrypt_key(digest, &pvt->dcx);
  4972. }
  4973. static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
  4974. {
  4975. /* it is required to hold the corresponding decrypt key to our encrypt key
  4976. * in the pvt struct because queued frames occasionally need to be decrypted and
  4977. * re-encrypted when updated for a retransmission */
  4978. build_rand_pad(pvt->semirand, sizeof(pvt->semirand));
  4979. ast_aes_encrypt_key(digest, &pvt->ecx);
  4980. ast_aes_decrypt_key(digest, &pvt->mydcx);
  4981. }
  4982. static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
  4983. {
  4984. #if 0
  4985. /* Debug with "fake encryption" */
  4986. int x;
  4987. if (len % 16)
  4988. ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
  4989. for (x=0;x<len;x++)
  4990. dst[x] = src[x] ^ 0xff;
  4991. #else
  4992. unsigned char lastblock[16] = { 0 };
  4993. int x;
  4994. while(len > 0) {
  4995. ast_aes_decrypt(src, dst, dcx);
  4996. for (x=0;x<16;x++)
  4997. dst[x] ^= lastblock[x];
  4998. memcpy(lastblock, src, sizeof(lastblock));
  4999. dst += 16;
  5000. src += 16;
  5001. len -= 16;
  5002. }
  5003. #endif
  5004. }
  5005. static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
  5006. {
  5007. #if 0
  5008. /* Debug with "fake encryption" */
  5009. int x;
  5010. if (len % 16)
  5011. ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
  5012. for (x=0;x<len;x++)
  5013. dst[x] = src[x] ^ 0xff;
  5014. #else
  5015. unsigned char curblock[16] = { 0 };
  5016. int x;
  5017. while(len > 0) {
  5018. for (x=0;x<16;x++)
  5019. curblock[x] ^= src[x];
  5020. ast_aes_encrypt(curblock, dst, ecx);
  5021. memcpy(curblock, dst, sizeof(curblock));
  5022. dst += 16;
  5023. src += 16;
  5024. len -= 16;
  5025. }
  5026. #endif
  5027. }
  5028. static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
  5029. {
  5030. int padding;
  5031. unsigned char *workspace;
  5032. workspace = alloca(*datalen);
  5033. memset(f, 0, sizeof(*f));
  5034. if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
  5035. struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
  5036. if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
  5037. return -1;
  5038. /* Decrypt */
  5039. memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
  5040. padding = 16 + (workspace[15] & 0x0f);
  5041. if (iaxdebug)
  5042. ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen, padding, workspace[15]);
  5043. if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
  5044. return -1;
  5045. *datalen -= padding;
  5046. memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
  5047. f->frametype = fh->type;
  5048. if (f->frametype == AST_FRAME_VIDEO) {
  5049. f->subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
  5050. } else {
  5051. f->subclass = uncompress_subclass(fh->csub);
  5052. }
  5053. } else {
  5054. struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
  5055. if (iaxdebug)
  5056. ast_debug(1, "Decoding mini with length %d\n", *datalen);
  5057. if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
  5058. return -1;
  5059. /* Decrypt */
  5060. memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
  5061. padding = 16 + (workspace[15] & 0x0f);
  5062. if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
  5063. return -1;
  5064. *datalen -= padding;
  5065. memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
  5066. }
  5067. return 0;
  5068. }
  5069. static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
  5070. {
  5071. int padding;
  5072. unsigned char *workspace;
  5073. workspace = alloca(*datalen + 32);
  5074. if (!workspace)
  5075. return -1;
  5076. if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
  5077. struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
  5078. if (iaxdebug)
  5079. ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
  5080. padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
  5081. padding = 16 + (padding & 0xf);
  5082. memcpy(workspace, poo, padding);
  5083. memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
  5084. workspace[15] &= 0xf0;
  5085. workspace[15] |= (padding & 0xf);
  5086. if (iaxdebug)
  5087. ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02x)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
  5088. *datalen += padding;
  5089. memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
  5090. if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
  5091. memcpy(poo, workspace + *datalen - 32, 32);
  5092. } else {
  5093. struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
  5094. if (iaxdebug)
  5095. ast_debug(1, "Encoding mini frame with length %d\n", *datalen);
  5096. padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
  5097. padding = 16 + (padding & 0xf);
  5098. memcpy(workspace, poo, padding);
  5099. memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
  5100. workspace[15] &= 0xf0;
  5101. workspace[15] |= (padding & 0x0f);
  5102. *datalen += padding;
  5103. memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
  5104. if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
  5105. memcpy(poo, workspace + *datalen - 32, 32);
  5106. }
  5107. return 0;
  5108. }
  5109. static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
  5110. {
  5111. int res=-1;
  5112. if (!ast_test_flag(iaxs[callno], IAX_KEYPOPULATED)) {
  5113. /* Search for possible keys, given secrets */
  5114. struct MD5Context md5;
  5115. unsigned char digest[16];
  5116. char *tmppw, *stringp;
  5117. tmppw = ast_strdupa(iaxs[callno]->secret);
  5118. stringp = tmppw;
  5119. while ((tmppw = strsep(&stringp, ";"))) {
  5120. MD5Init(&md5);
  5121. MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
  5122. MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
  5123. MD5Final(digest, &md5);
  5124. build_encryption_keys(digest, iaxs[callno]);
  5125. res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
  5126. if (!res) {
  5127. ast_set_flag(iaxs[callno], IAX_KEYPOPULATED);
  5128. break;
  5129. }
  5130. }
  5131. } else
  5132. res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
  5133. return res;
  5134. }
  5135. static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
  5136. {
  5137. /* Queue a packet for delivery on a given private structure. Use "ts" for
  5138. timestamp, or calculate if ts is 0. Send immediately without retransmission
  5139. or delayed, with retransmission */
  5140. struct ast_iax2_full_hdr *fh;
  5141. struct ast_iax2_mini_hdr *mh;
  5142. struct ast_iax2_video_hdr *vh;
  5143. struct {
  5144. struct iax_frame fr2;
  5145. unsigned char buffer[4096];
  5146. } frb;
  5147. struct iax_frame *fr;
  5148. int res;
  5149. int sendmini=0;
  5150. unsigned int lastsent;
  5151. unsigned int fts;
  5152. frb.fr2.afdatalen = sizeof(frb.buffer);
  5153. if (!pvt) {
  5154. ast_log(LOG_WARNING, "No private structure for packet?\n");
  5155. return -1;
  5156. }
  5157. lastsent = pvt->lastsent;
  5158. /* Calculate actual timestamp */
  5159. fts = calc_timestamp(pvt, ts, f);
  5160. /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
  5161. * (the endpoint should detect the lost packet itself). But, we want to do this here, so that we
  5162. * increment the "predicted timestamps" for voice, if we're predicting */
  5163. if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
  5164. return 0;
  5165. if ((ast_test_flag(pvt, IAX_TRUNK) ||
  5166. (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
  5167. ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
  5168. /* High two bytes are the same on timestamp, or sending on a trunk */ &&
  5169. (f->frametype == AST_FRAME_VOICE)
  5170. /* is a voice frame */ &&
  5171. (f->subclass == pvt->svoiceformat)
  5172. /* is the same type */ ) {
  5173. /* Force immediate rather than delayed transmission */
  5174. now = 1;
  5175. /* Mark that mini-style frame is appropriate */
  5176. sendmini = 1;
  5177. }
  5178. if ( f->frametype == AST_FRAME_VIDEO ) {
  5179. /*
  5180. * If the lower 15 bits of the timestamp roll over, or if
  5181. * the video format changed then send a full frame.
  5182. * Otherwise send a mini video frame
  5183. */
  5184. if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
  5185. ((f->subclass & ~0x1) == pvt->svideoformat)
  5186. ) {
  5187. now = 1;
  5188. sendmini = 1;
  5189. } else {
  5190. now = 0;
  5191. sendmini = 0;
  5192. }
  5193. pvt->lastvsent = fts;
  5194. }
  5195. if (f->frametype == AST_FRAME_IAX) {
  5196. /* 0x8000 marks this message as TX:, this bit will be stripped later */
  5197. pvt->last_iax_message = f->subclass | MARK_IAX_SUBCLASS_TX;
  5198. if (!pvt->first_iax_message) {
  5199. pvt->first_iax_message = pvt->last_iax_message;
  5200. }
  5201. }
  5202. /* Allocate an iax_frame */
  5203. if (now) {
  5204. fr = &frb.fr2;
  5205. } else
  5206. fr = iax_frame_new(DIRECTION_OUTGRESS, ast_test_flag(pvt, IAX_ENCRYPTED) ? f->datalen + 32 : f->datalen, (f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_VIDEO));
  5207. if (!fr) {
  5208. ast_log(LOG_WARNING, "Out of memory\n");
  5209. return -1;
  5210. }
  5211. /* Copy our prospective frame into our immediate or retransmitted wrapper */
  5212. iax_frame_wrap(fr, f);
  5213. fr->ts = fts;
  5214. fr->callno = pvt->callno;
  5215. fr->transfer = transfer;
  5216. fr->final = final;
  5217. fr->encmethods = 0;
  5218. if (!sendmini) {
  5219. /* We need a full frame */
  5220. if (seqno > -1)
  5221. fr->oseqno = seqno;
  5222. else
  5223. fr->oseqno = pvt->oseqno++;
  5224. fr->iseqno = pvt->iseqno;
  5225. fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
  5226. fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
  5227. fh->ts = htonl(fr->ts);
  5228. fh->oseqno = fr->oseqno;
  5229. if (transfer) {
  5230. fh->iseqno = 0;
  5231. } else
  5232. fh->iseqno = fr->iseqno;
  5233. /* Keep track of the last thing we've acknowledged */
  5234. if (!transfer)
  5235. pvt->aseqno = fr->iseqno;
  5236. fh->type = fr->af.frametype & 0xFF;
  5237. if (fr->af.frametype == AST_FRAME_VIDEO)
  5238. fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
  5239. else
  5240. fh->csub = compress_subclass(fr->af.subclass);
  5241. if (transfer) {
  5242. fr->dcallno = pvt->transfercallno;
  5243. } else
  5244. fr->dcallno = pvt->peercallno;
  5245. fh->dcallno = htons(fr->dcallno);
  5246. fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
  5247. fr->data = fh;
  5248. fr->retries = 0;
  5249. /* Retry after 2x the ping time has passed */
  5250. fr->retrytime = pvt->pingtime * 2;
  5251. if (fr->retrytime < MIN_RETRY_TIME)
  5252. fr->retrytime = MIN_RETRY_TIME;
  5253. if (fr->retrytime > MAX_RETRY_TIME)
  5254. fr->retrytime = MAX_RETRY_TIME;
  5255. /* Acks' don't get retried */
  5256. if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
  5257. fr->retries = -1;
  5258. else if (f->frametype == AST_FRAME_VOICE)
  5259. pvt->svoiceformat = f->subclass;
  5260. else if (f->frametype == AST_FRAME_VIDEO)
  5261. pvt->svideoformat = f->subclass & ~0x1;
  5262. if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
  5263. if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
  5264. if (iaxdebug) {
  5265. if (fr->transfer)
  5266. iax_showframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
  5267. else
  5268. iax_showframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
  5269. }
  5270. encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
  5271. fr->encmethods = pvt->encmethods;
  5272. fr->ecx = pvt->ecx;
  5273. fr->mydcx = pvt->mydcx;
  5274. memcpy(fr->semirand, pvt->semirand, sizeof(fr->semirand));
  5275. } else
  5276. ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
  5277. }
  5278. if (now) {
  5279. res = send_packet(fr);
  5280. } else
  5281. res = iax2_transmit(fr);
  5282. } else {
  5283. if (ast_test_flag(pvt, IAX_TRUNK)) {
  5284. iax2_trunk_queue(pvt, fr);
  5285. res = 0;
  5286. } else if (fr->af.frametype == AST_FRAME_VIDEO) {
  5287. /* Video frame have no sequence number */
  5288. fr->oseqno = -1;
  5289. fr->iseqno = -1;
  5290. vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
  5291. vh->zeros = 0;
  5292. vh->callno = htons(0x8000 | fr->callno);
  5293. vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
  5294. fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
  5295. fr->data = vh;
  5296. fr->retries = -1;
  5297. res = send_packet(fr);
  5298. } else {
  5299. /* Mini-frames have no sequence number */
  5300. fr->oseqno = -1;
  5301. fr->iseqno = -1;
  5302. /* Mini frame will do */
  5303. mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
  5304. mh->callno = htons(fr->callno);
  5305. mh->ts = htons(fr->ts & 0xFFFF);
  5306. fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
  5307. fr->data = mh;
  5308. fr->retries = -1;
  5309. if (pvt->transferring == TRANSFER_MEDIAPASS)
  5310. fr->transfer = 1;
  5311. if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
  5312. if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
  5313. encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
  5314. } else
  5315. ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
  5316. }
  5317. res = send_packet(fr);
  5318. }
  5319. }
  5320. return res;
  5321. }
  5322. static char *handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  5323. {
  5324. regex_t regexbuf;
  5325. int havepattern = 0;
  5326. #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
  5327. #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
  5328. struct iax2_user *user = NULL;
  5329. char auth[90];
  5330. char *pstr = "";
  5331. struct ao2_iterator i;
  5332. switch (cmd) {
  5333. case CLI_INIT:
  5334. e->command = "iax2 show users [like]";
  5335. e->usage =
  5336. "Usage: iax2 show users [like <pattern>]\n"
  5337. " Lists all known IAX2 users.\n"
  5338. " Optional regular expression pattern is used to filter the user list.\n";
  5339. return NULL;
  5340. case CLI_GENERATE:
  5341. return NULL;
  5342. }
  5343. switch (a->argc) {
  5344. case 5:
  5345. if (!strcasecmp(a->argv[3], "like")) {
  5346. if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
  5347. return CLI_SHOWUSAGE;
  5348. havepattern = 1;
  5349. } else
  5350. return CLI_SHOWUSAGE;
  5351. case 3:
  5352. break;
  5353. default:
  5354. return CLI_SHOWUSAGE;
  5355. }
  5356. ast_cli(a->fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
  5357. i = ao2_iterator_init(users, 0);
  5358. for (user = ao2_iterator_next(&i); user;
  5359. user_unref(user), user = ao2_iterator_next(&i)) {
  5360. if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
  5361. continue;
  5362. if (!ast_strlen_zero(user->secret)) {
  5363. ast_copy_string(auth,user->secret, sizeof(auth));
  5364. } else if (!ast_strlen_zero(user->inkeys)) {
  5365. snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
  5366. } else
  5367. ast_copy_string(auth, "-no secret-", sizeof(auth));
  5368. if(ast_test_flag(user,IAX_CODEC_NOCAP))
  5369. pstr = "REQ Only";
  5370. else if(ast_test_flag(user,IAX_CODEC_NOPREFS))
  5371. pstr = "Disabled";
  5372. else
  5373. pstr = ast_test_flag(user,IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
  5374. ast_cli(a->fd, FORMAT2, user->name, auth, user->authmethods,
  5375. user->contexts ? user->contexts->context : context,
  5376. user->ha ? "Yes" : "No", pstr);
  5377. }
  5378. ao2_iterator_destroy(&i);
  5379. if (havepattern)
  5380. regfree(&regexbuf);
  5381. return CLI_SUCCESS;
  5382. #undef FORMAT
  5383. #undef FORMAT2
  5384. }
  5385. static int __iax2_show_peers(int manager, int fd, struct mansession *s, int argc, char *argv[])
  5386. {
  5387. regex_t regexbuf;
  5388. int havepattern = 0;
  5389. int total_peers = 0;
  5390. int online_peers = 0;
  5391. int offline_peers = 0;
  5392. int unmonitored_peers = 0;
  5393. struct ao2_iterator i;
  5394. #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %s %-10s%s"
  5395. #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %s %-10s%s"
  5396. struct iax2_peer *peer = NULL;
  5397. char name[256];
  5398. int registeredonly=0;
  5399. char *term = manager ? "\r\n" : "\n";
  5400. char idtext[256] = "";
  5401. switch (argc) {
  5402. case 6:
  5403. if (!strcasecmp(argv[3], "registered"))
  5404. registeredonly = 1;
  5405. else
  5406. return RESULT_SHOWUSAGE;
  5407. if (!strcasecmp(argv[4], "like")) {
  5408. if (regcomp(&regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
  5409. return RESULT_SHOWUSAGE;
  5410. havepattern = 1;
  5411. } else
  5412. return RESULT_SHOWUSAGE;
  5413. break;
  5414. case 5:
  5415. if (!strcasecmp(argv[3], "like")) {
  5416. if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
  5417. return RESULT_SHOWUSAGE;
  5418. havepattern = 1;
  5419. } else
  5420. return RESULT_SHOWUSAGE;
  5421. break;
  5422. case 4:
  5423. if (!strcasecmp(argv[3], "registered"))
  5424. registeredonly = 1;
  5425. else
  5426. return RESULT_SHOWUSAGE;
  5427. break;
  5428. case 3:
  5429. break;
  5430. default:
  5431. return RESULT_SHOWUSAGE;
  5432. }
  5433. if (!s)
  5434. ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term);
  5435. i = ao2_iterator_init(peers, 0);
  5436. for (peer = ao2_iterator_next(&i); peer;
  5437. peer_unref(peer), peer = ao2_iterator_next(&i)) {
  5438. char nm[20];
  5439. char status[20];
  5440. char srch[2000];
  5441. int retstatus;
  5442. if (registeredonly && !peer->addr.sin_addr.s_addr)
  5443. continue;
  5444. if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0))
  5445. continue;
  5446. if (!ast_strlen_zero(peer->username))
  5447. snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
  5448. else
  5449. ast_copy_string(name, peer->name, sizeof(name));
  5450. retstatus = peer_status(peer, status, sizeof(status));
  5451. if (retstatus > 0)
  5452. online_peers++;
  5453. else if (!retstatus)
  5454. offline_peers++;
  5455. else
  5456. unmonitored_peers++;
  5457. ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
  5458. snprintf(srch, sizeof(srch), FORMAT, name,
  5459. peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
  5460. ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
  5461. nm,
  5462. ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
  5463. peer->encmethods ? "(E)" : " ", status, term);
  5464. if (s)
  5465. astman_append(s,
  5466. "Event: PeerEntry\r\n%s"
  5467. "Channeltype: IAX2\r\n"
  5468. "ChanObjectType: peer\r\n"
  5469. "ObjectName: %s\r\n"
  5470. "IPaddress: %s\r\n"
  5471. "IPport: %d\r\n"
  5472. "Dynamic: %s\r\n"
  5473. "Status: %s\r\n\r\n",
  5474. idtext,
  5475. name,
  5476. peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
  5477. ntohs(peer->addr.sin_port),
  5478. ast_test_flag(peer, IAX_DYNAMIC) ? "yes" : "no",
  5479. status);
  5480. else
  5481. ast_cli(fd, FORMAT, name,
  5482. peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
  5483. ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
  5484. nm,
  5485. ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
  5486. peer->encmethods ? "(E)" : " ", status, term);
  5487. total_peers++;
  5488. }
  5489. ao2_iterator_destroy(&i);
  5490. if (!s)
  5491. ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers, online_peers, offline_peers, unmonitored_peers, term);
  5492. if (havepattern)
  5493. regfree(&regexbuf);
  5494. return RESULT_SUCCESS;
  5495. #undef FORMAT
  5496. #undef FORMAT2
  5497. }
  5498. static char *handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  5499. {
  5500. struct iax2_thread *thread = NULL;
  5501. time_t t;
  5502. int threadcount = 0, dynamiccount = 0;
  5503. char type;
  5504. switch (cmd) {
  5505. case CLI_INIT:
  5506. e->command = "iax2 show threads";
  5507. e->usage =
  5508. "Usage: iax2 show threads\n"
  5509. " Lists status of IAX helper threads\n";
  5510. return NULL;
  5511. case CLI_GENERATE:
  5512. return NULL;
  5513. }
  5514. if (a->argc != 3)
  5515. return CLI_SHOWUSAGE;
  5516. ast_cli(a->fd, "IAX2 Thread Information\n");
  5517. time(&t);
  5518. ast_cli(a->fd, "Idle Threads:\n");
  5519. AST_LIST_LOCK(&idle_list);
  5520. AST_LIST_TRAVERSE(&idle_list, thread, list) {
  5521. #ifdef DEBUG_SCHED_MULTITHREAD
  5522. ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n",
  5523. thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
  5524. #else
  5525. ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n",
  5526. thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
  5527. #endif
  5528. threadcount++;
  5529. }
  5530. AST_LIST_UNLOCK(&idle_list);
  5531. ast_cli(a->fd, "Active Threads:\n");
  5532. AST_LIST_LOCK(&active_list);
  5533. AST_LIST_TRAVERSE(&active_list, thread, list) {
  5534. if (thread->type == IAX_THREAD_TYPE_DYNAMIC)
  5535. type = 'D';
  5536. else
  5537. type = 'P';
  5538. #ifdef DEBUG_SCHED_MULTITHREAD
  5539. ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d, func='%s'\n",
  5540. type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
  5541. #else
  5542. ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d\n",
  5543. type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
  5544. #endif
  5545. threadcount++;
  5546. }
  5547. AST_LIST_UNLOCK(&active_list);
  5548. ast_cli(a->fd, "Dynamic Threads:\n");
  5549. AST_LIST_LOCK(&dynamic_list);
  5550. AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
  5551. #ifdef DEBUG_SCHED_MULTITHREAD
  5552. ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n",
  5553. thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
  5554. #else
  5555. ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n",
  5556. thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
  5557. #endif
  5558. dynamiccount++;
  5559. }
  5560. AST_LIST_UNLOCK(&dynamic_list);
  5561. ast_cli(a->fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
  5562. return CLI_SUCCESS;
  5563. }
  5564. static char *handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  5565. {
  5566. struct iax2_peer *p;
  5567. switch (cmd) {
  5568. case CLI_INIT:
  5569. e->command = "iax2 unregister";
  5570. e->usage =
  5571. "Usage: iax2 unregister <peername>\n"
  5572. " Unregister (force expiration) an IAX2 peer from the registry.\n";
  5573. return NULL;
  5574. case CLI_GENERATE:
  5575. return complete_iax2_unregister(a->line, a->word, a->pos, a->n);
  5576. }
  5577. if (a->argc != 3)
  5578. return CLI_SHOWUSAGE;
  5579. p = find_peer(a->argv[2], 1);
  5580. if (p) {
  5581. if (p->expire > 0) {
  5582. struct iax2_peer tmp_peer = {
  5583. .name = a->argv[2],
  5584. };
  5585. struct iax2_peer *peer;
  5586. peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
  5587. if (peer) {
  5588. expire_registry(peer_ref(peer)); /* will release its own reference when done */
  5589. peer_unref(peer); /* ref from ao2_find() */
  5590. ast_cli(a->fd, "Peer %s unregistered\n", a->argv[2]);
  5591. } else {
  5592. ast_cli(a->fd, "Peer %s not found\n", a->argv[2]);
  5593. }
  5594. } else {
  5595. ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
  5596. }
  5597. } else {
  5598. ast_cli(a->fd, "Peer unknown: %s. Not unregistered\n", a->argv[2]);
  5599. }
  5600. return CLI_SUCCESS;
  5601. }
  5602. static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state)
  5603. {
  5604. int which = 0;
  5605. struct iax2_peer *p = NULL;
  5606. char *res = NULL;
  5607. int wordlen = strlen(word);
  5608. /* 0 - iax2; 1 - unregister; 2 - <peername> */
  5609. if (pos == 2) {
  5610. struct ao2_iterator i = ao2_iterator_init(peers, 0);
  5611. while ((p = ao2_iterator_next(&i))) {
  5612. if (!strncasecmp(p->name, word, wordlen) &&
  5613. ++which > state && p->expire > 0) {
  5614. res = ast_strdup(p->name);
  5615. peer_unref(p);
  5616. break;
  5617. }
  5618. peer_unref(p);
  5619. }
  5620. ao2_iterator_destroy(&i);
  5621. }
  5622. return res;
  5623. }
  5624. static char *handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  5625. {
  5626. switch (cmd) {
  5627. case CLI_INIT:
  5628. e->command = "iax2 show peers";
  5629. e->usage =
  5630. "Usage: iax2 show peers [registered] [like <pattern>]\n"
  5631. " Lists all known IAX2 peers.\n"
  5632. " Optional 'registered' argument lists only peers with known addresses.\n"
  5633. " Optional regular expression pattern is used to filter the peer list.\n";
  5634. return NULL;
  5635. case CLI_GENERATE:
  5636. return NULL;
  5637. }
  5638. switch (__iax2_show_peers(0, a->fd, NULL, a->argc, a->argv)) {
  5639. case RESULT_SHOWUSAGE:
  5640. return CLI_SHOWUSAGE;
  5641. case RESULT_FAILURE:
  5642. return CLI_FAILURE;
  5643. default:
  5644. return CLI_SUCCESS;
  5645. }
  5646. }
  5647. static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
  5648. {
  5649. ast_cli_netstats(s, -1, 0);
  5650. astman_append(s, "\r\n");
  5651. return RESULT_SUCCESS;
  5652. }
  5653. static char *handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  5654. {
  5655. struct iax_firmware *cur = NULL;
  5656. switch (cmd) {
  5657. case CLI_INIT:
  5658. e->command = "iax2 show firmware";
  5659. e->usage =
  5660. "Usage: iax2 show firmware\n"
  5661. " Lists all known IAX firmware images.\n";
  5662. return NULL;
  5663. case CLI_GENERATE:
  5664. return NULL;
  5665. }
  5666. if (a->argc != 3 && a->argc != 4)
  5667. return CLI_SHOWUSAGE;
  5668. ast_cli(a->fd, "%-15.15s %-15.15s %-15.15s\n", "Device", "Version", "Size");
  5669. AST_LIST_LOCK(&firmwares);
  5670. AST_LIST_TRAVERSE(&firmwares, cur, list) {
  5671. if ((a->argc == 3) || (!strcasecmp(a->argv[3], (char *) cur->fwh->devname))) {
  5672. ast_cli(a->fd, "%-15.15s %-15d %-15d\n", cur->fwh->devname,
  5673. ntohs(cur->fwh->version), (int)ntohl(cur->fwh->datalen));
  5674. }
  5675. }
  5676. AST_LIST_UNLOCK(&firmwares);
  5677. return CLI_SUCCESS;
  5678. }
  5679. /*! \brief callback to display iax peers in manager */
  5680. static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
  5681. {
  5682. char *a[] = { "iax2", "show", "users" };
  5683. const char *id = astman_get_header(m,"ActionID");
  5684. char idtext[256] = "";
  5685. if (!ast_strlen_zero(id))
  5686. snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
  5687. astman_send_ack(s, m, "Peer status list will follow");
  5688. return __iax2_show_peers(1, -1, s, 3, a );
  5689. }
  5690. /*! \brief callback to display iax peers in manager format */
  5691. static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
  5692. {
  5693. struct iax2_peer *peer = NULL;
  5694. int peer_count = 0;
  5695. char nm[20];
  5696. char status[20];
  5697. const char *id = astman_get_header(m,"ActionID");
  5698. char idtext[256] = "";
  5699. struct ao2_iterator i;
  5700. if (!ast_strlen_zero(id))
  5701. snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
  5702. astman_append(s, "Response: Success\r\n%sMessage: IAX Peer status list will follow\r\n\r\n", idtext);
  5703. i = ao2_iterator_init(peers, 0);
  5704. for (peer = ao2_iterator_next(&i); peer; peer_unref(peer), peer = ao2_iterator_next(&i)) {
  5705. astman_append(s, "Event: PeerEntry\r\n%sChanneltype: IAX\r\n", idtext);
  5706. if (!ast_strlen_zero(peer->username)) {
  5707. astman_append(s, "ObjectName: %s\r\nObjectUsername: %s\r\n", peer->name, peer->username);
  5708. } else {
  5709. astman_append(s, "ObjectName: %s\r\n", peer->name);
  5710. }
  5711. astman_append(s, "ChanObjectType: peer\r\n");
  5712. astman_append(s, "IPaddress: %s\r\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-");
  5713. ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
  5714. astman_append(s, "Mask: %s\r\n", nm);
  5715. astman_append(s, "Port: %d\r\n", ntohs(peer->addr.sin_port));
  5716. astman_append(s, "Dynamic: %s\r\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes" : "No");
  5717. peer_status(peer, status, sizeof(status));
  5718. astman_append(s, "Status: %s\r\n\r\n", status);
  5719. peer_count++;
  5720. }
  5721. ao2_iterator_destroy(&i);
  5722. astman_append(s, "Event: PeerlistComplete\r\n%sListItems: %d\r\n\r\n", idtext, peer_count);
  5723. return RESULT_SUCCESS;
  5724. }
  5725. static char *regstate2str(int regstate)
  5726. {
  5727. switch(regstate) {
  5728. case REG_STATE_UNREGISTERED:
  5729. return "Unregistered";
  5730. case REG_STATE_REGSENT:
  5731. return "Request Sent";
  5732. case REG_STATE_AUTHSENT:
  5733. return "Auth. Sent";
  5734. case REG_STATE_REGISTERED:
  5735. return "Registered";
  5736. case REG_STATE_REJECTED:
  5737. return "Rejected";
  5738. case REG_STATE_TIMEOUT:
  5739. return "Timeout";
  5740. case REG_STATE_NOAUTH:
  5741. return "No Authentication";
  5742. default:
  5743. return "Unknown";
  5744. }
  5745. }
  5746. static char *handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  5747. {
  5748. #define FORMAT2 "%-20.20s %-6.6s %-10.10s %-20.20s %8.8s %s\n"
  5749. #define FORMAT "%-20.20s %-6.6s %-10.10s %-20.20s %8d %s\n"
  5750. struct iax2_registry *reg = NULL;
  5751. char host[80];
  5752. char perceived[80];
  5753. int counter = 0;
  5754. switch (cmd) {
  5755. case CLI_INIT:
  5756. e->command = "iax2 show registry";
  5757. e->usage =
  5758. "Usage: iax2 show registry\n"
  5759. " Lists all registration requests and status.\n";
  5760. return NULL;
  5761. case CLI_GENERATE:
  5762. return NULL;
  5763. }
  5764. if (a->argc != 3)
  5765. return CLI_SHOWUSAGE;
  5766. ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
  5767. AST_LIST_LOCK(&registrations);
  5768. AST_LIST_TRAVERSE(&registrations, reg, entry) {
  5769. snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
  5770. if (reg->us.sin_addr.s_addr)
  5771. snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
  5772. else
  5773. ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
  5774. ast_cli(a->fd, FORMAT, host,
  5775. (reg->dnsmgr) ? "Y" : "N",
  5776. reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
  5777. counter++;
  5778. }
  5779. AST_LIST_UNLOCK(&registrations);
  5780. ast_cli(a->fd, "%d IAX2 registrations.\n", counter);
  5781. return CLI_SUCCESS;
  5782. #undef FORMAT
  5783. #undef FORMAT2
  5784. }
  5785. static char *handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  5786. {
  5787. #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s %s %9s\n"
  5788. #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"
  5789. #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
  5790. int x;
  5791. int numchans = 0;
  5792. char first_message[10] = { 0, };
  5793. char last_message[10] = { 0, };
  5794. switch (cmd) {
  5795. case CLI_INIT:
  5796. e->command = "iax2 show channels";
  5797. e->usage =
  5798. "Usage: iax2 show channels\n"
  5799. " Lists all currently active IAX channels.\n";
  5800. return NULL;
  5801. case CLI_GENERATE:
  5802. return NULL;
  5803. }
  5804. if (a->argc != 3)
  5805. return CLI_SHOWUSAGE;
  5806. ast_cli(a->fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format", "FirstMsg", "LastMsg");
  5807. for (x = 0; x < ARRAY_LEN(iaxs); x++) {
  5808. ast_mutex_lock(&iaxsl[x]);
  5809. if (iaxs[x]) {
  5810. int lag, jitter, localdelay;
  5811. jb_info jbinfo;
  5812. if (ast_test_flag(iaxs[x], IAX_USEJITTERBUF)) {
  5813. jb_getinfo(iaxs[x]->jb, &jbinfo);
  5814. jitter = jbinfo.jitter;
  5815. localdelay = jbinfo.current - jbinfo.min;
  5816. } else {
  5817. jitter = -1;
  5818. localdelay = 0;
  5819. }
  5820. iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
  5821. iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
  5822. lag = iaxs[x]->remote_rr.delay;
  5823. ast_cli(a->fd, FORMAT,
  5824. iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
  5825. ast_inet_ntoa(iaxs[x]->addr.sin_addr),
  5826. S_OR(iaxs[x]->username, "(None)"),
  5827. iaxs[x]->callno, iaxs[x]->peercallno,
  5828. iaxs[x]->oseqno, iaxs[x]->iseqno,
  5829. lag,
  5830. jitter,
  5831. localdelay,
  5832. ast_getformatname(iaxs[x]->voiceformat),
  5833. (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
  5834. first_message,
  5835. (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
  5836. last_message);
  5837. numchans++;
  5838. }
  5839. ast_mutex_unlock(&iaxsl[x]);
  5840. }
  5841. ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
  5842. return CLI_SUCCESS;
  5843. #undef FORMAT
  5844. #undef FORMAT2
  5845. #undef FORMATB
  5846. }
  5847. static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
  5848. {
  5849. int x;
  5850. int numchans = 0;
  5851. char first_message[10] = { 0, };
  5852. char last_message[10] = { 0, };
  5853. #define ACN_FORMAT1 "%-20.25s %4d %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d %s%s %4s%s\n"
  5854. #define ACN_FORMAT2 "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"
  5855. for (x = 0; x < ARRAY_LEN(iaxs); x++) {
  5856. ast_mutex_lock(&iaxsl[x]);
  5857. if (iaxs[x]) {
  5858. int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
  5859. jb_info jbinfo;
  5860. iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
  5861. iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
  5862. if(ast_test_flag(iaxs[x], IAX_USEJITTERBUF)) {
  5863. jb_getinfo(iaxs[x]->jb, &jbinfo);
  5864. localjitter = jbinfo.jitter;
  5865. localdelay = jbinfo.current - jbinfo.min;
  5866. locallost = jbinfo.frames_lost;
  5867. locallosspct = jbinfo.losspct/1000;
  5868. localdropped = jbinfo.frames_dropped;
  5869. localooo = jbinfo.frames_ooo;
  5870. } else {
  5871. localjitter = -1;
  5872. localdelay = 0;
  5873. locallost = -1;
  5874. locallosspct = -1;
  5875. localdropped = 0;
  5876. localooo = -1;
  5877. }
  5878. if (s)
  5879. astman_append(s, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
  5880. iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
  5881. iaxs[x]->pingtime,
  5882. localjitter,
  5883. localdelay,
  5884. locallost,
  5885. locallosspct,
  5886. localdropped,
  5887. localooo,
  5888. iaxs[x]->frames_received/1000,
  5889. iaxs[x]->remote_rr.jitter,
  5890. iaxs[x]->remote_rr.delay,
  5891. iaxs[x]->remote_rr.losscnt,
  5892. iaxs[x]->remote_rr.losspct,
  5893. iaxs[x]->remote_rr.dropped,
  5894. iaxs[x]->remote_rr.ooo,
  5895. iaxs[x]->remote_rr.packets/1000,
  5896. (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
  5897. first_message,
  5898. (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
  5899. last_message);
  5900. else
  5901. ast_cli(fd, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
  5902. iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
  5903. iaxs[x]->pingtime,
  5904. localjitter,
  5905. localdelay,
  5906. locallost,
  5907. locallosspct,
  5908. localdropped,
  5909. localooo,
  5910. iaxs[x]->frames_received/1000,
  5911. iaxs[x]->remote_rr.jitter,
  5912. iaxs[x]->remote_rr.delay,
  5913. iaxs[x]->remote_rr.losscnt,
  5914. iaxs[x]->remote_rr.losspct,
  5915. iaxs[x]->remote_rr.dropped,
  5916. iaxs[x]->remote_rr.ooo,
  5917. iaxs[x]->remote_rr.packets/1000,
  5918. (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
  5919. first_message,
  5920. (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
  5921. last_message);
  5922. numchans++;
  5923. }
  5924. ast_mutex_unlock(&iaxsl[x]);
  5925. }
  5926. return numchans;
  5927. }
  5928. static char *handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  5929. {
  5930. int numchans = 0;
  5931. switch (cmd) {
  5932. case CLI_INIT:
  5933. e->command = "iax2 show netstats";
  5934. e->usage =
  5935. "Usage: iax2 show netstats\n"
  5936. " Lists network status for all currently active IAX channels.\n";
  5937. return NULL;
  5938. case CLI_GENERATE:
  5939. return NULL;
  5940. }
  5941. if (a->argc != 3)
  5942. return CLI_SHOWUSAGE;
  5943. ast_cli(a->fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
  5944. ast_cli(a->fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts FirstMsg LastMsg\n");
  5945. numchans = ast_cli_netstats(NULL, a->fd, 1);
  5946. ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
  5947. return CLI_SUCCESS;
  5948. }
  5949. static char *handle_cli_iax2_set_debug_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  5950. {
  5951. switch (cmd) {
  5952. case CLI_INIT:
  5953. e->command = "iax2 set debug [off]";
  5954. e->usage =
  5955. "Usage: iax2 set debug [off]\n"
  5956. " Enables/Disables dumping of IAX packets for debugging purposes.\n";
  5957. return NULL;
  5958. case CLI_GENERATE:
  5959. return NULL;
  5960. }
  5961. if (a->argc < 3 || a->argc > 4)
  5962. return CLI_SHOWUSAGE;
  5963. if (a->argc == 3) {
  5964. iaxdebug = 1;
  5965. ast_cli(a->fd, "IAX2 Debugging Enabled\n");
  5966. } else {
  5967. iaxdebug = 0;
  5968. ast_cli(a->fd, "IAX2 Debugging Disabled\n");
  5969. }
  5970. return CLI_SUCCESS;
  5971. }
  5972. static char *handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  5973. {
  5974. switch (cmd) {
  5975. case CLI_INIT:
  5976. e->command = "iax2 set debug {on|off}";
  5977. e->usage =
  5978. "Usage: iax2 set debug {on|off}\n"
  5979. " Enables/Disables dumping of IAX packets for debugging purposes.\n";
  5980. return NULL;
  5981. case CLI_GENERATE:
  5982. return NULL;
  5983. }
  5984. if (a->argc != e->args)
  5985. return CLI_SHOWUSAGE;
  5986. if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
  5987. iaxdebug = 1;
  5988. ast_cli(a->fd, "IAX2 Debugging Enabled\n");
  5989. } else {
  5990. iaxdebug = 0;
  5991. ast_cli(a->fd, "IAX2 Debugging Disabled\n");
  5992. }
  5993. return CLI_SUCCESS;
  5994. }
  5995. static char *handle_cli_iax2_set_debug_trunk_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  5996. {
  5997. switch (cmd) {
  5998. case CLI_INIT:
  5999. e->command = "iax2 set debug trunk [off]";
  6000. e->usage =
  6001. "Usage: iax2 set debug trunk [off]\n"
  6002. " Enables/Disables debugging of IAX trunking\n";
  6003. return NULL;
  6004. case CLI_GENERATE:
  6005. return NULL;
  6006. }
  6007. if (a->argc < 4 || a->argc > 5)
  6008. return CLI_SHOWUSAGE;
  6009. if (a->argc == 4) {
  6010. iaxtrunkdebug = 1;
  6011. ast_cli(a->fd, "IAX2 Trunk Debugging Enabled\n");
  6012. } else {
  6013. iaxtrunkdebug = 0;
  6014. ast_cli(a->fd, "IAX2 Trunk Debugging Disabled\n");
  6015. }
  6016. return CLI_SUCCESS;
  6017. }
  6018. static char *handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  6019. {
  6020. switch (cmd) {
  6021. case CLI_INIT:
  6022. e->command = "iax2 set debug trunk {on|off}";
  6023. e->usage =
  6024. "Usage: iax2 set debug trunk {on|off}\n"
  6025. " Enables/Disables debugging of IAX trunking\n";
  6026. return NULL;
  6027. case CLI_GENERATE:
  6028. return NULL;
  6029. }
  6030. if (a->argc != e->args)
  6031. return CLI_SHOWUSAGE;
  6032. if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
  6033. iaxtrunkdebug = 1;
  6034. ast_cli(a->fd, "IAX2 Trunk Debugging Enabled\n");
  6035. } else {
  6036. iaxtrunkdebug = 0;
  6037. ast_cli(a->fd, "IAX2 Trunk Debugging Disabled\n");
  6038. }
  6039. return CLI_SUCCESS;
  6040. }
  6041. static char *handle_cli_iax2_set_debug_jb_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  6042. {
  6043. switch (cmd) {
  6044. case CLI_INIT:
  6045. e->command = "iax2 set debug jb [off]";
  6046. e->usage =
  6047. "Usage: iax2 set debug jb [off]\n"
  6048. " Enables/Disables jitterbuffer debugging information\n";
  6049. return NULL;
  6050. case CLI_GENERATE:
  6051. return NULL;
  6052. }
  6053. if (a->argc < 4 || a->argc > 5)
  6054. return CLI_SHOWUSAGE;
  6055. if (a->argc == 4) {
  6056. jb_setoutput(jb_error_output, jb_warning_output, jb_debug_output);
  6057. ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Enabled\n");
  6058. } else {
  6059. jb_setoutput(jb_error_output, jb_warning_output, NULL);
  6060. ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Disabled\n");
  6061. }
  6062. return CLI_SUCCESS;
  6063. }
  6064. static char *handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  6065. {
  6066. switch (cmd) {
  6067. case CLI_INIT:
  6068. e->command = "iax2 set debug jb {on|off}";
  6069. e->usage =
  6070. "Usage: iax2 set debug jb {on|off}\n"
  6071. " Enables/Disables jitterbuffer debugging information\n";
  6072. return NULL;
  6073. case CLI_GENERATE:
  6074. return NULL;
  6075. }
  6076. if (a->argc != e->args)
  6077. return CLI_SHOWUSAGE;
  6078. if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
  6079. jb_setoutput(jb_error_output, jb_warning_output, jb_debug_output);
  6080. ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Enabled\n");
  6081. } else {
  6082. jb_setoutput(jb_error_output, jb_warning_output, NULL);
  6083. ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Disabled\n");
  6084. }
  6085. return CLI_SUCCESS;
  6086. }
  6087. static int iax2_write(struct ast_channel *c, struct ast_frame *f)
  6088. {
  6089. unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
  6090. int res = -1;
  6091. ast_mutex_lock(&iaxsl[callno]);
  6092. if (iaxs[callno]) {
  6093. /* If there's an outstanding error, return failure now */
  6094. if (!iaxs[callno]->error) {
  6095. if (ast_test_flag(iaxs[callno], IAX_ALREADYGONE))
  6096. res = 0;
  6097. /* Don't waste bandwidth sending null frames */
  6098. else if (f->frametype == AST_FRAME_NULL)
  6099. res = 0;
  6100. else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag(iaxs[callno], IAX_QUELCH))
  6101. res = 0;
  6102. else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
  6103. res = 0;
  6104. else
  6105. /* Simple, just queue for transmission */
  6106. res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
  6107. } else {
  6108. ast_debug(1, "Write error: %s\n", strerror(errno));
  6109. }
  6110. }
  6111. /* If it's already gone, just return */
  6112. ast_mutex_unlock(&iaxsl[callno]);
  6113. return res;
  6114. }
  6115. static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
  6116. int now, int transfer, int final)
  6117. {
  6118. struct ast_frame f = { 0, };
  6119. int res = 0;
  6120. f.frametype = type;
  6121. f.subclass = command;
  6122. f.datalen = datalen;
  6123. f.src = __FUNCTION__;
  6124. f.data = (void *) data;
  6125. if ((res = queue_signalling(i, &f)) <= 0) {
  6126. return res;
  6127. }
  6128. return iax2_send(i, &f, ts, seqno, now, transfer, final);
  6129. }
  6130. static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
  6131. {
  6132. return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
  6133. }
  6134. static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
  6135. {
  6136. int res;
  6137. ast_mutex_lock(&iaxsl[callno]);
  6138. res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
  6139. ast_mutex_unlock(&iaxsl[callno]);
  6140. return res;
  6141. }
  6142. /*!
  6143. * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
  6144. * the pvt struct for the given call number may disappear during its
  6145. * execution.
  6146. */
  6147. 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)
  6148. {
  6149. int call_num = i->callno;
  6150. /* It is assumed that the callno has already been locked */
  6151. iax2_predestroy(i->callno);
  6152. if (!iaxs[call_num])
  6153. return -1;
  6154. return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
  6155. }
  6156. 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)
  6157. {
  6158. return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
  6159. }
  6160. static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
  6161. {
  6162. return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
  6163. }
  6164. static int apply_context(struct iax2_context *con, const char *context)
  6165. {
  6166. while(con) {
  6167. if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
  6168. return -1;
  6169. con = con->next;
  6170. }
  6171. return 0;
  6172. }
  6173. static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
  6174. {
  6175. /* Start pessimistic */
  6176. int res = -1;
  6177. int version = 2;
  6178. struct iax2_user *user = NULL, *best = NULL;
  6179. int bestscore = 0;
  6180. int gotcapability = 0;
  6181. struct ast_variable *v = NULL, *tmpvar = NULL;
  6182. struct ao2_iterator i;
  6183. if (!iaxs[callno])
  6184. return res;
  6185. if (ies->called_number)
  6186. ast_string_field_set(iaxs[callno], exten, ies->called_number);
  6187. if (ies->calling_number) {
  6188. if (ast_test_flag(&globalflags, IAX_SHRINKCALLERID)) {
  6189. ast_shrink_phone_number(ies->calling_number);
  6190. }
  6191. ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
  6192. }
  6193. if (ies->calling_name)
  6194. ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
  6195. if (ies->calling_ani)
  6196. ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
  6197. if (ies->dnid)
  6198. ast_string_field_set(iaxs[callno], dnid, ies->dnid);
  6199. if (ies->rdnis)
  6200. ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
  6201. if (ies->called_context)
  6202. ast_string_field_set(iaxs[callno], context, ies->called_context);
  6203. if (ies->language)
  6204. ast_string_field_set(iaxs[callno], language, ies->language);
  6205. if (ies->username)
  6206. ast_string_field_set(iaxs[callno], username, ies->username);
  6207. if (ies->calling_ton > -1)
  6208. iaxs[callno]->calling_ton = ies->calling_ton;
  6209. if (ies->calling_tns > -1)
  6210. iaxs[callno]->calling_tns = ies->calling_tns;
  6211. if (ies->calling_pres > -1)
  6212. iaxs[callno]->calling_pres = ies->calling_pres;
  6213. if (ies->format)
  6214. iaxs[callno]->peerformat = ies->format;
  6215. if (ies->adsicpe)
  6216. iaxs[callno]->peeradsicpe = ies->adsicpe;
  6217. if (ies->capability) {
  6218. gotcapability = 1;
  6219. iaxs[callno]->peercapability = ies->capability;
  6220. }
  6221. if (ies->version)
  6222. version = ies->version;
  6223. /* Use provided preferences until told otherwise for actual preferences */
  6224. if(ies->codec_prefs) {
  6225. ast_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
  6226. ast_codec_pref_convert(&iaxs[callno]->prefs, ies->codec_prefs, 32, 0);
  6227. }
  6228. if (!gotcapability)
  6229. iaxs[callno]->peercapability = iaxs[callno]->peerformat;
  6230. if (version > IAX_PROTO_VERSION) {
  6231. ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
  6232. ast_inet_ntoa(sin->sin_addr), version);
  6233. return res;
  6234. }
  6235. /* Search the userlist for a compatible entry, and fill in the rest */
  6236. i = ao2_iterator_init(users, 0);
  6237. while ((user = ao2_iterator_next(&i))) {
  6238. if ((ast_strlen_zero(iaxs[callno]->username) || /* No username specified */
  6239. !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
  6240. && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
  6241. && (ast_strlen_zero(iaxs[callno]->context) || /* No context specified */
  6242. apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
  6243. if (!ast_strlen_zero(iaxs[callno]->username)) {
  6244. /* Exact match, stop right now. */
  6245. if (best)
  6246. user_unref(best);
  6247. best = user;
  6248. break;
  6249. } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
  6250. /* No required authentication */
  6251. if (user->ha) {
  6252. /* There was host authentication and we passed, bonus! */
  6253. if (bestscore < 4) {
  6254. bestscore = 4;
  6255. if (best)
  6256. user_unref(best);
  6257. best = user;
  6258. continue;
  6259. }
  6260. } else {
  6261. /* No host access, but no secret, either, not bad */
  6262. if (bestscore < 3) {
  6263. bestscore = 3;
  6264. if (best)
  6265. user_unref(best);
  6266. best = user;
  6267. continue;
  6268. }
  6269. }
  6270. } else {
  6271. if (user->ha) {
  6272. /* Authentication, but host access too, eh, it's something.. */
  6273. if (bestscore < 2) {
  6274. bestscore = 2;
  6275. if (best)
  6276. user_unref(best);
  6277. best = user;
  6278. continue;
  6279. }
  6280. } else {
  6281. /* Authentication and no host access... This is our baseline */
  6282. if (bestscore < 1) {
  6283. bestscore = 1;
  6284. if (best)
  6285. user_unref(best);
  6286. best = user;
  6287. continue;
  6288. }
  6289. }
  6290. }
  6291. }
  6292. user_unref(user);
  6293. }
  6294. ao2_iterator_destroy(&i);
  6295. user = best;
  6296. if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
  6297. user = realtime_user(iaxs[callno]->username, sin);
  6298. if (user && !ast_strlen_zero(iaxs[callno]->context) && /* No context specified */
  6299. !apply_context(user->contexts, iaxs[callno]->context)) { /* Context is permitted */
  6300. user = user_unref(user);
  6301. }
  6302. }
  6303. if (user) {
  6304. /* We found our match (use the first) */
  6305. /* copy vars */
  6306. for (v = user->vars ; v ; v = v->next) {
  6307. if((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
  6308. tmpvar->next = iaxs[callno]->vars;
  6309. iaxs[callno]->vars = tmpvar;
  6310. }
  6311. }
  6312. /* If a max AUTHREQ restriction is in place, activate it */
  6313. if (user->maxauthreq > 0)
  6314. ast_set_flag(iaxs[callno], IAX_MAXAUTHREQ);
  6315. iaxs[callno]->prefs = user->prefs;
  6316. ast_copy_flags(iaxs[callno], user, IAX_CODEC_USER_FIRST);
  6317. ast_copy_flags(iaxs[callno], user, IAX_CODEC_NOPREFS);
  6318. ast_copy_flags(iaxs[callno], user, IAX_CODEC_NOCAP);
  6319. iaxs[callno]->encmethods = user->encmethods;
  6320. /* Store the requested username if not specified */
  6321. if (ast_strlen_zero(iaxs[callno]->username))
  6322. ast_string_field_set(iaxs[callno], username, user->name);
  6323. /* Store whether this is a trunked call, too, of course, and move if appropriate */
  6324. ast_copy_flags(iaxs[callno], user, IAX_TRUNK);
  6325. iaxs[callno]->capability = user->capability;
  6326. /* And use the default context */
  6327. if (ast_strlen_zero(iaxs[callno]->context)) {
  6328. if (user->contexts)
  6329. ast_string_field_set(iaxs[callno], context, user->contexts->context);
  6330. else
  6331. ast_string_field_set(iaxs[callno], context, context);
  6332. }
  6333. /* And any input keys */
  6334. ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
  6335. /* And the permitted authentication methods */
  6336. iaxs[callno]->authmethods = user->authmethods;
  6337. iaxs[callno]->adsi = user->adsi;
  6338. /* If the user has callerid, override the remote caller id. */
  6339. if (ast_test_flag(user, IAX_HASCALLERID)) {
  6340. iaxs[callno]->calling_tns = 0;
  6341. iaxs[callno]->calling_ton = 0;
  6342. ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
  6343. ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
  6344. ast_string_field_set(iaxs[callno], ani, user->cid_num);
  6345. iaxs[callno]->calling_pres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
  6346. } else if (ast_strlen_zero(iaxs[callno]->cid_num) && ast_strlen_zero(iaxs[callno]->cid_name)) {
  6347. iaxs[callno]->calling_pres = AST_PRES_NUMBER_NOT_AVAILABLE;
  6348. } /* else user is allowed to set their own CID settings */
  6349. if (!ast_strlen_zero(user->accountcode))
  6350. ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
  6351. if (!ast_strlen_zero(user->mohinterpret))
  6352. ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
  6353. if (!ast_strlen_zero(user->mohsuggest))
  6354. ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
  6355. if (user->amaflags)
  6356. iaxs[callno]->amaflags = user->amaflags;
  6357. if (!ast_strlen_zero(user->language))
  6358. ast_string_field_set(iaxs[callno], language, user->language);
  6359. ast_copy_flags(iaxs[callno], user, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
  6360. /* Keep this check last */
  6361. if (!ast_strlen_zero(user->dbsecret)) {
  6362. char *family, *key=NULL;
  6363. char buf[80];
  6364. family = ast_strdupa(user->dbsecret);
  6365. key = strchr(family, '/');
  6366. if (key) {
  6367. *key = '\0';
  6368. key++;
  6369. }
  6370. if (!key || ast_db_get(family, key, buf, sizeof(buf)))
  6371. ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
  6372. else
  6373. ast_string_field_set(iaxs[callno], secret, buf);
  6374. } else
  6375. ast_string_field_set(iaxs[callno], secret, user->secret);
  6376. res = 0;
  6377. user = user_unref(user);
  6378. } else {
  6379. /* user was not found, but we should still fake an AUTHREQ.
  6380. * Set authmethods to the last known authmethod used by the system
  6381. * Set a fake secret, it's not looked at, just required to attempt authentication.
  6382. * Set authrej so the AUTHREP is rejected without even looking at its contents */
  6383. iaxs[callno]->authmethods = last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
  6384. ast_string_field_set(iaxs[callno], secret, "badsecret");
  6385. iaxs[callno]->authrej = 1;
  6386. if (!ast_strlen_zero(iaxs[callno]->username)) {
  6387. /* only send the AUTHREQ if a username was specified. */
  6388. res = 0;
  6389. }
  6390. }
  6391. ast_set2_flag(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);
  6392. return res;
  6393. }
  6394. static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst, int sockfd)
  6395. {
  6396. struct ast_iax2_full_hdr fh;
  6397. fh.scallno = htons(src | IAX_FLAG_FULL);
  6398. fh.dcallno = htons(dst);
  6399. fh.ts = 0;
  6400. fh.oseqno = 0;
  6401. fh.iseqno = 0;
  6402. fh.type = AST_FRAME_IAX;
  6403. fh.csub = compress_subclass(IAX_COMMAND_INVAL);
  6404. if (iaxdebug)
  6405. iax_showframe(NULL, &fh, 0, sin, 0);
  6406. #if 0
  6407. if (option_debug)
  6408. #endif
  6409. ast_debug(1, "Raw Hangup %s:%d, src=%d, dst=%d\n",
  6410. ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
  6411. return sendto(sockfd, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
  6412. }
  6413. static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
  6414. {
  6415. /* Select exactly one common encryption if there are any */
  6416. p->encmethods &= enc;
  6417. if (p->encmethods) {
  6418. if (p->encmethods & IAX_ENCRYPT_AES128)
  6419. p->encmethods = IAX_ENCRYPT_AES128;
  6420. else
  6421. p->encmethods = 0;
  6422. }
  6423. }
  6424. /*!
  6425. * \pre iaxsl[call_num] is locked
  6426. *
  6427. * \note Since this function calls send_command_final(), the pvt struct for the given
  6428. * call number may disappear while executing this function.
  6429. */
  6430. static int authenticate_request(int call_num)
  6431. {
  6432. struct iax_ie_data ied;
  6433. int res = -1, authreq_restrict = 0;
  6434. char challenge[10];
  6435. struct chan_iax2_pvt *p = iaxs[call_num];
  6436. memset(&ied, 0, sizeof(ied));
  6437. /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
  6438. if (ast_test_flag(p, IAX_MAXAUTHREQ)) {
  6439. struct iax2_user *user, tmp_user = {
  6440. .name = p->username,
  6441. };
  6442. user = ao2_find(users, &tmp_user, OBJ_POINTER);
  6443. if (user) {
  6444. if (user->curauthreq == user->maxauthreq)
  6445. authreq_restrict = 1;
  6446. else
  6447. user->curauthreq++;
  6448. user = user_unref(user);
  6449. }
  6450. }
  6451. /* If the AUTHREQ limit test failed, send back an error */
  6452. if (authreq_restrict) {
  6453. iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
  6454. iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_CALL_REJECTED);
  6455. send_command_final(p, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
  6456. return 0;
  6457. }
  6458. iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
  6459. if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
  6460. snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
  6461. ast_string_field_set(p, challenge, challenge);
  6462. /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
  6463. iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
  6464. }
  6465. if (p->encmethods)
  6466. iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, p->encmethods);
  6467. iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
  6468. res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
  6469. if (p->encmethods)
  6470. ast_set_flag(p, IAX_ENCRYPTED);
  6471. return res;
  6472. }
  6473. static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
  6474. {
  6475. char requeststr[256];
  6476. char md5secret[256] = "";
  6477. char secret[256] = "";
  6478. char rsasecret[256] = "";
  6479. int res = -1;
  6480. int x;
  6481. struct iax2_user *user, tmp_user = {
  6482. .name = p->username,
  6483. };
  6484. if (p->authrej) {
  6485. return res;
  6486. }
  6487. user = ao2_find(users, &tmp_user, OBJ_POINTER);
  6488. if (user) {
  6489. if (ast_test_flag(p, IAX_MAXAUTHREQ)) {
  6490. ast_atomic_fetchadd_int(&user->curauthreq, -1);
  6491. ast_clear_flag(p, IAX_MAXAUTHREQ);
  6492. }
  6493. ast_string_field_set(p, host, user->name);
  6494. user = user_unref(user);
  6495. }
  6496. if (!ast_test_flag(&p->state, IAX_STATE_AUTHENTICATED))
  6497. return res;
  6498. if (ies->password)
  6499. ast_copy_string(secret, ies->password, sizeof(secret));
  6500. if (ies->md5_result)
  6501. ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
  6502. if (ies->rsa_result)
  6503. ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
  6504. if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
  6505. struct ast_key *key;
  6506. char *keyn;
  6507. char tmpkey[256];
  6508. char *stringp=NULL;
  6509. ast_copy_string(tmpkey, p->inkeys, sizeof(tmpkey));
  6510. stringp=tmpkey;
  6511. keyn = strsep(&stringp, ":");
  6512. while(keyn) {
  6513. key = ast_key_get(keyn, AST_KEY_PUBLIC);
  6514. if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
  6515. res = 0;
  6516. break;
  6517. } else if (!key)
  6518. ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
  6519. keyn = strsep(&stringp, ":");
  6520. }
  6521. } else if (p->authmethods & IAX_AUTH_MD5) {
  6522. struct MD5Context md5;
  6523. unsigned char digest[16];
  6524. char *tmppw, *stringp;
  6525. tmppw = ast_strdupa(p->secret);
  6526. stringp = tmppw;
  6527. while((tmppw = strsep(&stringp, ";"))) {
  6528. MD5Init(&md5);
  6529. MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
  6530. MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
  6531. MD5Final(digest, &md5);
  6532. /* If they support md5, authenticate with it. */
  6533. for (x=0;x<16;x++)
  6534. sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
  6535. if (!strcasecmp(requeststr, md5secret)) {
  6536. res = 0;
  6537. break;
  6538. }
  6539. }
  6540. } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
  6541. if (!strcmp(secret, p->secret))
  6542. res = 0;
  6543. }
  6544. return res;
  6545. }
  6546. /*! \brief Verify inbound registration */
  6547. static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
  6548. {
  6549. char requeststr[256] = "";
  6550. char peer[256] = "";
  6551. char md5secret[256] = "";
  6552. char rsasecret[256] = "";
  6553. char secret[256] = "";
  6554. struct iax2_peer *p = NULL;
  6555. struct ast_key *key;
  6556. char *keyn;
  6557. int x;
  6558. int expire = 0;
  6559. int res = -1;
  6560. ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
  6561. /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
  6562. if (ies->username)
  6563. ast_copy_string(peer, ies->username, sizeof(peer));
  6564. if (ies->password)
  6565. ast_copy_string(secret, ies->password, sizeof(secret));
  6566. if (ies->md5_result)
  6567. ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
  6568. if (ies->rsa_result)
  6569. ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
  6570. if (ies->refresh)
  6571. expire = ies->refresh;
  6572. if (ast_strlen_zero(peer)) {
  6573. ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(sin->sin_addr));
  6574. return -1;
  6575. }
  6576. /* SLD: first call to lookup peer during registration */
  6577. ast_mutex_unlock(&iaxsl[callno]);
  6578. p = find_peer(peer, 1);
  6579. ast_mutex_lock(&iaxsl[callno]);
  6580. if (!p || !iaxs[callno]) {
  6581. if (iaxs[callno]) {
  6582. int plaintext = ((last_authmethod & IAX_AUTH_PLAINTEXT) | (iaxs[callno]->authmethods & IAX_AUTH_PLAINTEXT));
  6583. /* Anything, as long as it's non-blank */
  6584. ast_string_field_set(iaxs[callno], secret, "badsecret");
  6585. /* An AUTHREQ must be sent in response to a REGREQ of an invalid peer unless
  6586. * 1. A challenge already exists indicating a AUTHREQ was already sent out.
  6587. * 2. A plaintext secret is present in ie as result of a previous AUTHREQ requesting it.
  6588. * 3. A plaintext secret is present in the ie and the last_authmethod used by a peer happened
  6589. * to be plaintext, indicating it is an authmethod used by other peers on the system.
  6590. *
  6591. * If none of these cases exist, res will be returned as 0 without authentication indicating
  6592. * an AUTHREQ needs to be sent out. */
  6593. if (ast_strlen_zero(iaxs[callno]->challenge) &&
  6594. !(!ast_strlen_zero(secret) && plaintext)) {
  6595. /* by setting res to 0, an REGAUTH will be sent */
  6596. res = 0;
  6597. }
  6598. }
  6599. if (authdebug && !p)
  6600. ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
  6601. goto return_unref;
  6602. }
  6603. if (!ast_test_flag(p, IAX_DYNAMIC)) {
  6604. if (authdebug)
  6605. ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
  6606. goto return_unref;
  6607. }
  6608. if (!ast_apply_ha(p->ha, sin)) {
  6609. if (authdebug)
  6610. ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
  6611. goto return_unref;
  6612. }
  6613. ast_string_field_set(iaxs[callno], secret, p->secret);
  6614. ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
  6615. /* Check secret against what we have on file */
  6616. if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
  6617. if (!ast_strlen_zero(p->inkeys)) {
  6618. char tmpkeys[256];
  6619. char *stringp=NULL;
  6620. ast_copy_string(tmpkeys, p->inkeys, sizeof(tmpkeys));
  6621. stringp=tmpkeys;
  6622. keyn = strsep(&stringp, ":");
  6623. while(keyn) {
  6624. key = ast_key_get(keyn, AST_KEY_PUBLIC);
  6625. if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
  6626. ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
  6627. break;
  6628. } else if (!key)
  6629. ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
  6630. keyn = strsep(&stringp, ":");
  6631. }
  6632. if (!keyn) {
  6633. if (authdebug)
  6634. ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
  6635. goto return_unref;
  6636. }
  6637. } else {
  6638. if (authdebug)
  6639. ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
  6640. goto return_unref;
  6641. }
  6642. } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
  6643. struct MD5Context md5;
  6644. unsigned char digest[16];
  6645. char *tmppw, *stringp;
  6646. tmppw = ast_strdupa(p->secret);
  6647. stringp = tmppw;
  6648. while((tmppw = strsep(&stringp, ";"))) {
  6649. MD5Init(&md5);
  6650. MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
  6651. MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
  6652. MD5Final(digest, &md5);
  6653. for (x=0;x<16;x++)
  6654. sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
  6655. if (!strcasecmp(requeststr, md5secret))
  6656. break;
  6657. }
  6658. if (tmppw) {
  6659. ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
  6660. } else {
  6661. if (authdebug)
  6662. ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
  6663. goto return_unref;
  6664. }
  6665. } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
  6666. /* They've provided a plain text password and we support that */
  6667. if (strcmp(secret, p->secret)) {
  6668. if (authdebug)
  6669. ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
  6670. goto return_unref;
  6671. } else
  6672. ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
  6673. } else if (!ast_strlen_zero(iaxs[callno]->challenge) && ast_strlen_zero(md5secret) && ast_strlen_zero(rsasecret)) {
  6674. /* if challenge has been sent, but no challenge response if given, reject. */
  6675. goto return_unref;
  6676. }
  6677. ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name); /* Activate notification */
  6678. /* either Authentication has taken place, or a REGAUTH must be sent before verifying registration */
  6679. res = 0;
  6680. return_unref:
  6681. if (iaxs[callno]) {
  6682. ast_string_field_set(iaxs[callno], peer, peer);
  6683. /* Choose lowest expiry number */
  6684. if (expire && (expire < iaxs[callno]->expiry)) {
  6685. iaxs[callno]->expiry = expire;
  6686. }
  6687. }
  6688. if (p) {
  6689. peer_unref(p);
  6690. }
  6691. return res;
  6692. }
  6693. 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)
  6694. {
  6695. int res = -1;
  6696. int x;
  6697. if (!ast_strlen_zero(keyn)) {
  6698. if (!(authmethods & IAX_AUTH_RSA)) {
  6699. if (ast_strlen_zero(secret))
  6700. 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));
  6701. } else if (ast_strlen_zero(challenge)) {
  6702. ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin->sin_addr));
  6703. } else {
  6704. char sig[256];
  6705. struct ast_key *key;
  6706. key = ast_key_get(keyn, AST_KEY_PRIVATE);
  6707. if (!key) {
  6708. ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
  6709. } else {
  6710. if (ast_sign(key, (char*)challenge, sig)) {
  6711. ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
  6712. res = -1;
  6713. } else {
  6714. iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
  6715. res = 0;
  6716. }
  6717. }
  6718. }
  6719. }
  6720. /* Fall back */
  6721. if (res && !ast_strlen_zero(secret)) {
  6722. if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
  6723. struct MD5Context md5;
  6724. unsigned char digest[16];
  6725. char digres[128];
  6726. MD5Init(&md5);
  6727. MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
  6728. MD5Update(&md5, (unsigned char *)secret, strlen(secret));
  6729. MD5Final(digest, &md5);
  6730. /* If they support md5, authenticate with it. */
  6731. for (x=0;x<16;x++)
  6732. sprintf(digres + (x << 1), "%2.2x", digest[x]); /* safe */
  6733. if (pvt) {
  6734. build_encryption_keys(digest, pvt);
  6735. }
  6736. iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
  6737. res = 0;
  6738. } else if (authmethods & IAX_AUTH_PLAINTEXT) {
  6739. iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
  6740. res = 0;
  6741. } else
  6742. ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin->sin_addr), authmethods);
  6743. }
  6744. return res;
  6745. }
  6746. /*!
  6747. * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
  6748. * so do not call this function with a pvt lock held.
  6749. */
  6750. static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, const char *override, const char *okey)
  6751. {
  6752. struct iax2_peer *peer = NULL;
  6753. /* Start pessimistic */
  6754. int res = -1;
  6755. int authmethods = 0;
  6756. struct iax_ie_data ied;
  6757. uint16_t callno = p->callno;
  6758. memset(&ied, 0, sizeof(ied));
  6759. if (ies->username)
  6760. ast_string_field_set(p, username, ies->username);
  6761. if (ies->challenge)
  6762. ast_string_field_set(p, challenge, ies->challenge);
  6763. if (ies->authmethods)
  6764. authmethods = ies->authmethods;
  6765. if (authmethods & IAX_AUTH_MD5)
  6766. merge_encryption(p, ies->encmethods);
  6767. else
  6768. p->encmethods = 0;
  6769. /* Check for override RSA authentication first */
  6770. if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
  6771. /* Normal password authentication */
  6772. res = authenticate(p->challenge, override, okey, authmethods, &ied, sin, p);
  6773. } else {
  6774. struct ao2_iterator i = ao2_iterator_init(peers, 0);
  6775. while ((peer = ao2_iterator_next(&i))) {
  6776. if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
  6777. /* No peer specified at our end, or this is the peer */
  6778. && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
  6779. /* No username specified in peer rule, or this is the right username */
  6780. && (!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)))
  6781. /* No specified host, or this is our host */
  6782. ) {
  6783. res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin, p);
  6784. if (!res) {
  6785. peer_unref(peer);
  6786. break;
  6787. }
  6788. }
  6789. peer_unref(peer);
  6790. }
  6791. ao2_iterator_destroy(&i);
  6792. if (!peer) {
  6793. /* We checked our list and didn't find one. It's unlikely, but possible,
  6794. that we're trying to authenticate *to* a realtime peer */
  6795. const char *peer_name = ast_strdupa(p->peer);
  6796. ast_mutex_unlock(&iaxsl[callno]);
  6797. if ((peer = realtime_peer(peer_name, NULL))) {
  6798. ast_mutex_lock(&iaxsl[callno]);
  6799. if (!(p = iaxs[callno])) {
  6800. peer_unref(peer);
  6801. return -1;
  6802. }
  6803. res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, sin, p);
  6804. peer_unref(peer);
  6805. }
  6806. if (!peer) {
  6807. ast_mutex_lock(&iaxsl[callno]);
  6808. if (!(p = iaxs[callno]))
  6809. return -1;
  6810. }
  6811. }
  6812. }
  6813. if (ies->encmethods)
  6814. ast_set_flag(p, IAX_ENCRYPTED | IAX_KEYPOPULATED);
  6815. if (!res) {
  6816. struct ast_datastore *variablestore;
  6817. struct ast_variable *var, *prev = NULL;
  6818. AST_LIST_HEAD(, ast_var_t) *varlist;
  6819. varlist = ast_calloc(1, sizeof(*varlist));
  6820. variablestore = ast_channel_datastore_alloc(&iax2_variable_datastore_info, NULL);
  6821. if (variablestore && varlist && p->owner) {
  6822. variablestore->data = varlist;
  6823. variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
  6824. AST_LIST_HEAD_INIT(varlist);
  6825. for (var = ies->vars; var; var = var->next) {
  6826. struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
  6827. if (prev)
  6828. ast_free(prev);
  6829. prev = var;
  6830. if (!newvar) {
  6831. /* Don't abort list traversal, as this would leave ies->vars in an inconsistent state. */
  6832. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  6833. } else {
  6834. AST_LIST_INSERT_TAIL(varlist, newvar, entries);
  6835. }
  6836. }
  6837. if (prev)
  6838. ast_free(prev);
  6839. ies->vars = NULL;
  6840. ast_channel_datastore_add(p->owner, variablestore);
  6841. } else {
  6842. if (p->owner)
  6843. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  6844. if (variablestore)
  6845. ast_channel_datastore_free(variablestore);
  6846. if (varlist)
  6847. ast_free(varlist);
  6848. }
  6849. }
  6850. if (!res)
  6851. res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
  6852. return res;
  6853. }
  6854. static int iax2_do_register(struct iax2_registry *reg);
  6855. static void __iax2_do_register_s(const void *data)
  6856. {
  6857. struct iax2_registry *reg = (struct iax2_registry *)data;
  6858. reg->expire = -1;
  6859. iax2_do_register(reg);
  6860. }
  6861. static int iax2_do_register_s(const void *data)
  6862. {
  6863. #ifdef SCHED_MULTITHREADED
  6864. if (schedule_action(__iax2_do_register_s, data))
  6865. #endif
  6866. __iax2_do_register_s(data);
  6867. return 0;
  6868. }
  6869. static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
  6870. {
  6871. int newcall = 0;
  6872. char newip[256];
  6873. struct iax_ie_data ied;
  6874. struct sockaddr_in new;
  6875. memset(&ied, 0, sizeof(ied));
  6876. if (ies->apparent_addr)
  6877. memmove(&new, ies->apparent_addr, sizeof(new));
  6878. if (ies->callno)
  6879. newcall = ies->callno;
  6880. if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
  6881. ast_log(LOG_WARNING, "Invalid transfer request\n");
  6882. return -1;
  6883. }
  6884. pvt->transfercallno = newcall;
  6885. memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
  6886. inet_aton(newip, &pvt->transfer.sin_addr);
  6887. pvt->transfer.sin_family = AF_INET;
  6888. pvt->transferid = ies->transferid;
  6889. /* only store by transfercallno if this is a new transfer,
  6890. * just in case we get a duplicate TXREQ */
  6891. if (pvt->transferring == TRANSFER_NONE) {
  6892. store_by_transfercallno(pvt);
  6893. }
  6894. pvt->transferring = TRANSFER_BEGIN;
  6895. if (ies->transferid)
  6896. iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
  6897. send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
  6898. return 0;
  6899. }
  6900. static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
  6901. {
  6902. char exten[256] = "";
  6903. int status = CACHE_FLAG_UNKNOWN, expiry = iaxdefaultdpcache, x, matchmore = 0;
  6904. struct iax2_dpcache *dp = NULL;
  6905. if (ies->called_number)
  6906. ast_copy_string(exten, ies->called_number, sizeof(exten));
  6907. if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
  6908. status = CACHE_FLAG_EXISTS;
  6909. else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
  6910. status = CACHE_FLAG_CANEXIST;
  6911. else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
  6912. status = CACHE_FLAG_NONEXISTENT;
  6913. if (ies->refresh)
  6914. expiry = ies->refresh;
  6915. if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
  6916. matchmore = CACHE_FLAG_MATCHMORE;
  6917. AST_LIST_LOCK(&dpcache);
  6918. AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, peer_list) {
  6919. if (strcmp(dp->exten, exten))
  6920. continue;
  6921. AST_LIST_REMOVE_CURRENT(peer_list);
  6922. dp->callno = 0;
  6923. dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
  6924. if (dp->flags & CACHE_FLAG_PENDING) {
  6925. dp->flags &= ~CACHE_FLAG_PENDING;
  6926. dp->flags |= status;
  6927. dp->flags |= matchmore;
  6928. }
  6929. /* Wake up waiters */
  6930. for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
  6931. if (dp->waiters[x] > -1) {
  6932. if (write(dp->waiters[x], "asdf", 4) < 0) {
  6933. }
  6934. }
  6935. }
  6936. }
  6937. AST_LIST_TRAVERSE_SAFE_END;
  6938. AST_LIST_UNLOCK(&dpcache);
  6939. return 0;
  6940. }
  6941. static int complete_transfer(int callno, struct iax_ies *ies)
  6942. {
  6943. int peercallno = 0;
  6944. struct chan_iax2_pvt *pvt = iaxs[callno];
  6945. struct iax_frame *cur;
  6946. jb_frame frame;
  6947. if (ies->callno)
  6948. peercallno = ies->callno;
  6949. if (peercallno < 1) {
  6950. ast_log(LOG_WARNING, "Invalid transfer request\n");
  6951. return -1;
  6952. }
  6953. remove_by_transfercallno(pvt);
  6954. /* since a transfer has taken place, the address will change.
  6955. * This must be accounted for in the peercnts table. Remove
  6956. * the old address and add the new one */
  6957. peercnt_remove_by_addr(&pvt->addr);
  6958. peercnt_add(&pvt->transfer);
  6959. /* now copy over the new address */
  6960. memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
  6961. memset(&pvt->transfer, 0, sizeof(pvt->transfer));
  6962. /* Reset sequence numbers */
  6963. pvt->oseqno = 0;
  6964. pvt->rseqno = 0;
  6965. pvt->iseqno = 0;
  6966. pvt->aseqno = 0;
  6967. if (pvt->peercallno) {
  6968. remove_by_peercallno(pvt);
  6969. }
  6970. pvt->peercallno = peercallno;
  6971. /*this is where the transfering call swiches hash tables */
  6972. store_by_peercallno(pvt);
  6973. pvt->transferring = TRANSFER_NONE;
  6974. pvt->svoiceformat = -1;
  6975. pvt->voiceformat = 0;
  6976. pvt->svideoformat = -1;
  6977. pvt->videoformat = 0;
  6978. pvt->transfercallno = 0;
  6979. memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
  6980. memset(&pvt->offset, 0, sizeof(pvt->offset));
  6981. /* reset jitterbuffer */
  6982. while(jb_getall(pvt->jb,&frame) == JB_OK)
  6983. iax2_frame_free(frame.data);
  6984. jb_reset(pvt->jb);
  6985. pvt->lag = 0;
  6986. pvt->last = 0;
  6987. pvt->lastsent = 0;
  6988. pvt->nextpred = 0;
  6989. pvt->pingtime = DEFAULT_RETRY_TIME;
  6990. AST_LIST_LOCK(&frame_queue);
  6991. AST_LIST_TRAVERSE(&frame_queue, cur, list) {
  6992. /* We must cancel any packets that would have been transmitted
  6993. because now we're talking to someone new. It's okay, they
  6994. were transmitted to someone that didn't care anyway. */
  6995. if (callno == cur->callno)
  6996. cur->retries = -1;
  6997. }
  6998. AST_LIST_UNLOCK(&frame_queue);
  6999. return 0;
  7000. }
  7001. /*! \brief Acknowledgment received for OUR registration */
  7002. static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
  7003. {
  7004. struct iax2_registry *reg;
  7005. /* Start pessimistic */
  7006. char peer[256] = "";
  7007. char msgstatus[60];
  7008. int refresh = 60;
  7009. char ourip[256] = "<Unspecified>";
  7010. struct sockaddr_in oldus;
  7011. struct sockaddr_in us;
  7012. int oldmsgs;
  7013. memset(&us, 0, sizeof(us));
  7014. if (ies->apparent_addr)
  7015. memmove(&us, ies->apparent_addr, sizeof(us));
  7016. if (ies->username)
  7017. ast_copy_string(peer, ies->username, sizeof(peer));
  7018. if (ies->refresh)
  7019. refresh = ies->refresh;
  7020. if (ies->calling_number) {
  7021. /* We don't do anything with it really, but maybe we should */
  7022. }
  7023. reg = iaxs[callno]->reg;
  7024. if (!reg) {
  7025. ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
  7026. return -1;
  7027. }
  7028. memcpy(&oldus, &reg->us, sizeof(oldus));
  7029. oldmsgs = reg->messages;
  7030. if (inaddrcmp(&reg->addr, sin)) {
  7031. ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin->sin_addr));
  7032. return -1;
  7033. }
  7034. memcpy(&reg->us, &us, sizeof(reg->us));
  7035. if (ies->msgcount >= 0)
  7036. reg->messages = ies->msgcount & 0xffff; /* only low 16 bits are used in the transmission of the IE */
  7037. /* always refresh the registration at the interval requested by the server
  7038. we are registering to
  7039. */
  7040. reg->refresh = refresh;
  7041. reg->expire = iax2_sched_replace(reg->expire, sched,
  7042. (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
  7043. if (inaddrcmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) {
  7044. if (reg->messages > 255)
  7045. snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
  7046. else if (reg->messages > 1)
  7047. snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting\n", reg->messages);
  7048. else if (reg->messages > 0)
  7049. ast_copy_string(msgstatus, " with 1 new message waiting\n", sizeof(msgstatus));
  7050. else
  7051. ast_copy_string(msgstatus, " with no messages waiting\n", sizeof(msgstatus));
  7052. snprintf(ourip, sizeof(ourip), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
  7053. ast_verb(3, "Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin->sin_addr), ourip, msgstatus);
  7054. manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin->sin_addr));
  7055. }
  7056. reg->regstate = REG_STATE_REGISTERED;
  7057. return 0;
  7058. }
  7059. static int iax2_append_register(const char *hostname, const char *username,
  7060. const char *secret, const char *porta)
  7061. {
  7062. struct iax2_registry *reg;
  7063. if (!(reg = ast_calloc(1, sizeof(*reg))))
  7064. return -1;
  7065. if (ast_dnsmgr_lookup(hostname, &reg->addr.sin_addr, &reg->dnsmgr) < 0) {
  7066. ast_free(reg);
  7067. return -1;
  7068. }
  7069. ast_copy_string(reg->username, username, sizeof(reg->username));
  7070. if (secret)
  7071. ast_copy_string(reg->secret, secret, sizeof(reg->secret));
  7072. reg->expire = -1;
  7073. reg->refresh = IAX_DEFAULT_REG_EXPIRE;
  7074. reg->addr.sin_family = AF_INET;
  7075. reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(IAX_DEFAULT_PORTNO);
  7076. AST_LIST_LOCK(&registrations);
  7077. AST_LIST_INSERT_HEAD(&registrations, reg, entry);
  7078. AST_LIST_UNLOCK(&registrations);
  7079. return 0;
  7080. }
  7081. static int iax2_register(const char *value, int lineno)
  7082. {
  7083. char copy[256];
  7084. char *username, *hostname, *secret;
  7085. char *porta;
  7086. char *stringp=NULL;
  7087. if (!value)
  7088. return -1;
  7089. ast_copy_string(copy, value, sizeof(copy));
  7090. stringp = copy;
  7091. username = strsep(&stringp, "@");
  7092. hostname = strsep(&stringp, "@");
  7093. if (!hostname) {
  7094. ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
  7095. return -1;
  7096. }
  7097. stringp = username;
  7098. username = strsep(&stringp, ":");
  7099. secret = strsep(&stringp, ":");
  7100. stringp = hostname;
  7101. hostname = strsep(&stringp, ":");
  7102. porta = strsep(&stringp, ":");
  7103. if (porta && !atoi(porta)) {
  7104. ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
  7105. return -1;
  7106. }
  7107. return iax2_append_register(hostname, username, secret, porta);
  7108. }
  7109. static void register_peer_exten(struct iax2_peer *peer, int onoff)
  7110. {
  7111. char multi[256];
  7112. char *stringp, *ext;
  7113. if (!ast_strlen_zero(regcontext)) {
  7114. ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
  7115. stringp = multi;
  7116. while((ext = strsep(&stringp, "&"))) {
  7117. if (onoff) {
  7118. if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
  7119. ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
  7120. "Noop", ast_strdup(peer->name), ast_free_ptr, "IAX2");
  7121. } else
  7122. ast_context_remove_extension(regcontext, ext, 1, NULL);
  7123. }
  7124. }
  7125. }
  7126. static void prune_peers(void);
  7127. static void unlink_peer(struct iax2_peer *peer)
  7128. {
  7129. if (peer->expire > -1) {
  7130. if (!ast_sched_del(sched, peer->expire)) {
  7131. peer->expire = -1;
  7132. peer_unref(peer);
  7133. }
  7134. }
  7135. if (peer->pokeexpire > -1) {
  7136. if (!ast_sched_del(sched, peer->pokeexpire)) {
  7137. peer->pokeexpire = -1;
  7138. peer_unref(peer);
  7139. }
  7140. }
  7141. ao2_unlink(peers, peer);
  7142. }
  7143. static void __expire_registry(const void *data)
  7144. {
  7145. struct iax2_peer *peer = (struct iax2_peer *) data;
  7146. if (!peer)
  7147. return;
  7148. peer->expire = -1;
  7149. ast_debug(1, "Expiring registration for peer '%s'\n", peer->name);
  7150. if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(peer, IAX_TEMPONLY|IAX_RTCACHEFRIENDS)))
  7151. realtime_update_peer(peer->name, &peer->addr, 0);
  7152. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
  7153. /* modify entry in peercnts table as _not_ registered */
  7154. peercnt_modify(0, 0, &peer->addr);
  7155. /* Reset the address */
  7156. memset(&peer->addr, 0, sizeof(peer->addr));
  7157. /* Reset expiry value */
  7158. peer->expiry = min_reg_expire;
  7159. if (!ast_test_flag(peer, IAX_TEMPONLY))
  7160. ast_db_del("IAX/Registry", peer->name);
  7161. register_peer_exten(peer, 0);
  7162. ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
  7163. if (iax2_regfunk)
  7164. iax2_regfunk(peer->name, 0);
  7165. if (ast_test_flag(peer, IAX_RTAUTOCLEAR))
  7166. unlink_peer(peer);
  7167. peer_unref(peer);
  7168. }
  7169. static int expire_registry(const void *data)
  7170. {
  7171. #ifdef SCHED_MULTITHREADED
  7172. if (schedule_action(__expire_registry, data))
  7173. #endif
  7174. __expire_registry(data);
  7175. return 0;
  7176. }
  7177. static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
  7178. static void reg_source_db(struct iax2_peer *p)
  7179. {
  7180. char data[80];
  7181. struct in_addr in;
  7182. char *c, *d;
  7183. if (!ast_test_flag(p, IAX_TEMPONLY) && (!ast_db_get("IAX/Registry", p->name, data, sizeof(data)))) {
  7184. c = strchr(data, ':');
  7185. if (c) {
  7186. *c = '\0';
  7187. c++;
  7188. if (inet_aton(data, &in)) {
  7189. d = strchr(c, ':');
  7190. if (d) {
  7191. *d = '\0';
  7192. d++;
  7193. ast_verb(3, "Seeding '%s' at %s:%d for %d\n", p->name,
  7194. ast_inet_ntoa(in), atoi(c), atoi(d));
  7195. iax2_poke_peer(p, 0);
  7196. p->expiry = atoi(d);
  7197. memset(&p->addr, 0, sizeof(p->addr));
  7198. p->addr.sin_family = AF_INET;
  7199. p->addr.sin_addr = in;
  7200. p->addr.sin_port = htons(atoi(c));
  7201. if (p->expire > -1) {
  7202. if (!ast_sched_del(sched, p->expire)) {
  7203. p->expire = -1;
  7204. peer_unref(p);
  7205. }
  7206. }
  7207. ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
  7208. p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
  7209. if (p->expire == -1)
  7210. peer_unref(p);
  7211. if (iax2_regfunk)
  7212. iax2_regfunk(p->name, 1);
  7213. register_peer_exten(p, 1);
  7214. }
  7215. }
  7216. }
  7217. }
  7218. }
  7219. /*!
  7220. * \pre iaxsl[callno] is locked
  7221. *
  7222. * \note Since this function calls send_command_final(), the pvt struct for
  7223. * the given call number may disappear while executing this function.
  7224. */
  7225. static int update_registry(struct sockaddr_in *sin, int callno, char *devtype, int fd, unsigned short refresh)
  7226. {
  7227. /* Called from IAX thread only, with proper iaxsl lock */
  7228. struct iax_ie_data ied;
  7229. struct iax2_peer *p;
  7230. int msgcount;
  7231. char data[80];
  7232. int version;
  7233. const char *peer_name;
  7234. int res = -1;
  7235. memset(&ied, 0, sizeof(ied));
  7236. peer_name = ast_strdupa(iaxs[callno]->peer);
  7237. /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
  7238. ast_mutex_unlock(&iaxsl[callno]);
  7239. if (!(p = find_peer(peer_name, 1))) {
  7240. ast_mutex_lock(&iaxsl[callno]);
  7241. ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
  7242. return -1;
  7243. }
  7244. ast_mutex_lock(&iaxsl[callno]);
  7245. if (!iaxs[callno])
  7246. goto return_unref;
  7247. if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(p, IAX_TEMPONLY|IAX_RTCACHEFRIENDS))) {
  7248. if (sin->sin_addr.s_addr) {
  7249. time_t nowtime;
  7250. time(&nowtime);
  7251. realtime_update_peer(peer_name, sin, nowtime);
  7252. } else {
  7253. realtime_update_peer(peer_name, sin, 0);
  7254. }
  7255. }
  7256. if (inaddrcmp(&p->addr, sin)) {
  7257. if (iax2_regfunk)
  7258. iax2_regfunk(p->name, 1);
  7259. /* modify entry in peercnts table as _not_ registered */
  7260. peercnt_modify(0, 0, &p->addr);
  7261. /* Stash the IP address from which they registered */
  7262. memcpy(&p->addr, sin, sizeof(p->addr));
  7263. snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p->expiry);
  7264. if (!ast_test_flag(p, IAX_TEMPONLY) && sin->sin_addr.s_addr) {
  7265. ast_db_put("IAX/Registry", p->name, data);
  7266. ast_verb(3, "Registered IAX2 '%s' (%s) at %s:%d\n", p->name,
  7267. ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
  7268. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Registered\r\n", p->name);
  7269. register_peer_exten(p, 1);
  7270. ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
  7271. } else if (!ast_test_flag(p, IAX_TEMPONLY)) {
  7272. ast_verb(3, "Unregistered IAX2 '%s' (%s)\n", p->name,
  7273. ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
  7274. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p->name);
  7275. register_peer_exten(p, 0);
  7276. ast_db_del("IAX/Registry", p->name);
  7277. ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
  7278. }
  7279. /* Update the host */
  7280. /* Verify that the host is really there */
  7281. iax2_poke_peer(p, callno);
  7282. }
  7283. /* modify entry in peercnts table as registered */
  7284. if (p->maxcallno) {
  7285. peercnt_modify(1, p->maxcallno, &p->addr);
  7286. }
  7287. /* Make sure our call still exists, an INVAL at the right point may make it go away */
  7288. if (!iaxs[callno]) {
  7289. res = -1;
  7290. goto return_unref;
  7291. }
  7292. /* Store socket fd */
  7293. p->sockfd = fd;
  7294. /* Setup the expiry */
  7295. if (p->expire > -1) {
  7296. if (!ast_sched_del(sched, p->expire)) {
  7297. p->expire = -1;
  7298. peer_unref(p);
  7299. }
  7300. }
  7301. /* treat an unspecified refresh interval as the minimum */
  7302. if (!refresh)
  7303. refresh = min_reg_expire;
  7304. if (refresh > max_reg_expire) {
  7305. ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
  7306. p->name, max_reg_expire, refresh);
  7307. p->expiry = max_reg_expire;
  7308. } else if (refresh < min_reg_expire) {
  7309. ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
  7310. p->name, min_reg_expire, refresh);
  7311. p->expiry = min_reg_expire;
  7312. } else {
  7313. p->expiry = refresh;
  7314. }
  7315. if (p->expiry && sin->sin_addr.s_addr) {
  7316. p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
  7317. if (p->expire == -1)
  7318. peer_unref(p);
  7319. }
  7320. iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
  7321. iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(p->zonetag));
  7322. if (sin->sin_addr.s_addr) {
  7323. iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expiry);
  7324. iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &p->addr);
  7325. if (!ast_strlen_zero(p->mailbox)) {
  7326. struct ast_event *event;
  7327. int new, old;
  7328. char *mailbox, *context;
  7329. context = mailbox = ast_strdupa(p->mailbox);
  7330. strsep(&context, "@");
  7331. if (ast_strlen_zero(context))
  7332. context = "default";
  7333. event = ast_event_get_cached(AST_EVENT_MWI,
  7334. AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
  7335. AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
  7336. AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
  7337. AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
  7338. AST_EVENT_IE_END);
  7339. if (event) {
  7340. new = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
  7341. old = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
  7342. ast_event_destroy(event);
  7343. } else /* Fall back on checking the mailbox directly */
  7344. ast_app_inboxcount(p->mailbox, &new, &old);
  7345. if (new > 255)
  7346. new = 255;
  7347. if (old > 255)
  7348. old = 255;
  7349. msgcount = (old << 8) | new;
  7350. iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
  7351. }
  7352. if (ast_test_flag(p, IAX_HASCALLERID)) {
  7353. iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, p->cid_num);
  7354. iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->cid_name);
  7355. }
  7356. }
  7357. version = iax_check_version(devtype);
  7358. if (version)
  7359. iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
  7360. res = 0;
  7361. return_unref:
  7362. peer_unref(p);
  7363. return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
  7364. }
  7365. static int registry_authrequest(int callno)
  7366. {
  7367. struct iax_ie_data ied;
  7368. struct iax2_peer *p;
  7369. char challenge[10];
  7370. const char *peer_name;
  7371. int sentauthmethod;
  7372. peer_name = ast_strdupa(iaxs[callno]->peer);
  7373. /* SLD: third call to find_peer in registration */
  7374. ast_mutex_unlock(&iaxsl[callno]);
  7375. if ((p = find_peer(peer_name, 1))) {
  7376. last_authmethod = p->authmethods;
  7377. }
  7378. ast_mutex_lock(&iaxsl[callno]);
  7379. if (!iaxs[callno])
  7380. goto return_unref;
  7381. memset(&ied, 0, sizeof(ied));
  7382. /* The selection of which delayed reject is sent may leak information,
  7383. * if it sets a static response. For example, if a host is known to only
  7384. * use MD5 authentication, then an RSA response would indicate that the
  7385. * peer does not exist, and vice-versa.
  7386. * Therefore, we use whatever the last peer used (which may vary over the
  7387. * course of a server, which should leak minimal information). */
  7388. sentauthmethod = p ? p->authmethods : last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
  7389. if (!p) {
  7390. iaxs[callno]->authmethods = sentauthmethod;
  7391. }
  7392. iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, sentauthmethod);
  7393. if (sentauthmethod & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
  7394. /* Build the challenge */
  7395. snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
  7396. ast_string_field_set(iaxs[callno], challenge, challenge);
  7397. iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
  7398. }
  7399. iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
  7400. return_unref:
  7401. if (p) {
  7402. peer_unref(p);
  7403. }
  7404. return iaxs[callno] ? send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1) : -1;
  7405. }
  7406. static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
  7407. {
  7408. struct iax2_registry *reg;
  7409. /* Start pessimistic */
  7410. struct iax_ie_data ied;
  7411. char peer[256] = "";
  7412. char challenge[256] = "";
  7413. int res;
  7414. int authmethods = 0;
  7415. if (ies->authmethods)
  7416. authmethods = ies->authmethods;
  7417. if (ies->username)
  7418. ast_copy_string(peer, ies->username, sizeof(peer));
  7419. if (ies->challenge)
  7420. ast_copy_string(challenge, ies->challenge, sizeof(challenge));
  7421. memset(&ied, 0, sizeof(ied));
  7422. reg = iaxs[callno]->reg;
  7423. if (reg) {
  7424. if (inaddrcmp(&reg->addr, sin)) {
  7425. ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin->sin_addr));
  7426. return -1;
  7427. }
  7428. if (ast_strlen_zero(reg->secret)) {
  7429. ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
  7430. reg->regstate = REG_STATE_NOAUTH;
  7431. return -1;
  7432. }
  7433. iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
  7434. iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
  7435. if (reg->secret[0] == '[') {
  7436. char tmpkey[256];
  7437. ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
  7438. tmpkey[strlen(tmpkey) - 1] = '\0';
  7439. res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin, NULL);
  7440. } else
  7441. res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin, NULL);
  7442. if (!res) {
  7443. reg->regstate = REG_STATE_AUTHSENT;
  7444. add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
  7445. return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
  7446. } else
  7447. return -1;
  7448. ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
  7449. } else
  7450. ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
  7451. return -1;
  7452. }
  7453. static void stop_stuff(int callno)
  7454. {
  7455. iax2_destroy_helper(iaxs[callno]);
  7456. }
  7457. static void __auth_reject(const void *nothing)
  7458. {
  7459. /* Called from IAX thread only, without iaxs lock */
  7460. int callno = (int)(long)(nothing);
  7461. struct iax_ie_data ied;
  7462. ast_mutex_lock(&iaxsl[callno]);
  7463. if (iaxs[callno]) {
  7464. memset(&ied, 0, sizeof(ied));
  7465. if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
  7466. iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
  7467. iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_REJECTED);
  7468. } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
  7469. iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
  7470. iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
  7471. }
  7472. send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
  7473. }
  7474. ast_mutex_unlock(&iaxsl[callno]);
  7475. }
  7476. static int auth_reject(const void *data)
  7477. {
  7478. int callno = (int)(long)(data);
  7479. ast_mutex_lock(&iaxsl[callno]);
  7480. if (iaxs[callno])
  7481. iaxs[callno]->authid = -1;
  7482. ast_mutex_unlock(&iaxsl[callno]);
  7483. #ifdef SCHED_MULTITHREADED
  7484. if (schedule_action(__auth_reject, data))
  7485. #endif
  7486. __auth_reject(data);
  7487. return 0;
  7488. }
  7489. static int auth_fail(int callno, int failcode)
  7490. {
  7491. /* Schedule sending the authentication failure in one second, to prevent
  7492. guessing */
  7493. if (iaxs[callno]) {
  7494. iaxs[callno]->authfail = failcode;
  7495. if (delayreject) {
  7496. iaxs[callno]->authid = iax2_sched_replace(iaxs[callno]->authid,
  7497. sched, 1000, auth_reject, (void *)(long)callno);
  7498. } else
  7499. auth_reject((void *)(long)callno);
  7500. }
  7501. return 0;
  7502. }
  7503. static void __auto_hangup(const void *nothing)
  7504. {
  7505. /* Called from IAX thread only, without iaxs lock */
  7506. int callno = (int)(long)(nothing);
  7507. struct iax_ie_data ied;
  7508. ast_mutex_lock(&iaxsl[callno]);
  7509. if (iaxs[callno]) {
  7510. memset(&ied, 0, sizeof(ied));
  7511. iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
  7512. iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_NO_USER_RESPONSE);
  7513. send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
  7514. }
  7515. ast_mutex_unlock(&iaxsl[callno]);
  7516. }
  7517. static int auto_hangup(const void *data)
  7518. {
  7519. int callno = (int)(long)(data);
  7520. ast_mutex_lock(&iaxsl[callno]);
  7521. if (iaxs[callno]) {
  7522. iaxs[callno]->autoid = -1;
  7523. }
  7524. ast_mutex_unlock(&iaxsl[callno]);
  7525. #ifdef SCHED_MULTITHREADED
  7526. if (schedule_action(__auto_hangup, data))
  7527. #endif
  7528. __auto_hangup(data);
  7529. return 0;
  7530. }
  7531. static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
  7532. {
  7533. struct iax_ie_data ied;
  7534. /* Auto-hangup with 30 seconds of inactivity */
  7535. iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
  7536. sched, 30000, auto_hangup, (void *)(long)callno);
  7537. memset(&ied, 0, sizeof(ied));
  7538. iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
  7539. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
  7540. dp->flags |= CACHE_FLAG_TRANSMITTED;
  7541. }
  7542. static int iax2_vnak(int callno)
  7543. {
  7544. return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
  7545. }
  7546. static void vnak_retransmit(int callno, int last)
  7547. {
  7548. struct iax_frame *f;
  7549. AST_LIST_LOCK(&frame_queue);
  7550. AST_LIST_TRAVERSE(&frame_queue, f, list) {
  7551. /* Send a copy immediately */
  7552. if ((f->callno == callno) && iaxs[f->callno] &&
  7553. ((unsigned char ) (f->oseqno - last) < 128) &&
  7554. (f->retries >= 0)) {
  7555. send_packet(f);
  7556. }
  7557. }
  7558. AST_LIST_UNLOCK(&frame_queue);
  7559. }
  7560. static void __iax2_poke_peer_s(const void *data)
  7561. {
  7562. struct iax2_peer *peer = (struct iax2_peer *)data;
  7563. iax2_poke_peer(peer, 0);
  7564. peer_unref(peer);
  7565. }
  7566. static int iax2_poke_peer_s(const void *data)
  7567. {
  7568. struct iax2_peer *peer = (struct iax2_peer *)data;
  7569. peer->pokeexpire = -1;
  7570. #ifdef SCHED_MULTITHREADED
  7571. if (schedule_action(__iax2_poke_peer_s, data))
  7572. #endif
  7573. __iax2_poke_peer_s(data);
  7574. return 0;
  7575. }
  7576. static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
  7577. {
  7578. int res = 0;
  7579. struct iax_frame *fr;
  7580. struct ast_iax2_meta_hdr *meta;
  7581. struct ast_iax2_meta_trunk_hdr *mth;
  7582. int calls = 0;
  7583. /* Point to frame */
  7584. fr = (struct iax_frame *)tpeer->trunkdata;
  7585. /* Point to meta data */
  7586. meta = (struct ast_iax2_meta_hdr *)fr->afdata;
  7587. mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
  7588. if (tpeer->trunkdatalen) {
  7589. /* We're actually sending a frame, so fill the meta trunk header and meta header */
  7590. meta->zeros = 0;
  7591. meta->metacmd = IAX_META_TRUNK;
  7592. if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS))
  7593. meta->cmddata = IAX_META_TRUNK_MINI;
  7594. else
  7595. meta->cmddata = IAX_META_TRUNK_SUPERMINI;
  7596. mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
  7597. /* And the rest of the ast_iax2 header */
  7598. fr->direction = DIRECTION_OUTGRESS;
  7599. fr->retrans = -1;
  7600. fr->transfer = 0;
  7601. /* Any appropriate call will do */
  7602. fr->data = fr->afdata;
  7603. fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
  7604. res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
  7605. calls = tpeer->calls;
  7606. #if 0
  7607. 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));
  7608. #endif
  7609. /* Reset transmit trunk side data */
  7610. tpeer->trunkdatalen = 0;
  7611. tpeer->calls = 0;
  7612. }
  7613. if (res < 0)
  7614. return res;
  7615. return calls;
  7616. }
  7617. static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
  7618. {
  7619. /* Drop when trunk is about 5 seconds idle */
  7620. if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
  7621. return 1;
  7622. return 0;
  7623. }
  7624. static int timing_read(int *id, int fd, short events, void *cbdata)
  7625. {
  7626. char buf[1024];
  7627. int res, processed = 0, totalcalls = 0;
  7628. struct iax2_trunk_peer *tpeer = NULL, *drop = NULL;
  7629. #ifdef DAHDI_TIMERACK
  7630. int x = 1;
  7631. #endif
  7632. struct timeval now = ast_tvnow();
  7633. if (iaxtrunkdebug)
  7634. ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", trunkmaxsize);
  7635. if (events & AST_IO_PRI) {
  7636. #ifdef DAHDI_TIMERACK
  7637. /* Great, this is a timing interface, just call the ioctl */
  7638. if (ioctl(fd, DAHDI_TIMERACK, &x)) {
  7639. ast_log(LOG_WARNING, "Unable to acknowledge DAHDI timer. IAX trunking will fail!\n");
  7640. usleep(1);
  7641. return -1;
  7642. }
  7643. #endif
  7644. } else {
  7645. /* Read and ignore from the pseudo channel for timing */
  7646. res = read(fd, buf, sizeof(buf));
  7647. if (res < 1) {
  7648. ast_log(LOG_WARNING, "Unable to read from timing fd\n");
  7649. return 1;
  7650. }
  7651. }
  7652. /* For each peer that supports trunking... */
  7653. AST_LIST_LOCK(&tpeers);
  7654. AST_LIST_TRAVERSE_SAFE_BEGIN(&tpeers, tpeer, list) {
  7655. processed++;
  7656. res = 0;
  7657. ast_mutex_lock(&tpeer->lock);
  7658. /* We can drop a single tpeer per pass. That makes all this logic
  7659. substantially easier */
  7660. if (!drop && iax2_trunk_expired(tpeer, &now)) {
  7661. /* Take it out of the list, but don't free it yet, because it
  7662. could be in use */
  7663. AST_LIST_REMOVE_CURRENT(list);
  7664. drop = tpeer;
  7665. } else {
  7666. res = send_trunk(tpeer, &now);
  7667. trunk_timed++;
  7668. if (iaxtrunkdebug)
  7669. ast_verbose(" - Trunk peer (%s:%d) has %d call chunk%s in transit, %d bytes backloged and has hit a high water mark of %d bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), res, (res != 1) ? "s" : "", tpeer->trunkdatalen, tpeer->trunkdataalloc);
  7670. }
  7671. totalcalls += res;
  7672. res = 0;
  7673. ast_mutex_unlock(&tpeer->lock);
  7674. }
  7675. AST_LIST_TRAVERSE_SAFE_END;
  7676. AST_LIST_UNLOCK(&tpeers);
  7677. if (drop) {
  7678. ast_mutex_lock(&drop->lock);
  7679. /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
  7680. because by the time they could get tpeerlock, we've already grabbed it */
  7681. ast_debug(1, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop->addr.sin_addr), ntohs(drop->addr.sin_port));
  7682. if (drop->trunkdata) {
  7683. ast_free(drop->trunkdata);
  7684. drop->trunkdata = NULL;
  7685. }
  7686. ast_mutex_unlock(&drop->lock);
  7687. ast_mutex_destroy(&drop->lock);
  7688. ast_free(drop);
  7689. }
  7690. if (iaxtrunkdebug)
  7691. ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
  7692. iaxtrunkdebug = 0;
  7693. return 1;
  7694. }
  7695. struct dpreq_data {
  7696. int callno;
  7697. char context[AST_MAX_EXTENSION];
  7698. char callednum[AST_MAX_EXTENSION];
  7699. char *callerid;
  7700. };
  7701. static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
  7702. {
  7703. unsigned short dpstatus = 0;
  7704. struct iax_ie_data ied1;
  7705. int mm;
  7706. memset(&ied1, 0, sizeof(ied1));
  7707. mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
  7708. /* Must be started */
  7709. if (!strcmp(callednum, ast_parking_ext()) || ast_exists_extension(NULL, context, callednum, 1, callerid)) {
  7710. dpstatus = IAX_DPSTATUS_EXISTS;
  7711. } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
  7712. dpstatus = IAX_DPSTATUS_CANEXIST;
  7713. } else {
  7714. dpstatus = IAX_DPSTATUS_NONEXISTENT;
  7715. }
  7716. if (ast_ignore_pattern(context, callednum))
  7717. dpstatus |= IAX_DPSTATUS_IGNOREPAT;
  7718. if (mm)
  7719. dpstatus |= IAX_DPSTATUS_MATCHMORE;
  7720. if (!skiplock)
  7721. ast_mutex_lock(&iaxsl[callno]);
  7722. if (iaxs[callno]) {
  7723. iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
  7724. iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
  7725. iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
  7726. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
  7727. }
  7728. if (!skiplock)
  7729. ast_mutex_unlock(&iaxsl[callno]);
  7730. }
  7731. static void *dp_lookup_thread(void *data)
  7732. {
  7733. /* Look up for dpreq */
  7734. struct dpreq_data *dpr = data;
  7735. dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
  7736. if (dpr->callerid)
  7737. ast_free(dpr->callerid);
  7738. ast_free(dpr);
  7739. return NULL;
  7740. }
  7741. static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
  7742. {
  7743. pthread_t newthread;
  7744. struct dpreq_data *dpr;
  7745. if (!(dpr = ast_calloc(1, sizeof(*dpr))))
  7746. return;
  7747. dpr->callno = callno;
  7748. ast_copy_string(dpr->context, context, sizeof(dpr->context));
  7749. ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
  7750. if (callerid)
  7751. dpr->callerid = ast_strdup(callerid);
  7752. if (ast_pthread_create_detached(&newthread, NULL, dp_lookup_thread, dpr)) {
  7753. ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
  7754. }
  7755. }
  7756. struct iax_dual {
  7757. struct ast_channel *chan1;
  7758. struct ast_channel *chan2;
  7759. };
  7760. static void *iax_park_thread(void *stuff)
  7761. {
  7762. struct ast_channel *chan1, *chan2;
  7763. struct iax_dual *d;
  7764. struct ast_frame *f;
  7765. int ext;
  7766. int res;
  7767. d = stuff;
  7768. chan1 = d->chan1;
  7769. chan2 = d->chan2;
  7770. ast_free(d);
  7771. f = ast_read(chan1);
  7772. if (f)
  7773. ast_frfree(f);
  7774. res = ast_park_call(chan1, chan2, 0, &ext);
  7775. ast_hangup(chan2);
  7776. ast_log(LOG_NOTICE, "Parked on extension '%d'\n", ext);
  7777. return NULL;
  7778. }
  7779. static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2)
  7780. {
  7781. struct iax_dual *d;
  7782. struct ast_channel *chan1m, *chan2m;
  7783. pthread_t th;
  7784. chan1m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
  7785. chan2m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "IAXPeer/%s",chan2->name);
  7786. if (chan2m && chan1m) {
  7787. /* Make formats okay */
  7788. chan1m->readformat = chan1->readformat;
  7789. chan1m->writeformat = chan1->writeformat;
  7790. ast_channel_masquerade(chan1m, chan1);
  7791. /* Setup the extensions and such */
  7792. ast_copy_string(chan1m->context, chan1->context, sizeof(chan1m->context));
  7793. ast_copy_string(chan1m->exten, chan1->exten, sizeof(chan1m->exten));
  7794. chan1m->priority = chan1->priority;
  7795. /* We make a clone of the peer channel too, so we can play
  7796. back the announcement */
  7797. /* Make formats okay */
  7798. chan2m->readformat = chan2->readformat;
  7799. chan2m->writeformat = chan2->writeformat;
  7800. ast_channel_masquerade(chan2m, chan2);
  7801. /* Setup the extensions and such */
  7802. ast_copy_string(chan2m->context, chan2->context, sizeof(chan2m->context));
  7803. ast_copy_string(chan2m->exten, chan2->exten, sizeof(chan2m->exten));
  7804. chan2m->priority = chan2->priority;
  7805. if (ast_do_masquerade(chan2m)) {
  7806. ast_log(LOG_WARNING, "Masquerade failed :(\n");
  7807. ast_hangup(chan2m);
  7808. return -1;
  7809. }
  7810. } else {
  7811. if (chan1m)
  7812. ast_hangup(chan1m);
  7813. if (chan2m)
  7814. ast_hangup(chan2m);
  7815. return -1;
  7816. }
  7817. if ((d = ast_calloc(1, sizeof(*d)))) {
  7818. d->chan1 = chan1m;
  7819. d->chan2 = chan2m;
  7820. if (!ast_pthread_create_detached_background(&th, NULL, iax_park_thread, d)) {
  7821. return 0;
  7822. }
  7823. ast_free(d);
  7824. }
  7825. return -1;
  7826. }
  7827. static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
  7828. static int check_provisioning(struct sockaddr_in *sin, int sockfd, char *si, unsigned int ver)
  7829. {
  7830. unsigned int ourver;
  7831. char rsi[80];
  7832. snprintf(rsi, sizeof(rsi), "si-%s", si);
  7833. if (iax_provision_version(&ourver, rsi, 1))
  7834. return 0;
  7835. ast_debug(1, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
  7836. if (ourver != ver)
  7837. iax2_provision(sin, sockfd, NULL, rsi, 1);
  7838. return 0;
  7839. }
  7840. static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
  7841. {
  7842. jb_info stats;
  7843. jb_getinfo(pvt->jb, &stats);
  7844. memset(iep, 0, sizeof(*iep));
  7845. iax_ie_append_int(iep,IAX_IE_RR_JITTER, stats.jitter);
  7846. if(stats.frames_in == 0) stats.frames_in = 1;
  7847. iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
  7848. iax_ie_append_int(iep,IAX_IE_RR_PKTS, stats.frames_in);
  7849. iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
  7850. iax_ie_append_int(iep,IAX_IE_RR_DROPPED, stats.frames_dropped);
  7851. iax_ie_append_int(iep,IAX_IE_RR_OOO, stats.frames_ooo);
  7852. }
  7853. static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
  7854. {
  7855. iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
  7856. iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
  7857. iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
  7858. iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
  7859. iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
  7860. iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
  7861. iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
  7862. }
  7863. static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
  7864. {
  7865. int i;
  7866. unsigned int length, offset = 0;
  7867. char full_osptoken[IAX_MAX_OSPBUFF_SIZE];
  7868. for (i = 0; i < IAX_MAX_OSPBLOCK_NUM; i++) {
  7869. length = ies->ospblocklength[i];
  7870. if (length != 0) {
  7871. if (length > IAX_MAX_OSPBLOCK_SIZE) {
  7872. /* OSP token block length wrong, clear buffer */
  7873. offset = 0;
  7874. break;
  7875. } else {
  7876. memcpy(full_osptoken + offset, ies->osptokenblock[i], length);
  7877. offset += length;
  7878. }
  7879. } else {
  7880. break;
  7881. }
  7882. }
  7883. *(full_osptoken + offset) = '\0';
  7884. if (strlen(full_osptoken) != offset) {
  7885. /* OSP token length wrong, clear buffer */
  7886. *full_osptoken = '\0';
  7887. }
  7888. ast_string_field_set(iaxs[fr->callno], osptoken, full_osptoken);
  7889. }
  7890. static void log_jitterstats(unsigned short callno)
  7891. {
  7892. int localjitter = -1, localdelay = 0, locallost = -1, locallosspct = -1, localdropped = 0, localooo = -1, localpackets = -1;
  7893. jb_info jbinfo;
  7894. ast_mutex_lock(&iaxsl[callno]);
  7895. if (iaxs[callno] && iaxs[callno]->owner && iaxs[callno]->owner->name) {
  7896. if(ast_test_flag(iaxs[callno], IAX_USEJITTERBUF)) {
  7897. jb_getinfo(iaxs[callno]->jb, &jbinfo);
  7898. localjitter = jbinfo.jitter;
  7899. localdelay = jbinfo.current - jbinfo.min;
  7900. locallost = jbinfo.frames_lost;
  7901. locallosspct = jbinfo.losspct/1000;
  7902. localdropped = jbinfo.frames_dropped;
  7903. localooo = jbinfo.frames_ooo;
  7904. localpackets = jbinfo.frames_in;
  7905. }
  7906. ast_debug(3, "JB STATS:%s ping=%d 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",
  7907. iaxs[callno]->owner->name,
  7908. iaxs[callno]->pingtime,
  7909. localjitter,
  7910. localdelay,
  7911. locallost,
  7912. locallosspct,
  7913. localdropped,
  7914. localooo,
  7915. localpackets,
  7916. iaxs[callno]->remote_rr.jitter,
  7917. iaxs[callno]->remote_rr.delay,
  7918. iaxs[callno]->remote_rr.losscnt,
  7919. iaxs[callno]->remote_rr.losspct/1000,
  7920. iaxs[callno]->remote_rr.dropped,
  7921. iaxs[callno]->remote_rr.ooo,
  7922. iaxs[callno]->remote_rr.packets);
  7923. manager_event(EVENT_FLAG_REPORTING, "JitterBufStats", "Owner: %s\r\nPing: %d\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",
  7924. iaxs[callno]->owner->name,
  7925. iaxs[callno]->pingtime,
  7926. localjitter,
  7927. localdelay,
  7928. locallost,
  7929. locallosspct,
  7930. localdropped,
  7931. localooo,
  7932. localpackets,
  7933. iaxs[callno]->remote_rr.jitter,
  7934. iaxs[callno]->remote_rr.delay,
  7935. iaxs[callno]->remote_rr.losscnt,
  7936. iaxs[callno]->remote_rr.losspct/1000,
  7937. iaxs[callno]->remote_rr.dropped,
  7938. iaxs[callno]->remote_rr.ooo,
  7939. iaxs[callno]->remote_rr.packets);
  7940. }
  7941. ast_mutex_unlock(&iaxsl[callno]);
  7942. }
  7943. static int socket_process(struct iax2_thread *thread);
  7944. /*!
  7945. * \brief Handle any deferred full frames for this thread
  7946. */
  7947. static void handle_deferred_full_frames(struct iax2_thread *thread)
  7948. {
  7949. struct iax2_pkt_buf *pkt_buf;
  7950. ast_mutex_lock(&thread->lock);
  7951. while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
  7952. ast_mutex_unlock(&thread->lock);
  7953. thread->buf = pkt_buf->buf;
  7954. thread->buf_len = pkt_buf->len;
  7955. thread->buf_size = pkt_buf->len + 1;
  7956. socket_process(thread);
  7957. thread->buf = NULL;
  7958. ast_free(pkt_buf);
  7959. ast_mutex_lock(&thread->lock);
  7960. }
  7961. ast_mutex_unlock(&thread->lock);
  7962. }
  7963. /*!
  7964. * \brief Queue the last read full frame for processing by a certain thread
  7965. *
  7966. * If there are already any full frames queued, they are sorted
  7967. * by sequence number.
  7968. */
  7969. static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
  7970. {
  7971. struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
  7972. struct ast_iax2_full_hdr *fh, *cur_fh;
  7973. if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
  7974. return;
  7975. pkt_buf->len = from_here->buf_len;
  7976. memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
  7977. fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
  7978. ast_mutex_lock(&to_here->lock);
  7979. AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
  7980. cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
  7981. if (fh->oseqno < cur_fh->oseqno) {
  7982. AST_LIST_INSERT_BEFORE_CURRENT(pkt_buf, entry);
  7983. break;
  7984. }
  7985. }
  7986. AST_LIST_TRAVERSE_SAFE_END
  7987. if (!cur_pkt_buf)
  7988. AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
  7989. ast_mutex_unlock(&to_here->lock);
  7990. }
  7991. static int socket_read(int *id, int fd, short events, void *cbdata)
  7992. {
  7993. struct iax2_thread *thread;
  7994. socklen_t len;
  7995. time_t t;
  7996. static time_t last_errtime = 0;
  7997. struct ast_iax2_full_hdr *fh;
  7998. if (!(thread = find_idle_thread())) {
  7999. time(&t);
  8000. if (t != last_errtime)
  8001. ast_debug(1, "Out of idle IAX2 threads for I/O, pausing!\n");
  8002. last_errtime = t;
  8003. usleep(1);
  8004. return 1;
  8005. }
  8006. len = sizeof(thread->iosin);
  8007. thread->iofd = fd;
  8008. thread->buf_len = recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, (struct sockaddr *) &thread->iosin, &len);
  8009. thread->buf_size = sizeof(thread->readbuf);
  8010. thread->buf = thread->readbuf;
  8011. if (thread->buf_len < 0) {
  8012. if (errno != ECONNREFUSED && errno != EAGAIN)
  8013. ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
  8014. handle_error();
  8015. thread->iostate = IAX_IOSTATE_IDLE;
  8016. signal_condition(&thread->lock, &thread->cond);
  8017. return 1;
  8018. }
  8019. if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) { /* simulate random loss condition */
  8020. thread->iostate = IAX_IOSTATE_IDLE;
  8021. signal_condition(&thread->lock, &thread->cond);
  8022. return 1;
  8023. }
  8024. /* Determine if this frame is a full frame; if so, and any thread is currently
  8025. processing a full frame for the same callno from this peer, then drop this
  8026. frame (and the peer will retransmit it) */
  8027. fh = (struct ast_iax2_full_hdr *) thread->buf;
  8028. if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
  8029. struct iax2_thread *cur = NULL;
  8030. uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
  8031. AST_LIST_LOCK(&active_list);
  8032. AST_LIST_TRAVERSE(&active_list, cur, list) {
  8033. if ((cur->ffinfo.callno == callno) &&
  8034. !inaddrcmp(&cur->ffinfo.sin, &thread->iosin))
  8035. break;
  8036. }
  8037. if (cur) {
  8038. /* we found another thread processing a full frame for this call,
  8039. so queue it up for processing later. */
  8040. defer_full_frame(thread, cur);
  8041. AST_LIST_UNLOCK(&active_list);
  8042. thread->iostate = IAX_IOSTATE_IDLE;
  8043. signal_condition(&thread->lock, &thread->cond);
  8044. return 1;
  8045. } else {
  8046. /* this thread is going to process this frame, so mark it */
  8047. thread->ffinfo.callno = callno;
  8048. memcpy(&thread->ffinfo.sin, &thread->iosin, sizeof(thread->ffinfo.sin));
  8049. thread->ffinfo.type = fh->type;
  8050. thread->ffinfo.csub = fh->csub;
  8051. }
  8052. AST_LIST_UNLOCK(&active_list);
  8053. }
  8054. /* Mark as ready and send on its way */
  8055. thread->iostate = IAX_IOSTATE_READY;
  8056. #ifdef DEBUG_SCHED_MULTITHREAD
  8057. ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
  8058. #endif
  8059. signal_condition(&thread->lock, &thread->cond);
  8060. return 1;
  8061. }
  8062. static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct sockaddr_in *sin, int sockfd,
  8063. struct iax_frame *fr)
  8064. {
  8065. unsigned char metatype;
  8066. struct ast_iax2_meta_trunk_mini *mtm;
  8067. struct ast_iax2_meta_trunk_hdr *mth;
  8068. struct ast_iax2_meta_trunk_entry *mte;
  8069. struct iax2_trunk_peer *tpeer;
  8070. unsigned int ts;
  8071. void *ptr;
  8072. struct timeval rxtrunktime;
  8073. struct ast_frame f = { 0, };
  8074. if (packet_len < sizeof(*meta)) {
  8075. ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a meta frame but is too short\n",
  8076. ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
  8077. return 1;
  8078. }
  8079. if (meta->metacmd != IAX_META_TRUNK)
  8080. return 1;
  8081. if (packet_len < (sizeof(*meta) + sizeof(*mth))) {
  8082. ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %d min)\n", packet_len,
  8083. (int) (sizeof(*meta) + sizeof(*mth)));
  8084. return 1;
  8085. }
  8086. mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
  8087. ts = ntohl(mth->ts);
  8088. metatype = meta->cmddata;
  8089. packet_len -= (sizeof(*meta) + sizeof(*mth));
  8090. ptr = mth->data;
  8091. tpeer = find_tpeer(sin, sockfd);
  8092. if (!tpeer) {
  8093. ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s:%d': No matching peer\n",
  8094. ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
  8095. return 1;
  8096. }
  8097. tpeer->trunkact = ast_tvnow();
  8098. if (!ts || ast_tvzero(tpeer->rxtrunktime))
  8099. tpeer->rxtrunktime = tpeer->trunkact;
  8100. rxtrunktime = tpeer->rxtrunktime;
  8101. ast_mutex_unlock(&tpeer->lock);
  8102. while (packet_len >= sizeof(*mte)) {
  8103. /* Process channels */
  8104. unsigned short callno, trunked_ts, len;
  8105. if (metatype == IAX_META_TRUNK_MINI) {
  8106. mtm = (struct ast_iax2_meta_trunk_mini *) ptr;
  8107. ptr += sizeof(*mtm);
  8108. packet_len -= sizeof(*mtm);
  8109. len = ntohs(mtm->len);
  8110. callno = ntohs(mtm->mini.callno);
  8111. trunked_ts = ntohs(mtm->mini.ts);
  8112. } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
  8113. mte = (struct ast_iax2_meta_trunk_entry *)ptr;
  8114. ptr += sizeof(*mte);
  8115. packet_len -= sizeof(*mte);
  8116. len = ntohs(mte->len);
  8117. callno = ntohs(mte->callno);
  8118. trunked_ts = 0;
  8119. } else {
  8120. ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
  8121. break;
  8122. }
  8123. /* Stop if we don't have enough data */
  8124. if (len > packet_len)
  8125. break;
  8126. fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, sin, NEW_PREVENT, sockfd, 0);
  8127. if (!fr->callno)
  8128. continue;
  8129. /* If it's a valid call, deliver the contents. If not, we
  8130. drop it, since we don't have a scallno to use for an INVAL */
  8131. /* Process as a mini frame */
  8132. memset(&f, 0, sizeof(f));
  8133. f.frametype = AST_FRAME_VOICE;
  8134. if (!iaxs[fr->callno]) {
  8135. /* drop it */
  8136. } else if (iaxs[fr->callno]->voiceformat == 0) {
  8137. ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n");
  8138. iax2_vnak(fr->callno);
  8139. } else {
  8140. f.subclass = iaxs[fr->callno]->voiceformat;
  8141. f.datalen = len;
  8142. if (f.datalen >= 0) {
  8143. if (f.datalen)
  8144. f.data = ptr;
  8145. else
  8146. f.data = NULL;
  8147. if (trunked_ts)
  8148. fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
  8149. else
  8150. fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
  8151. /* Don't pass any packets until we're started */
  8152. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
  8153. struct iax_frame *duped_fr;
  8154. /* Common things */
  8155. f.src = "IAX2";
  8156. f.mallocd = 0;
  8157. f.offset = 0;
  8158. if (f.datalen && (f.frametype == AST_FRAME_VOICE))
  8159. f.samples = ast_codec_get_samples(&f);
  8160. else
  8161. f.samples = 0;
  8162. fr->outoforder = 0;
  8163. iax_frame_wrap(fr, &f);
  8164. duped_fr = iaxfrdup2(fr);
  8165. if (duped_fr)
  8166. schedule_delivery(duped_fr, 1, 1, &fr->ts);
  8167. if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts)
  8168. iaxs[fr->callno]->last = fr->ts;
  8169. }
  8170. } else {
  8171. ast_log(LOG_WARNING, "Datalen < 0?\n");
  8172. }
  8173. }
  8174. ast_mutex_unlock(&iaxsl[fr->callno]);
  8175. ptr += len;
  8176. packet_len -= len;
  8177. }
  8178. return 1;
  8179. }
  8180. static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  8181. {
  8182. struct ast_datastore *variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
  8183. AST_LIST_HEAD(, ast_var_t) *varlist;
  8184. struct ast_var_t *var;
  8185. if (!variablestore) {
  8186. *buf = '\0';
  8187. return 0;
  8188. }
  8189. varlist = variablestore->data;
  8190. AST_LIST_LOCK(varlist);
  8191. AST_LIST_TRAVERSE(varlist, var, entries) {
  8192. if (strcmp(var->name, data) == 0) {
  8193. ast_copy_string(buf, var->value, len);
  8194. break;
  8195. }
  8196. }
  8197. AST_LIST_UNLOCK(varlist);
  8198. return 0;
  8199. }
  8200. static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
  8201. {
  8202. struct ast_datastore *variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
  8203. AST_LIST_HEAD(, ast_var_t) *varlist;
  8204. struct ast_var_t *var;
  8205. if (!variablestore) {
  8206. variablestore = ast_channel_datastore_alloc(&iax2_variable_datastore_info, NULL);
  8207. if (!variablestore) {
  8208. ast_log(LOG_ERROR, "Memory allocation error\n");
  8209. return -1;
  8210. }
  8211. varlist = ast_calloc(1, sizeof(*varlist));
  8212. if (!varlist) {
  8213. ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
  8214. return -1;
  8215. }
  8216. AST_LIST_HEAD_INIT(varlist);
  8217. variablestore->data = varlist;
  8218. variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
  8219. ast_channel_datastore_add(chan, variablestore);
  8220. } else
  8221. varlist = variablestore->data;
  8222. AST_LIST_LOCK(varlist);
  8223. AST_LIST_TRAVERSE_SAFE_BEGIN(varlist, var, entries) {
  8224. if (strcmp(var->name, data) == 0) {
  8225. AST_LIST_REMOVE_CURRENT(entries);
  8226. ast_var_delete(var);
  8227. break;
  8228. }
  8229. }
  8230. AST_LIST_TRAVERSE_SAFE_END;
  8231. var = ast_var_assign(data, value);
  8232. if (var)
  8233. AST_LIST_INSERT_TAIL(varlist, var, entries);
  8234. else
  8235. ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
  8236. AST_LIST_UNLOCK(varlist);
  8237. return 0;
  8238. }
  8239. static struct ast_custom_function iaxvar_function = {
  8240. .name = "IAXVAR",
  8241. .synopsis = "Sets or retrieves a remote variable",
  8242. .syntax = "IAXVAR(<varname>)",
  8243. .read = acf_iaxvar_read,
  8244. .write = acf_iaxvar_write,
  8245. };
  8246. static int socket_process(struct iax2_thread *thread)
  8247. {
  8248. struct sockaddr_in sin;
  8249. int res;
  8250. int updatehistory=1;
  8251. int new = NEW_PREVENT;
  8252. int dcallno = 0;
  8253. char decrypted = 0;
  8254. struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
  8255. struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
  8256. struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
  8257. struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
  8258. struct iax_frame *fr;
  8259. struct iax_frame *cur;
  8260. struct ast_frame f = { 0, };
  8261. struct ast_channel *c = NULL;
  8262. struct iax2_dpcache *dp;
  8263. struct iax2_peer *peer;
  8264. struct iax_ies ies;
  8265. struct iax_ie_data ied0, ied1;
  8266. int format;
  8267. int fd;
  8268. int exists;
  8269. int minivid = 0;
  8270. char empty[32]=""; /* Safety measure */
  8271. struct iax_frame *duped_fr;
  8272. char host_pref_buf[128];
  8273. char caller_pref_buf[128];
  8274. struct ast_codec_pref pref;
  8275. char *using_prefs = "mine";
  8276. /* allocate an iax_frame with 4096 bytes of data buffer */
  8277. fr = alloca(sizeof(*fr) + 4096);
  8278. memset(fr, 0, sizeof(*fr));
  8279. fr->afdatalen = 4096; /* From alloca() above */
  8280. /* Copy frequently used parameters to the stack */
  8281. res = thread->buf_len;
  8282. fd = thread->iofd;
  8283. memcpy(&sin, &thread->iosin, sizeof(sin));
  8284. if (res < sizeof(*mh)) {
  8285. ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int) sizeof(*mh));
  8286. return 1;
  8287. }
  8288. if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
  8289. if (res < sizeof(*vh)) {
  8290. 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));
  8291. return 1;
  8292. }
  8293. /* This is a video frame, get call number */
  8294. fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, fd, 0);
  8295. minivid = 1;
  8296. } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000))
  8297. return socket_process_meta(res, meta, &sin, fd, fr);
  8298. #ifdef DEBUG_SUPPORT
  8299. if (iaxdebug && (res >= sizeof(*fh)))
  8300. iax_showframe(NULL, fh, 1, &sin, res - sizeof(*fh));
  8301. #endif
  8302. if (ntohs(mh->callno) & IAX_FLAG_FULL) {
  8303. if (res < sizeof(*fh)) {
  8304. 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));
  8305. return 1;
  8306. }
  8307. /* Get the destination call number */
  8308. dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
  8309. /* check to make sure this full frame isn't encrypted before we attempt
  8310. * to look inside of it. If it is encrypted, decrypt it first. Its ok if the
  8311. * callno is not found here, that just means one hasn't been allocated for
  8312. * this connection yet. */
  8313. if ((dcallno != 1) && (fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, NEW_PREVENT, fd, 1))) {
  8314. ast_mutex_lock(&iaxsl[fr->callno]);
  8315. if (iaxs[fr->callno] && ast_test_flag(iaxs[fr->callno], IAX_ENCRYPTED)) {
  8316. if (decrypt_frame(fr->callno, fh, &f, &res)) {
  8317. ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
  8318. ast_mutex_unlock(&iaxsl[fr->callno]);
  8319. return 1;
  8320. }
  8321. decrypted = 1;
  8322. }
  8323. ast_mutex_unlock(&iaxsl[fr->callno]);
  8324. }
  8325. /* Retrieve the type and subclass */
  8326. f.frametype = fh->type;
  8327. if (f.frametype == AST_FRAME_VIDEO) {
  8328. f.subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
  8329. } else {
  8330. f.subclass = uncompress_subclass(fh->csub);
  8331. }
  8332. /* Deal with POKE/PONG without allocating a callno */
  8333. if (f.frametype == AST_FRAME_IAX && f.subclass == IAX_COMMAND_POKE) {
  8334. /* Reply back with a PONG, but don't care about the result. */
  8335. send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_PONG, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
  8336. return 1;
  8337. } else if (f.frametype == AST_FRAME_IAX && f.subclass == IAX_COMMAND_ACK && dcallno == 1) {
  8338. /* Ignore */
  8339. return 1;
  8340. }
  8341. f.datalen = res - sizeof(*fh);
  8342. if (f.datalen) {
  8343. if (f.frametype == AST_FRAME_IAX) {
  8344. if (iax_parse_ies(&ies, thread->buf + sizeof(*fh), f.datalen)) {
  8345. ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin.sin_addr));
  8346. return 1;
  8347. }
  8348. f.data = NULL;
  8349. f.datalen = 0;
  8350. } else {
  8351. f.data = thread->buf + sizeof(*fh);
  8352. memset(&ies, 0, sizeof(ies));
  8353. }
  8354. } else {
  8355. if (f.frametype == AST_FRAME_IAX)
  8356. f.data = NULL;
  8357. else
  8358. f.data = empty;
  8359. memset(&ies, 0, sizeof(ies));
  8360. }
  8361. if (!dcallno && iax2_allow_new(f.frametype, f.subclass, 1)) {
  8362. /* only set NEW_ALLOW if calltoken checks out */
  8363. if (handle_call_token(fh, &ies, &sin, fd)) {
  8364. return 1;
  8365. }
  8366. if (ies.calltoken && ies.calltokendata) {
  8367. /* if we've gotten this far, and the calltoken ie data exists,
  8368. * then calltoken validation _MUST_ have taken place. If calltoken
  8369. * data is provided, it is always validated reguardless of any
  8370. * calltokenoptional or requirecalltoken options */
  8371. new = NEW_ALLOW_CALLTOKEN_VALIDATED;
  8372. } else {
  8373. new = NEW_ALLOW;
  8374. }
  8375. }
  8376. } else {
  8377. /* Don't know anything about it yet */
  8378. f.frametype = AST_FRAME_NULL;
  8379. f.subclass = 0;
  8380. }
  8381. if (!fr->callno) {
  8382. int check_dcallno = 0;
  8383. /*
  8384. * We enforce accurate destination call numbers for ACKs. This forces the other
  8385. * end to know the destination call number before call setup can complete.
  8386. *
  8387. * Discussed in the following thread:
  8388. * http://lists.digium.com/pipermail/asterisk-dev/2008-May/033217.html
  8389. */
  8390. if ((ntohs(mh->callno) & IAX_FLAG_FULL) && ((f.frametype == AST_FRAME_IAX) && (f.subclass == IAX_COMMAND_ACK))) {
  8391. check_dcallno = 1;
  8392. }
  8393. if (!(fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, new, fd, check_dcallno))) {
  8394. if (f.frametype == AST_FRAME_IAX && f.subclass == IAX_COMMAND_NEW) {
  8395. send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
  8396. } else if (f.frametype == AST_FRAME_IAX && (f.subclass == IAX_COMMAND_REGREQ || f.subclass == IAX_COMMAND_REGREL)) {
  8397. send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
  8398. }
  8399. return 1;
  8400. }
  8401. }
  8402. if (fr->callno > 0)
  8403. ast_mutex_lock(&iaxsl[fr->callno]);
  8404. if (!fr->callno || !iaxs[fr->callno]) {
  8405. /* A call arrived for a nonexistent destination. Unless it's an "inval"
  8406. frame, reply with an inval */
  8407. if (ntohs(mh->callno) & IAX_FLAG_FULL) {
  8408. /* We can only raw hangup control frames */
  8409. if (((f.subclass != IAX_COMMAND_INVAL) &&
  8410. (f.subclass != IAX_COMMAND_TXCNT) &&
  8411. (f.subclass != IAX_COMMAND_TXACC) &&
  8412. (f.subclass != IAX_COMMAND_FWDOWNL))||
  8413. (f.frametype != AST_FRAME_IAX))
  8414. raw_hangup(&sin, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
  8415. fd);
  8416. }
  8417. if (fr->callno > 0)
  8418. ast_mutex_unlock(&iaxsl[fr->callno]);
  8419. return 1;
  8420. }
  8421. if (ast_test_flag(iaxs[fr->callno], IAX_ENCRYPTED) && !decrypted) {
  8422. if (decrypt_frame(fr->callno, fh, &f, &res)) {
  8423. ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
  8424. ast_mutex_unlock(&iaxsl[fr->callno]);
  8425. return 1;
  8426. }
  8427. decrypted = 1;
  8428. }
  8429. #ifdef DEBUG_SUPPORT
  8430. if (decrypted && iaxdebug)
  8431. iax_showframe(NULL, fh, 3, &sin, res - sizeof(*fh));
  8432. #endif
  8433. /* count this frame */
  8434. iaxs[fr->callno]->frames_received++;
  8435. if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && !minivid &&
  8436. f.subclass != IAX_COMMAND_TXCNT && /* for attended transfer */
  8437. f.subclass != IAX_COMMAND_TXACC) { /* for attended transfer */
  8438. unsigned short new_peercallno;
  8439. new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
  8440. if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
  8441. if (iaxs[fr->callno]->peercallno) {
  8442. remove_by_peercallno(iaxs[fr->callno]);
  8443. }
  8444. iaxs[fr->callno]->peercallno = new_peercallno;
  8445. store_by_peercallno(iaxs[fr->callno]);
  8446. }
  8447. }
  8448. if (ntohs(mh->callno) & IAX_FLAG_FULL) {
  8449. if (iaxdebug)
  8450. ast_debug(1, "Received packet %d, (%d, %d)\n", fh->oseqno, f.frametype, f.subclass);
  8451. /* Check if it's out of order (and not an ACK or INVAL) */
  8452. fr->oseqno = fh->oseqno;
  8453. fr->iseqno = fh->iseqno;
  8454. fr->ts = ntohl(fh->ts);
  8455. #ifdef IAXTESTS
  8456. if (test_resync) {
  8457. ast_debug(1, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
  8458. fr->ts += test_resync;
  8459. }
  8460. #endif /* IAXTESTS */
  8461. #if 0
  8462. if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
  8463. ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
  8464. (f.subclass == IAX_COMMAND_NEW ||
  8465. f.subclass == IAX_COMMAND_AUTHREQ ||
  8466. f.subclass == IAX_COMMAND_ACCEPT ||
  8467. f.subclass == IAX_COMMAND_REJECT)) ) )
  8468. #endif
  8469. if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
  8470. updatehistory = 0;
  8471. if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
  8472. (iaxs[fr->callno]->iseqno ||
  8473. ((f.subclass != IAX_COMMAND_TXCNT) &&
  8474. (f.subclass != IAX_COMMAND_TXREADY) && /* for attended transfer */
  8475. (f.subclass != IAX_COMMAND_TXREL) && /* for attended transfer */
  8476. (f.subclass != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
  8477. (f.subclass != IAX_COMMAND_TXACC)) ||
  8478. (f.frametype != AST_FRAME_IAX))) {
  8479. if (
  8480. ((f.subclass != IAX_COMMAND_ACK) &&
  8481. (f.subclass != IAX_COMMAND_INVAL) &&
  8482. (f.subclass != IAX_COMMAND_TXCNT) &&
  8483. (f.subclass != IAX_COMMAND_TXREADY) && /* for attended transfer */
  8484. (f.subclass != IAX_COMMAND_TXREL) && /* for attended transfer */
  8485. (f.subclass != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
  8486. (f.subclass != IAX_COMMAND_TXACC) &&
  8487. (f.subclass != IAX_COMMAND_VNAK)) ||
  8488. (f.frametype != AST_FRAME_IAX)) {
  8489. /* If it's not an ACK packet, it's out of order. */
  8490. ast_debug(1, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
  8491. iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass);
  8492. /* Check to see if we need to request retransmission,
  8493. * and take sequence number wraparound into account */
  8494. if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
  8495. /* If we've already seen it, ack it XXX There's a border condition here XXX */
  8496. if ((f.frametype != AST_FRAME_IAX) ||
  8497. ((f.subclass != IAX_COMMAND_ACK) && (f.subclass != IAX_COMMAND_INVAL))) {
  8498. ast_debug(1, "Acking anyway\n");
  8499. /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
  8500. we have anything to send, we'll retransmit and get an ACK back anyway XXX */
  8501. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  8502. }
  8503. } else {
  8504. /* Send a VNAK requesting retransmission */
  8505. iax2_vnak(fr->callno);
  8506. }
  8507. ast_mutex_unlock(&iaxsl[fr->callno]);
  8508. return 1;
  8509. }
  8510. } else {
  8511. /* Increment unless it's an ACK or VNAK */
  8512. if (((f.subclass != IAX_COMMAND_ACK) &&
  8513. (f.subclass != IAX_COMMAND_INVAL) &&
  8514. (f.subclass != IAX_COMMAND_TXCNT) &&
  8515. (f.subclass != IAX_COMMAND_TXACC) &&
  8516. (f.subclass != IAX_COMMAND_VNAK)) ||
  8517. (f.frametype != AST_FRAME_IAX))
  8518. iaxs[fr->callno]->iseqno++;
  8519. }
  8520. /* Ensure text frames are NULL-terminated */
  8521. if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
  8522. if (res < thread->buf_size)
  8523. thread->buf[res++] = '\0';
  8524. else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
  8525. thread->buf[res - 1] = '\0';
  8526. }
  8527. /* Handle implicit ACKing unless this is an INVAL, and only if this is
  8528. from the real peer, not the transfer peer */
  8529. if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
  8530. ((f.subclass != IAX_COMMAND_INVAL) ||
  8531. (f.frametype != AST_FRAME_IAX))) {
  8532. unsigned char x;
  8533. int call_to_destroy;
  8534. /* XXX This code is not very efficient. Surely there is a better way which still
  8535. properly handles boundary conditions? XXX */
  8536. /* First we have to qualify that the ACKed value is within our window */
  8537. for (x=iaxs[fr->callno]->rseqno; x != iaxs[fr->callno]->oseqno; x++)
  8538. if (fr->iseqno == x)
  8539. break;
  8540. if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
  8541. /* The acknowledgement is within our window. Time to acknowledge everything
  8542. that it says to */
  8543. for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
  8544. /* Ack the packet with the given timestamp */
  8545. if (iaxdebug)
  8546. ast_debug(1, "Cancelling transmission of packet %d\n", x);
  8547. call_to_destroy = 0;
  8548. AST_LIST_LOCK(&frame_queue);
  8549. AST_LIST_TRAVERSE(&frame_queue, cur, list) {
  8550. /* If it's our call, and our timestamp, mark -1 retries */
  8551. if ((fr->callno == cur->callno) && (x == cur->oseqno)) {
  8552. cur->retries = -1;
  8553. /* Destroy call if this is the end */
  8554. if (cur->final)
  8555. call_to_destroy = fr->callno;
  8556. }
  8557. }
  8558. AST_LIST_UNLOCK(&frame_queue);
  8559. if (call_to_destroy) {
  8560. if (iaxdebug)
  8561. ast_debug(1, "Really destroying %d, having been acked on final message\n", call_to_destroy);
  8562. ast_mutex_lock(&iaxsl[call_to_destroy]);
  8563. iax2_destroy(call_to_destroy);
  8564. ast_mutex_unlock(&iaxsl[call_to_destroy]);
  8565. }
  8566. }
  8567. /* Note how much we've received acknowledgement for */
  8568. if (iaxs[fr->callno])
  8569. iaxs[fr->callno]->rseqno = fr->iseqno;
  8570. else {
  8571. /* Stop processing now */
  8572. ast_mutex_unlock(&iaxsl[fr->callno]);
  8573. return 1;
  8574. }
  8575. } else {
  8576. ast_debug(1, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
  8577. }
  8578. }
  8579. if (inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
  8580. ((f.frametype != AST_FRAME_IAX) ||
  8581. ((f.subclass != IAX_COMMAND_TXACC) &&
  8582. (f.subclass != IAX_COMMAND_TXCNT)))) {
  8583. /* Only messages we accept from a transfer host are TXACC and TXCNT */
  8584. ast_mutex_unlock(&iaxsl[fr->callno]);
  8585. return 1;
  8586. }
  8587. /* when we receive the first full frame for a new incoming channel,
  8588. it is safe to start the PBX on the channel because we have now
  8589. completed a 3-way handshake with the peer */
  8590. if ((f.frametype == AST_FRAME_VOICE) ||
  8591. (f.frametype == AST_FRAME_VIDEO) ||
  8592. (f.frametype == AST_FRAME_IAX)) {
  8593. if (ast_test_flag(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
  8594. ast_clear_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
  8595. if (!ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->chosenformat)) {
  8596. ast_mutex_unlock(&iaxsl[fr->callno]);
  8597. return 1;
  8598. }
  8599. }
  8600. if (ies.vars) {
  8601. struct ast_datastore *variablestore;
  8602. struct ast_variable *var, *prev = NULL;
  8603. AST_LIST_HEAD(, ast_var_t) *varlist;
  8604. if ((c = iaxs[fr->callno]->owner)) {
  8605. varlist = ast_calloc(1, sizeof(*varlist));
  8606. variablestore = ast_channel_datastore_alloc(&iax2_variable_datastore_info, NULL);
  8607. if (variablestore && varlist) {
  8608. variablestore->data = varlist;
  8609. variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
  8610. AST_LIST_HEAD_INIT(varlist);
  8611. ast_debug(1, "I can haz IAX vars?\n");
  8612. for (var = ies.vars; var; var = var->next) {
  8613. struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
  8614. if (prev) {
  8615. ast_free(prev);
  8616. }
  8617. prev = var;
  8618. if (!newvar) {
  8619. /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
  8620. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  8621. } else {
  8622. AST_LIST_INSERT_TAIL(varlist, newvar, entries);
  8623. }
  8624. }
  8625. if (prev) {
  8626. ast_free(prev);
  8627. }
  8628. ies.vars = NULL;
  8629. ast_channel_datastore_add(c, variablestore);
  8630. } else {
  8631. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  8632. if (variablestore) {
  8633. ast_channel_datastore_free(variablestore);
  8634. }
  8635. if (varlist) {
  8636. ast_free(varlist);
  8637. }
  8638. }
  8639. } else {
  8640. /* No channel yet, so transfer the variables directly over to the pvt,
  8641. * for later inheritance. */
  8642. ast_debug(1, "No channel, so populating IAXVARs to the pvt, as an intermediate step.\n");
  8643. for (var = ies.vars; var && var->next; var = var->next);
  8644. if (var) {
  8645. var->next = iaxs[fr->callno]->iaxvars;
  8646. iaxs[fr->callno]->iaxvars = ies.vars;
  8647. ies.vars = NULL;
  8648. }
  8649. }
  8650. }
  8651. }
  8652. if (ies.vars) {
  8653. ast_debug(1, "I have IAX variables, but they were not processed\n");
  8654. }
  8655. /* once we receive our first IAX Full Frame that is not CallToken related, send all
  8656. * queued signaling frames that were being held. */
  8657. if ((f.frametype == AST_FRAME_IAX) && (f.subclass != IAX_COMMAND_CALLTOKEN) && iaxs[fr->callno]->hold_signaling) {
  8658. send_signaling(iaxs[fr->callno]);
  8659. }
  8660. if (f.frametype == AST_FRAME_VOICE) {
  8661. if (f.subclass != iaxs[fr->callno]->voiceformat) {
  8662. iaxs[fr->callno]->voiceformat = f.subclass;
  8663. ast_debug(1, "Ooh, voice format changed to %d\n", f.subclass);
  8664. if (iaxs[fr->callno]->owner) {
  8665. int orignative;
  8666. retryowner:
  8667. if (ast_channel_trylock(iaxs[fr->callno]->owner)) {
  8668. DEADLOCK_AVOIDANCE(&iaxsl[fr->callno]);
  8669. if (iaxs[fr->callno] && iaxs[fr->callno]->owner) goto retryowner;
  8670. }
  8671. if (iaxs[fr->callno]) {
  8672. if (iaxs[fr->callno]->owner) {
  8673. orignative = iaxs[fr->callno]->owner->nativeformats;
  8674. iaxs[fr->callno]->owner->nativeformats = f.subclass;
  8675. if (iaxs[fr->callno]->owner->readformat)
  8676. ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
  8677. iaxs[fr->callno]->owner->nativeformats = orignative;
  8678. ast_channel_unlock(iaxs[fr->callno]->owner);
  8679. }
  8680. } else {
  8681. ast_debug(1, "Neat, somebody took away the channel at a magical time but i found it!\n");
  8682. /* Free remote variables (if any) */
  8683. if (ies.vars) {
  8684. ast_variables_destroy(ies.vars);
  8685. ast_debug(1, "I can haz iaxvars, but they is no good. :-(\n");
  8686. ies.vars = NULL;
  8687. }
  8688. ast_mutex_unlock(&iaxsl[fr->callno]);
  8689. return 1;
  8690. }
  8691. }
  8692. }
  8693. }
  8694. if (f.frametype == AST_FRAME_VIDEO) {
  8695. if (f.subclass != iaxs[fr->callno]->videoformat) {
  8696. ast_debug(1, "Ooh, video format changed to %d\n", f.subclass & ~0x1);
  8697. iaxs[fr->callno]->videoformat = f.subclass & ~0x1;
  8698. }
  8699. }
  8700. if (f.frametype == AST_FRAME_CONTROL && iaxs[fr->callno]->owner) {
  8701. if (f.subclass == AST_CONTROL_BUSY) {
  8702. iaxs[fr->callno]->owner->hangupcause = AST_CAUSE_BUSY;
  8703. } else if (f.subclass == AST_CONTROL_CONGESTION) {
  8704. iaxs[fr->callno]->owner->hangupcause = AST_CAUSE_CONGESTION;
  8705. }
  8706. }
  8707. if (f.frametype == AST_FRAME_IAX) {
  8708. AST_SCHED_DEL(sched, iaxs[fr->callno]->initid);
  8709. /* Handle the IAX pseudo frame itself */
  8710. if (iaxdebug)
  8711. ast_debug(1, "IAX subclass %d received\n", f.subclass);
  8712. /* Update last ts unless the frame's timestamp originated with us. */
  8713. if (iaxs[fr->callno]->last < fr->ts &&
  8714. f.subclass != IAX_COMMAND_ACK &&
  8715. f.subclass != IAX_COMMAND_PONG &&
  8716. f.subclass != IAX_COMMAND_LAGRP) {
  8717. iaxs[fr->callno]->last = fr->ts;
  8718. if (iaxdebug)
  8719. ast_debug(1, "For call=%d, set last=%d\n", fr->callno, fr->ts);
  8720. }
  8721. iaxs[fr->callno]->last_iax_message = f.subclass;
  8722. if (!iaxs[fr->callno]->first_iax_message) {
  8723. iaxs[fr->callno]->first_iax_message = f.subclass;
  8724. }
  8725. switch(f.subclass) {
  8726. case IAX_COMMAND_ACK:
  8727. /* Do nothing */
  8728. break;
  8729. case IAX_COMMAND_QUELCH:
  8730. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
  8731. /* Generate Manager Hold event, if necessary*/
  8732. if (iaxs[fr->callno]->owner) {
  8733. manager_event(EVENT_FLAG_CALL, "Hold",
  8734. "Status: On\r\n"
  8735. "Channel: %s\r\n"
  8736. "Uniqueid: %s\r\n",
  8737. iaxs[fr->callno]->owner->name,
  8738. iaxs[fr->callno]->owner->uniqueid);
  8739. }
  8740. ast_set_flag(iaxs[fr->callno], IAX_QUELCH);
  8741. if (ies.musiconhold) {
  8742. if (iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner)) {
  8743. const char *mohsuggest = iaxs[fr->callno]->mohsuggest;
  8744. iax2_queue_control_data(fr->callno, AST_CONTROL_HOLD,
  8745. S_OR(mohsuggest, NULL),
  8746. !ast_strlen_zero(mohsuggest) ? strlen(mohsuggest) + 1 : 0);
  8747. if (!iaxs[fr->callno]) {
  8748. ast_mutex_unlock(&iaxsl[fr->callno]);
  8749. return 1;
  8750. }
  8751. }
  8752. }
  8753. }
  8754. break;
  8755. case IAX_COMMAND_UNQUELCH:
  8756. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
  8757. /* Generate Manager Unhold event, if necessary*/
  8758. if (iaxs[fr->callno]->owner && ast_test_flag(iaxs[fr->callno], IAX_QUELCH)) {
  8759. manager_event(EVENT_FLAG_CALL, "Hold",
  8760. "Status: Off\r\n"
  8761. "Channel: %s\r\n"
  8762. "Uniqueid: %s\r\n",
  8763. iaxs[fr->callno]->owner->name,
  8764. iaxs[fr->callno]->owner->uniqueid);
  8765. }
  8766. ast_clear_flag(iaxs[fr->callno], IAX_QUELCH);
  8767. if (iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner)) {
  8768. iax2_queue_control_data(fr->callno, AST_CONTROL_UNHOLD, NULL, 0);
  8769. if (!iaxs[fr->callno]) {
  8770. ast_mutex_unlock(&iaxsl[fr->callno]);
  8771. return 1;
  8772. }
  8773. }
  8774. }
  8775. break;
  8776. case IAX_COMMAND_TXACC:
  8777. if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
  8778. /* Ack the packet with the given timestamp */
  8779. AST_LIST_LOCK(&frame_queue);
  8780. AST_LIST_TRAVERSE(&frame_queue, cur, list) {
  8781. /* Cancel any outstanding txcnt's */
  8782. if ((fr->callno == cur->callno) && (cur->transfer))
  8783. cur->retries = -1;
  8784. }
  8785. AST_LIST_UNLOCK(&frame_queue);
  8786. memset(&ied1, 0, sizeof(ied1));
  8787. iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
  8788. send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
  8789. iaxs[fr->callno]->transferring = TRANSFER_READY;
  8790. }
  8791. break;
  8792. case IAX_COMMAND_NEW:
  8793. /* Ignore if it's already up */
  8794. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD))
  8795. break;
  8796. if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
  8797. ast_mutex_unlock(&iaxsl[fr->callno]);
  8798. check_provisioning(&sin, fd, ies.serviceident, ies.provver);
  8799. ast_mutex_lock(&iaxsl[fr->callno]);
  8800. if (!iaxs[fr->callno]) {
  8801. ast_mutex_unlock(&iaxsl[fr->callno]);
  8802. return 1;
  8803. }
  8804. }
  8805. /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
  8806. if (ast_test_flag(iaxs[fr->callno], IAX_TRUNK)) {
  8807. int new_callno;
  8808. if ((new_callno = make_trunk(fr->callno, 1)) != -1)
  8809. fr->callno = new_callno;
  8810. }
  8811. /* For security, always ack immediately */
  8812. if (delayreject)
  8813. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  8814. if (check_access(fr->callno, &sin, &ies)) {
  8815. /* They're not allowed on */
  8816. auth_fail(fr->callno, IAX_COMMAND_REJECT);
  8817. if (authdebug)
  8818. 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);
  8819. break;
  8820. }
  8821. if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
  8822. const char *context, *exten, *cid_num;
  8823. context = ast_strdupa(iaxs[fr->callno]->context);
  8824. exten = ast_strdupa(iaxs[fr->callno]->exten);
  8825. cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
  8826. /* This might re-enter the IAX code and need the lock */
  8827. ast_mutex_unlock(&iaxsl[fr->callno]);
  8828. exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
  8829. ast_mutex_lock(&iaxsl[fr->callno]);
  8830. if (!iaxs[fr->callno]) {
  8831. ast_mutex_unlock(&iaxsl[fr->callno]);
  8832. return 1;
  8833. }
  8834. } else
  8835. exists = 0;
  8836. /* Get OSP token if it does exist */
  8837. save_osptoken(fr, &ies);
  8838. if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
  8839. if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
  8840. memset(&ied0, 0, sizeof(ied0));
  8841. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
  8842. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
  8843. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  8844. if (!iaxs[fr->callno]) {
  8845. ast_mutex_unlock(&iaxsl[fr->callno]);
  8846. return 1;
  8847. }
  8848. if (authdebug)
  8849. 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);
  8850. } else {
  8851. /* Select an appropriate format */
  8852. if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
  8853. if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
  8854. using_prefs = "reqonly";
  8855. } else {
  8856. using_prefs = "disabled";
  8857. }
  8858. format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
  8859. memset(&pref, 0, sizeof(pref));
  8860. strcpy(caller_pref_buf, "disabled");
  8861. strcpy(host_pref_buf, "disabled");
  8862. } else {
  8863. using_prefs = "mine";
  8864. /* If the information elements are in here... use them */
  8865. if (ies.codec_prefs)
  8866. ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
  8867. if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
  8868. /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
  8869. if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
  8870. pref = iaxs[fr->callno]->rprefs;
  8871. using_prefs = "caller";
  8872. } else {
  8873. pref = iaxs[fr->callno]->prefs;
  8874. }
  8875. } else
  8876. pref = iaxs[fr->callno]->prefs;
  8877. format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
  8878. ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
  8879. ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
  8880. }
  8881. if (!format) {
  8882. if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
  8883. format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
  8884. if (!format) {
  8885. memset(&ied0, 0, sizeof(ied0));
  8886. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
  8887. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  8888. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  8889. if (!iaxs[fr->callno]) {
  8890. ast_mutex_unlock(&iaxsl[fr->callno]);
  8891. return 1;
  8892. }
  8893. if (authdebug) {
  8894. if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
  8895. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
  8896. else
  8897. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
  8898. }
  8899. } else {
  8900. /* Pick one... */
  8901. if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
  8902. if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
  8903. format = 0;
  8904. } else {
  8905. if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
  8906. using_prefs = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
  8907. memset(&pref, 0, sizeof(pref));
  8908. format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
  8909. strcpy(caller_pref_buf,"disabled");
  8910. strcpy(host_pref_buf,"disabled");
  8911. } else {
  8912. using_prefs = "mine";
  8913. if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
  8914. /* Do the opposite of what we tried above. */
  8915. if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
  8916. pref = iaxs[fr->callno]->prefs;
  8917. } else {
  8918. pref = iaxs[fr->callno]->rprefs;
  8919. using_prefs = "caller";
  8920. }
  8921. format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
  8922. } else /* if no codec_prefs IE do it the old way */
  8923. format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
  8924. }
  8925. }
  8926. if (!format) {
  8927. memset(&ied0, 0, sizeof(ied0));
  8928. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
  8929. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  8930. ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
  8931. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  8932. if (!iaxs[fr->callno]) {
  8933. ast_mutex_unlock(&iaxsl[fr->callno]);
  8934. return 1;
  8935. }
  8936. if (authdebug)
  8937. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
  8938. ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
  8939. break;
  8940. }
  8941. }
  8942. }
  8943. if (format) {
  8944. /* No authentication required, let them in */
  8945. memset(&ied1, 0, sizeof(ied1));
  8946. iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
  8947. send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
  8948. if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
  8949. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
  8950. ast_verb(3, "Accepting UNAUTHENTICATED call from %s:\n"
  8951. "%srequested format = %s,\n"
  8952. "%srequested prefs = %s,\n"
  8953. "%sactual format = %s,\n"
  8954. "%shost prefs = %s,\n"
  8955. "%spriority = %s\n",
  8956. ast_inet_ntoa(sin.sin_addr),
  8957. VERBOSE_PREFIX_4,
  8958. ast_getformatname(iaxs[fr->callno]->peerformat),
  8959. VERBOSE_PREFIX_4,
  8960. caller_pref_buf,
  8961. VERBOSE_PREFIX_4,
  8962. ast_getformatname(format),
  8963. VERBOSE_PREFIX_4,
  8964. host_pref_buf,
  8965. VERBOSE_PREFIX_4,
  8966. using_prefs);
  8967. iaxs[fr->callno]->chosenformat = format;
  8968. ast_set_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
  8969. } else {
  8970. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
  8971. /* If this is a TBD call, we're ready but now what... */
  8972. ast_verb(3, "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
  8973. }
  8974. }
  8975. }
  8976. break;
  8977. }
  8978. if (iaxs[fr->callno]->authmethods & IAX_AUTH_MD5)
  8979. merge_encryption(iaxs[fr->callno],ies.encmethods);
  8980. else
  8981. iaxs[fr->callno]->encmethods = 0;
  8982. if (!authenticate_request(fr->callno) && iaxs[fr->callno])
  8983. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED);
  8984. if (!iaxs[fr->callno]) {
  8985. ast_mutex_unlock(&iaxsl[fr->callno]);
  8986. return 1;
  8987. }
  8988. break;
  8989. case IAX_COMMAND_DPREQ:
  8990. /* Request status in the dialplan */
  8991. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
  8992. !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
  8993. if (iaxcompat) {
  8994. /* Spawn a thread for the lookup */
  8995. spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
  8996. } else {
  8997. /* Just look it up */
  8998. dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
  8999. }
  9000. }
  9001. break;
  9002. case IAX_COMMAND_HANGUP:
  9003. ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
  9004. ast_debug(1, "Immediately destroying %d, having received hangup\n", fr->callno);
  9005. /* Set hangup cause according to remote */
  9006. if (ies.causecode && iaxs[fr->callno]->owner)
  9007. iaxs[fr->callno]->owner->hangupcause = ies.causecode;
  9008. /* Send ack immediately, before we destroy */
  9009. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  9010. iax2_destroy(fr->callno);
  9011. break;
  9012. case IAX_COMMAND_REJECT:
  9013. /* Set hangup cause according to remote */
  9014. if (ies.causecode && iaxs[fr->callno]->owner)
  9015. iaxs[fr->callno]->owner->hangupcause = ies.causecode;
  9016. if (!ast_test_flag(iaxs[fr->callno], IAX_PROVISION)) {
  9017. if (iaxs[fr->callno]->owner && authdebug)
  9018. ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
  9019. ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr),
  9020. ies.cause ? ies.cause : "<Unknown>");
  9021. ast_debug(1, "Immediately destroying %d, having received reject\n",
  9022. fr->callno);
  9023. }
  9024. /* Send ack immediately, before we destroy */
  9025. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK,
  9026. fr->ts, NULL, 0, fr->iseqno);
  9027. if (!ast_test_flag(iaxs[fr->callno], IAX_PROVISION))
  9028. iaxs[fr->callno]->error = EPERM;
  9029. iax2_destroy(fr->callno);
  9030. break;
  9031. case IAX_COMMAND_TRANSFER:
  9032. {
  9033. struct ast_channel *bridged_chan;
  9034. if (iaxs[fr->callno]->owner && (bridged_chan = ast_bridged_channel(iaxs[fr->callno]->owner)) && ies.called_number) {
  9035. /* Set BLINDTRANSFER channel variables */
  9036. ast_mutex_unlock(&iaxsl[fr->callno]);
  9037. pbx_builtin_setvar_helper(iaxs[fr->callno]->owner, "BLINDTRANSFER", bridged_chan->name);
  9038. ast_mutex_lock(&iaxsl[fr->callno]);
  9039. if (!iaxs[fr->callno]) {
  9040. ast_mutex_unlock(&iaxsl[fr->callno]);
  9041. return 1;
  9042. }
  9043. pbx_builtin_setvar_helper(bridged_chan, "BLINDTRANSFER", iaxs[fr->callno]->owner->name);
  9044. if (!strcmp(ies.called_number, ast_parking_ext())) {
  9045. struct ast_channel *saved_channel = iaxs[fr->callno]->owner;
  9046. ast_mutex_unlock(&iaxsl[fr->callno]);
  9047. if (iax_park(bridged_chan, saved_channel)) {
  9048. ast_log(LOG_WARNING, "Failed to park call on '%s'\n", bridged_chan->name);
  9049. } else {
  9050. ast_debug(1, "Parked call on '%s'\n", ast_bridged_channel(iaxs[fr->callno]->owner)->name);
  9051. }
  9052. ast_mutex_lock(&iaxsl[fr->callno]);
  9053. } else {
  9054. if (ast_async_goto(bridged_chan, iaxs[fr->callno]->context, ies.called_number, 1))
  9055. ast_log(LOG_WARNING, "Async goto of '%s' to '%s@%s' failed\n", bridged_chan->name,
  9056. ies.called_number, iaxs[fr->callno]->context);
  9057. else {
  9058. ast_debug(1, "Async goto of '%s' to '%s@%s' started\n", bridged_chan->name,
  9059. ies.called_number, iaxs[fr->callno]->context);
  9060. }
  9061. }
  9062. } else {
  9063. ast_debug(1, "Async goto not applicable on call %d\n", fr->callno);
  9064. }
  9065. break;
  9066. }
  9067. case IAX_COMMAND_ACCEPT:
  9068. /* Ignore if call is already up or needs authentication or is a TBD */
  9069. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD | IAX_STATE_AUTHENTICATED))
  9070. break;
  9071. if (ast_test_flag(iaxs[fr->callno], IAX_PROVISION)) {
  9072. /* Send ack immediately, before we destroy */
  9073. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  9074. iax2_destroy(fr->callno);
  9075. break;
  9076. }
  9077. if (ies.format) {
  9078. iaxs[fr->callno]->peerformat = ies.format;
  9079. } else {
  9080. if (iaxs[fr->callno]->owner)
  9081. iaxs[fr->callno]->peerformat = iaxs[fr->callno]->owner->nativeformats;
  9082. else
  9083. iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
  9084. }
  9085. ast_verb(3, "Call accepted by %s (format %s)\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), ast_getformatname(iaxs[fr->callno]->peerformat));
  9086. if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
  9087. memset(&ied0, 0, sizeof(ied0));
  9088. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
  9089. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  9090. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  9091. if (!iaxs[fr->callno]) {
  9092. ast_mutex_unlock(&iaxsl[fr->callno]);
  9093. return 1;
  9094. }
  9095. if (authdebug)
  9096. ast_log(LOG_NOTICE, "Rejected call to %s, format 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
  9097. } else {
  9098. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
  9099. if (iaxs[fr->callno]->owner) {
  9100. /* Switch us to use a compatible format */
  9101. iaxs[fr->callno]->owner->nativeformats = iaxs[fr->callno]->peerformat;
  9102. ast_verb(3, "Format for call is %s\n", ast_getformatname(iaxs[fr->callno]->owner->nativeformats));
  9103. retryowner2:
  9104. if (ast_channel_trylock(iaxs[fr->callno]->owner)) {
  9105. DEADLOCK_AVOIDANCE(&iaxsl[fr->callno]);
  9106. if (iaxs[fr->callno] && iaxs[fr->callno]->owner) goto retryowner2;
  9107. }
  9108. if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
  9109. /* Setup read/write formats properly. */
  9110. if (iaxs[fr->callno]->owner->writeformat)
  9111. ast_set_write_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->writeformat);
  9112. if (iaxs[fr->callno]->owner->readformat)
  9113. ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
  9114. ast_channel_unlock(iaxs[fr->callno]->owner);
  9115. }
  9116. }
  9117. }
  9118. if (iaxs[fr->callno]) {
  9119. AST_LIST_LOCK(&dpcache);
  9120. AST_LIST_TRAVERSE(&iaxs[fr->callno]->dpentries, dp, peer_list)
  9121. if (!(dp->flags & CACHE_FLAG_TRANSMITTED))
  9122. iax2_dprequest(dp, fr->callno);
  9123. AST_LIST_UNLOCK(&dpcache);
  9124. }
  9125. break;
  9126. case IAX_COMMAND_POKE:
  9127. /* Send back a pong packet with the original timestamp */
  9128. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
  9129. if (!iaxs[fr->callno]) {
  9130. ast_mutex_unlock(&iaxsl[fr->callno]);
  9131. return 1;
  9132. }
  9133. break;
  9134. case IAX_COMMAND_PING:
  9135. {
  9136. struct iax_ie_data pingied;
  9137. construct_rr(iaxs[fr->callno], &pingied);
  9138. /* Send back a pong packet with the original timestamp */
  9139. send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
  9140. }
  9141. break;
  9142. case IAX_COMMAND_PONG:
  9143. /* Calculate ping time */
  9144. iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
  9145. /* save RR info */
  9146. save_rr(fr, &ies);
  9147. /* Good time to write jb stats for this call */
  9148. log_jitterstats(fr->callno);
  9149. if (iaxs[fr->callno]->peerpoke) {
  9150. peer = iaxs[fr->callno]->peerpoke;
  9151. if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
  9152. if (iaxs[fr->callno]->pingtime <= peer->maxms) {
  9153. ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %d\n", peer->name, iaxs[fr->callno]->pingtime);
  9154. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime);
  9155. ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
  9156. }
  9157. } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
  9158. if (iaxs[fr->callno]->pingtime > peer->maxms) {
  9159. ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
  9160. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime);
  9161. ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
  9162. }
  9163. }
  9164. peer->lastms = iaxs[fr->callno]->pingtime;
  9165. if (peer->smoothing && (peer->lastms > -1))
  9166. peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
  9167. else if (peer->smoothing && peer->lastms < 0)
  9168. peer->historicms = (0 + peer->historicms) / 2;
  9169. else
  9170. peer->historicms = iaxs[fr->callno]->pingtime;
  9171. /* Remove scheduled iax2_poke_noanswer */
  9172. if (peer->pokeexpire > -1) {
  9173. if (!ast_sched_del(sched, peer->pokeexpire)) {
  9174. peer_unref(peer);
  9175. peer->pokeexpire = -1;
  9176. }
  9177. }
  9178. /* Schedule the next cycle */
  9179. if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
  9180. peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
  9181. else
  9182. peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
  9183. if (peer->pokeexpire == -1)
  9184. peer_unref(peer);
  9185. /* and finally send the ack */
  9186. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  9187. /* And wrap up the qualify call */
  9188. iax2_destroy(fr->callno);
  9189. peer->callno = 0;
  9190. ast_debug(1, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
  9191. }
  9192. break;
  9193. case IAX_COMMAND_LAGRQ:
  9194. case IAX_COMMAND_LAGRP:
  9195. f.src = "LAGRQ";
  9196. f.mallocd = 0;
  9197. f.offset = 0;
  9198. f.samples = 0;
  9199. iax_frame_wrap(fr, &f);
  9200. if(f.subclass == IAX_COMMAND_LAGRQ) {
  9201. /* Received a LAGRQ - echo back a LAGRP */
  9202. fr->af.subclass = IAX_COMMAND_LAGRP;
  9203. iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
  9204. } else {
  9205. /* Received LAGRP in response to our LAGRQ */
  9206. unsigned int ts;
  9207. /* This is a reply we've been given, actually measure the difference */
  9208. ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
  9209. iaxs[fr->callno]->lag = ts - fr->ts;
  9210. if (iaxdebug)
  9211. ast_debug(1, "Peer %s lag measured as %dms\n",
  9212. ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->lag);
  9213. }
  9214. break;
  9215. case IAX_COMMAND_AUTHREQ:
  9216. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
  9217. ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
  9218. break;
  9219. }
  9220. if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
  9221. struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
  9222. .subclass = AST_CONTROL_HANGUP,
  9223. };
  9224. ast_log(LOG_WARNING,
  9225. "I don't know how to authenticate %s to %s\n",
  9226. ies.username ? ies.username : "<unknown>", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr));
  9227. iax2_queue_frame(fr->callno, &hangup_fr);
  9228. }
  9229. if (!iaxs[fr->callno]) {
  9230. ast_mutex_unlock(&iaxsl[fr->callno]);
  9231. return 1;
  9232. }
  9233. break;
  9234. case IAX_COMMAND_AUTHREP:
  9235. /* For security, always ack immediately */
  9236. if (delayreject)
  9237. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  9238. /* Ignore once we've started */
  9239. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
  9240. ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
  9241. break;
  9242. }
  9243. if (authenticate_verify(iaxs[fr->callno], &ies)) {
  9244. if (authdebug)
  9245. 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);
  9246. memset(&ied0, 0, sizeof(ied0));
  9247. auth_fail(fr->callno, IAX_COMMAND_REJECT);
  9248. break;
  9249. }
  9250. if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
  9251. /* This might re-enter the IAX code and need the lock */
  9252. exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
  9253. } else
  9254. exists = 0;
  9255. if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
  9256. if (authdebug)
  9257. 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);
  9258. memset(&ied0, 0, sizeof(ied0));
  9259. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
  9260. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
  9261. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  9262. if (!iaxs[fr->callno]) {
  9263. ast_mutex_unlock(&iaxsl[fr->callno]);
  9264. return 1;
  9265. }
  9266. } else {
  9267. /* Select an appropriate format */
  9268. if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
  9269. if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
  9270. using_prefs = "reqonly";
  9271. } else {
  9272. using_prefs = "disabled";
  9273. }
  9274. format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
  9275. memset(&pref, 0, sizeof(pref));
  9276. strcpy(caller_pref_buf, "disabled");
  9277. strcpy(host_pref_buf, "disabled");
  9278. } else {
  9279. using_prefs = "mine";
  9280. if (ies.codec_prefs)
  9281. ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
  9282. if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
  9283. if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
  9284. pref = iaxs[fr->callno]->rprefs;
  9285. using_prefs = "caller";
  9286. } else {
  9287. pref = iaxs[fr->callno]->prefs;
  9288. }
  9289. } else /* if no codec_prefs IE do it the old way */
  9290. pref = iaxs[fr->callno]->prefs;
  9291. format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
  9292. ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
  9293. ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
  9294. }
  9295. if (!format) {
  9296. if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
  9297. ast_debug(1, "We don't do requested format %s, falling back to peer capability %d\n", ast_getformatname(iaxs[fr->callno]->peerformat), iaxs[fr->callno]->peercapability);
  9298. format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
  9299. }
  9300. if (!format) {
  9301. if (authdebug) {
  9302. if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
  9303. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
  9304. else
  9305. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
  9306. }
  9307. memset(&ied0, 0, sizeof(ied0));
  9308. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
  9309. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  9310. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  9311. if (!iaxs[fr->callno]) {
  9312. ast_mutex_unlock(&iaxsl[fr->callno]);
  9313. return 1;
  9314. }
  9315. } else {
  9316. /* Pick one... */
  9317. if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
  9318. if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
  9319. format = 0;
  9320. } else {
  9321. if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
  9322. using_prefs = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
  9323. memset(&pref, 0, sizeof(pref));
  9324. format = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ?
  9325. iaxs[fr->callno]->peerformat : ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
  9326. strcpy(caller_pref_buf,"disabled");
  9327. strcpy(host_pref_buf,"disabled");
  9328. } else {
  9329. using_prefs = "mine";
  9330. if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
  9331. /* Do the opposite of what we tried above. */
  9332. if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
  9333. pref = iaxs[fr->callno]->prefs;
  9334. } else {
  9335. pref = iaxs[fr->callno]->rprefs;
  9336. using_prefs = "caller";
  9337. }
  9338. format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
  9339. } else /* if no codec_prefs IE do it the old way */
  9340. format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
  9341. }
  9342. }
  9343. if (!format) {
  9344. ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
  9345. if (authdebug) {
  9346. if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
  9347. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
  9348. else
  9349. ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
  9350. }
  9351. memset(&ied0, 0, sizeof(ied0));
  9352. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
  9353. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  9354. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  9355. if (!iaxs[fr->callno]) {
  9356. ast_mutex_unlock(&iaxsl[fr->callno]);
  9357. return 1;
  9358. }
  9359. }
  9360. }
  9361. }
  9362. if (format) {
  9363. /* Authentication received */
  9364. memset(&ied1, 0, sizeof(ied1));
  9365. iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
  9366. send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
  9367. if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
  9368. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
  9369. ast_verb(3, "Accepting AUTHENTICATED call from %s:\n"
  9370. "%srequested format = %s,\n"
  9371. "%srequested prefs = %s,\n"
  9372. "%sactual format = %s,\n"
  9373. "%shost prefs = %s,\n"
  9374. "%spriority = %s\n",
  9375. ast_inet_ntoa(sin.sin_addr),
  9376. VERBOSE_PREFIX_4,
  9377. ast_getformatname(iaxs[fr->callno]->peerformat),
  9378. VERBOSE_PREFIX_4,
  9379. caller_pref_buf,
  9380. VERBOSE_PREFIX_4,
  9381. ast_getformatname(format),
  9382. VERBOSE_PREFIX_4,
  9383. host_pref_buf,
  9384. VERBOSE_PREFIX_4,
  9385. using_prefs);
  9386. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
  9387. if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, format)))
  9388. iax2_destroy(fr->callno);
  9389. else if (ies.vars) {
  9390. struct ast_datastore *variablestore;
  9391. struct ast_variable *var, *prev = NULL;
  9392. AST_LIST_HEAD(, ast_var_t) *varlist;
  9393. varlist = ast_calloc(1, sizeof(*varlist));
  9394. variablestore = ast_channel_datastore_alloc(&iax2_variable_datastore_info, NULL);
  9395. if (variablestore && varlist) {
  9396. variablestore->data = varlist;
  9397. variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
  9398. AST_LIST_HEAD_INIT(varlist);
  9399. ast_debug(1, "I can haz IAX vars? w00t\n");
  9400. for (var = ies.vars; var; var = var->next) {
  9401. struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
  9402. if (prev)
  9403. ast_free(prev);
  9404. prev = var;
  9405. if (!newvar) {
  9406. /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
  9407. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  9408. } else {
  9409. AST_LIST_INSERT_TAIL(varlist, newvar, entries);
  9410. }
  9411. }
  9412. if (prev)
  9413. ast_free(prev);
  9414. ies.vars = NULL;
  9415. ast_channel_datastore_add(c, variablestore);
  9416. } else {
  9417. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  9418. if (variablestore)
  9419. ast_channel_datastore_free(variablestore);
  9420. if (varlist)
  9421. ast_free(varlist);
  9422. }
  9423. }
  9424. } else {
  9425. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
  9426. /* If this is a TBD call, we're ready but now what... */
  9427. ast_verb(3, "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
  9428. }
  9429. }
  9430. }
  9431. break;
  9432. case IAX_COMMAND_DIAL:
  9433. if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
  9434. ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
  9435. ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
  9436. if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
  9437. if (authdebug)
  9438. 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);
  9439. memset(&ied0, 0, sizeof(ied0));
  9440. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
  9441. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
  9442. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  9443. if (!iaxs[fr->callno]) {
  9444. ast_mutex_unlock(&iaxsl[fr->callno]);
  9445. return 1;
  9446. }
  9447. } else {
  9448. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
  9449. ast_verb(3, "Accepting DIAL from %s, formats = 0x%x\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat);
  9450. ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
  9451. send_command(iaxs[fr->callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
  9452. if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->peerformat)))
  9453. iax2_destroy(fr->callno);
  9454. else if (ies.vars) {
  9455. struct ast_datastore *variablestore;
  9456. struct ast_variable *var, *prev = NULL;
  9457. AST_LIST_HEAD(, ast_var_t) *varlist;
  9458. varlist = ast_calloc(1, sizeof(*varlist));
  9459. variablestore = ast_channel_datastore_alloc(&iax2_variable_datastore_info, NULL);
  9460. if (variablestore && varlist) {
  9461. variablestore->data = varlist;
  9462. variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
  9463. AST_LIST_HEAD_INIT(varlist);
  9464. for (var = ies.vars; var; var = var->next) {
  9465. struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
  9466. if (prev)
  9467. ast_free(prev);
  9468. prev = var;
  9469. if (!newvar) {
  9470. /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
  9471. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  9472. } else {
  9473. AST_LIST_INSERT_TAIL(varlist, newvar, entries);
  9474. }
  9475. }
  9476. if (prev)
  9477. ast_free(prev);
  9478. ies.vars = NULL;
  9479. ast_channel_datastore_add(c, variablestore);
  9480. } else {
  9481. ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
  9482. if (variablestore)
  9483. ast_channel_datastore_free(variablestore);
  9484. if (varlist)
  9485. ast_free(varlist);
  9486. }
  9487. }
  9488. }
  9489. }
  9490. break;
  9491. case IAX_COMMAND_INVAL:
  9492. iaxs[fr->callno]->error = ENOTCONN;
  9493. ast_debug(1, "Immediately destroying %d, having received INVAL\n", fr->callno);
  9494. iax2_destroy(fr->callno);
  9495. ast_debug(1, "Destroying call %d\n", fr->callno);
  9496. break;
  9497. case IAX_COMMAND_VNAK:
  9498. ast_debug(1, "Received VNAK: resending outstanding frames\n");
  9499. /* Force retransmission */
  9500. vnak_retransmit(fr->callno, fr->iseqno);
  9501. break;
  9502. case IAX_COMMAND_REGREQ:
  9503. case IAX_COMMAND_REGREL:
  9504. /* For security, always ack immediately */
  9505. if (delayreject)
  9506. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  9507. if (register_verify(fr->callno, &sin, &ies)) {
  9508. if (!iaxs[fr->callno]) {
  9509. ast_mutex_unlock(&iaxsl[fr->callno]);
  9510. return 1;
  9511. }
  9512. /* Send delayed failure */
  9513. auth_fail(fr->callno, IAX_COMMAND_REGREJ);
  9514. break;
  9515. }
  9516. if (!iaxs[fr->callno]) {
  9517. ast_mutex_unlock(&iaxsl[fr->callno]);
  9518. return 1;
  9519. }
  9520. if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
  9521. ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED)) {
  9522. if (f.subclass == IAX_COMMAND_REGREL)
  9523. memset(&sin, 0, sizeof(sin));
  9524. if (update_registry(&sin, fr->callno, ies.devicetype, fd, ies.refresh))
  9525. ast_log(LOG_WARNING, "Registry error\n");
  9526. if (!iaxs[fr->callno]) {
  9527. ast_mutex_unlock(&iaxsl[fr->callno]);
  9528. return 1;
  9529. }
  9530. if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
  9531. ast_mutex_unlock(&iaxsl[fr->callno]);
  9532. check_provisioning(&sin, fd, ies.serviceident, ies.provver);
  9533. ast_mutex_lock(&iaxsl[fr->callno]);
  9534. if (!iaxs[fr->callno]) {
  9535. ast_mutex_unlock(&iaxsl[fr->callno]);
  9536. return 1;
  9537. }
  9538. }
  9539. break;
  9540. }
  9541. registry_authrequest(fr->callno);
  9542. if (!iaxs[fr->callno]) {
  9543. ast_mutex_unlock(&iaxsl[fr->callno]);
  9544. return 1;
  9545. }
  9546. break;
  9547. case IAX_COMMAND_REGACK:
  9548. if (iax2_ack_registry(&ies, &sin, fr->callno))
  9549. ast_log(LOG_WARNING, "Registration failure\n");
  9550. /* Send ack immediately, before we destroy */
  9551. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  9552. iax2_destroy(fr->callno);
  9553. break;
  9554. case IAX_COMMAND_REGREJ:
  9555. if (iaxs[fr->callno]->reg) {
  9556. if (authdebug) {
  9557. 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));
  9558. 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>");
  9559. }
  9560. iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
  9561. }
  9562. /* Send ack immediately, before we destroy */
  9563. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  9564. iax2_destroy(fr->callno);
  9565. break;
  9566. case IAX_COMMAND_REGAUTH:
  9567. /* Authentication request */
  9568. if (registry_rerequest(&ies, fr->callno, &sin)) {
  9569. memset(&ied0, 0, sizeof(ied0));
  9570. iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
  9571. iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
  9572. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  9573. if (!iaxs[fr->callno]) {
  9574. ast_mutex_unlock(&iaxsl[fr->callno]);
  9575. return 1;
  9576. }
  9577. }
  9578. break;
  9579. case IAX_COMMAND_TXREJ:
  9580. iaxs[fr->callno]->transferring = 0;
  9581. ast_verb(3, "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
  9582. memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
  9583. if (iaxs[fr->callno]->bridgecallno) {
  9584. if (iaxs[iaxs[fr->callno]->bridgecallno]->transferring) {
  9585. iaxs[iaxs[fr->callno]->bridgecallno]->transferring = 0;
  9586. send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
  9587. }
  9588. }
  9589. break;
  9590. case IAX_COMMAND_TXREADY:
  9591. if ((iaxs[fr->callno]->transferring == TRANSFER_BEGIN) ||
  9592. (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)) {
  9593. if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)
  9594. iaxs[fr->callno]->transferring = TRANSFER_MREADY;
  9595. else
  9596. iaxs[fr->callno]->transferring = TRANSFER_READY;
  9597. ast_verb(3, "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
  9598. if (iaxs[fr->callno]->bridgecallno) {
  9599. if ((iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_READY) ||
  9600. (iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_MREADY)) {
  9601. /* They're both ready, now release them. */
  9602. if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
  9603. ast_verb(3, "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
  9604. iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
  9605. iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MEDIA;
  9606. iaxs[fr->callno]->transferring = TRANSFER_MEDIA;
  9607. memset(&ied0, 0, sizeof(ied0));
  9608. memset(&ied1, 0, sizeof(ied1));
  9609. iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
  9610. iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
  9611. send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
  9612. send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
  9613. } else {
  9614. ast_verb(3, "Releasing %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
  9615. iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
  9616. iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
  9617. iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
  9618. ast_set_flag(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
  9619. ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
  9620. /* Stop doing lag & ping requests */
  9621. stop_stuff(fr->callno);
  9622. stop_stuff(iaxs[fr->callno]->bridgecallno);
  9623. memset(&ied0, 0, sizeof(ied0));
  9624. memset(&ied1, 0, sizeof(ied1));
  9625. iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
  9626. iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
  9627. send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
  9628. send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
  9629. }
  9630. }
  9631. }
  9632. }
  9633. break;
  9634. case IAX_COMMAND_TXREQ:
  9635. try_transfer(iaxs[fr->callno], &ies);
  9636. break;
  9637. case IAX_COMMAND_TXCNT:
  9638. if (iaxs[fr->callno]->transferring)
  9639. send_command_transfer(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, NULL, 0);
  9640. break;
  9641. case IAX_COMMAND_TXREL:
  9642. /* Send ack immediately, rather than waiting until we've changed addresses */
  9643. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  9644. complete_transfer(fr->callno, &ies);
  9645. stop_stuff(fr->callno); /* for attended transfer to work with libiax */
  9646. break;
  9647. case IAX_COMMAND_TXMEDIA:
  9648. if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
  9649. AST_LIST_LOCK(&frame_queue);
  9650. AST_LIST_TRAVERSE(&frame_queue, cur, list) {
  9651. /* Cancel any outstanding frames and start anew */
  9652. if ((fr->callno == cur->callno) && (cur->transfer))
  9653. cur->retries = -1;
  9654. }
  9655. AST_LIST_UNLOCK(&frame_queue);
  9656. /* Start sending our media to the transfer address, but otherwise leave the call as-is */
  9657. iaxs[fr->callno]->transferring = TRANSFER_MEDIAPASS;
  9658. }
  9659. break;
  9660. case IAX_COMMAND_DPREP:
  9661. complete_dpreply(iaxs[fr->callno], &ies);
  9662. break;
  9663. case IAX_COMMAND_UNSUPPORT:
  9664. ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
  9665. break;
  9666. case IAX_COMMAND_FWDOWNL:
  9667. /* Firmware download */
  9668. if (!ast_test_flag(&globalflags, IAX_ALLOWFWDOWNLOAD)) {
  9669. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, NULL, 0, -1);
  9670. break;
  9671. }
  9672. memset(&ied0, 0, sizeof(ied0));
  9673. res = iax_firmware_append(&ied0, (unsigned char *)ies.devicetype, ies.fwdesc);
  9674. if (res < 0)
  9675. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
  9676. else if (res > 0)
  9677. send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
  9678. else
  9679. send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
  9680. if (!iaxs[fr->callno]) {
  9681. ast_mutex_unlock(&iaxsl[fr->callno]);
  9682. return 1;
  9683. }
  9684. break;
  9685. case IAX_COMMAND_CALLTOKEN:
  9686. {
  9687. struct iax_frame *cur;
  9688. int found = 0;
  9689. AST_LIST_LOCK(&frame_queue);
  9690. AST_LIST_TRAVERSE(&frame_queue, cur, list) {
  9691. /* find the last sent frame in our frame queue for this callno.
  9692. * There are many things to take into account before resending this frame.
  9693. * All of these are taken care of in resend_with_token() */
  9694. if (cur->callno == fr->callno) {
  9695. found = 1;
  9696. break;
  9697. }
  9698. }
  9699. AST_LIST_UNLOCK(&frame_queue);
  9700. /* find last sent frame */
  9701. if (cur && found && ies.calltoken && ies.calltokendata) {
  9702. resend_with_token(fr->callno, cur, (char *) ies.calltokendata);
  9703. }
  9704. break;
  9705. }
  9706. default:
  9707. ast_debug(1, "Unknown IAX command %d on %d/%d\n", f.subclass, fr->callno, iaxs[fr->callno]->peercallno);
  9708. memset(&ied0, 0, sizeof(ied0));
  9709. iax_ie_append_byte(&ied0, IAX_IE_IAX_UNKNOWN, f.subclass);
  9710. send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
  9711. }
  9712. /* Free remote variables (if any) */
  9713. if (ies.vars) {
  9714. ast_variables_destroy(ies.vars);
  9715. ast_debug(1, "I can haz IAX vars, but they is no good :-(\n");
  9716. ies.vars = NULL;
  9717. }
  9718. /* Don't actually pass these frames along */
  9719. if ((f.subclass != IAX_COMMAND_ACK) &&
  9720. (f.subclass != IAX_COMMAND_TXCNT) &&
  9721. (f.subclass != IAX_COMMAND_TXACC) &&
  9722. (f.subclass != IAX_COMMAND_INVAL) &&
  9723. (f.subclass != IAX_COMMAND_VNAK)) {
  9724. if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
  9725. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  9726. }
  9727. ast_mutex_unlock(&iaxsl[fr->callno]);
  9728. return 1;
  9729. }
  9730. /* Unless this is an ACK or INVAL frame, ack it */
  9731. if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
  9732. send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
  9733. } else if (minivid) {
  9734. f.frametype = AST_FRAME_VIDEO;
  9735. if (iaxs[fr->callno]->videoformat > 0)
  9736. f.subclass = iaxs[fr->callno]->videoformat | (ntohs(vh->ts) & 0x8000 ? 1 : 0);
  9737. else {
  9738. ast_log(LOG_WARNING, "Received mini frame before first full video frame\n");
  9739. iax2_vnak(fr->callno);
  9740. ast_mutex_unlock(&iaxsl[fr->callno]);
  9741. return 1;
  9742. }
  9743. f.datalen = res - sizeof(*vh);
  9744. if (f.datalen)
  9745. f.data = thread->buf + sizeof(*vh);
  9746. else
  9747. f.data = NULL;
  9748. #ifdef IAXTESTS
  9749. if (test_resync) {
  9750. fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
  9751. } else
  9752. #endif /* IAXTESTS */
  9753. fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
  9754. } else {
  9755. /* A mini frame */
  9756. f.frametype = AST_FRAME_VOICE;
  9757. if (iaxs[fr->callno]->voiceformat > 0)
  9758. f.subclass = iaxs[fr->callno]->voiceformat;
  9759. else {
  9760. ast_debug(1, "Received mini frame before first full voice frame\n");
  9761. iax2_vnak(fr->callno);
  9762. ast_mutex_unlock(&iaxsl[fr->callno]);
  9763. return 1;
  9764. }
  9765. f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
  9766. if (f.datalen < 0) {
  9767. ast_log(LOG_WARNING, "Datalen < 0?\n");
  9768. ast_mutex_unlock(&iaxsl[fr->callno]);
  9769. return 1;
  9770. }
  9771. if (f.datalen)
  9772. f.data = thread->buf + sizeof(*mh);
  9773. else
  9774. f.data = NULL;
  9775. #ifdef IAXTESTS
  9776. if (test_resync) {
  9777. fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
  9778. } else
  9779. #endif /* IAXTESTS */
  9780. fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
  9781. /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
  9782. }
  9783. /* Don't pass any packets until we're started */
  9784. if (!ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
  9785. ast_mutex_unlock(&iaxsl[fr->callno]);
  9786. return 1;
  9787. }
  9788. /* Common things */
  9789. f.src = "IAX2";
  9790. f.mallocd = 0;
  9791. f.offset = 0;
  9792. f.len = 0;
  9793. if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
  9794. f.samples = ast_codec_get_samples(&f);
  9795. /* We need to byteswap incoming slinear samples from network byte order */
  9796. if (f.subclass == AST_FORMAT_SLINEAR)
  9797. ast_frame_byteswap_be(&f);
  9798. } else
  9799. f.samples = 0;
  9800. iax_frame_wrap(fr, &f);
  9801. /* If this is our most recent packet, use it as our basis for timestamping */
  9802. if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
  9803. /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
  9804. fr->outoforder = 0;
  9805. } else {
  9806. if (iaxdebug && iaxs[fr->callno])
  9807. ast_debug(1, "Received out of order packet... (type=%d, subclass %d, ts = %d, last = %d)\n", f.frametype, f.subclass, fr->ts, iaxs[fr->callno]->last);
  9808. fr->outoforder = -1;
  9809. }
  9810. fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
  9811. duped_fr = iaxfrdup2(fr);
  9812. if (duped_fr) {
  9813. schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
  9814. }
  9815. if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
  9816. iaxs[fr->callno]->last = fr->ts;
  9817. #if 1
  9818. if (iaxdebug)
  9819. ast_debug(1, "For call=%d, set last=%d\n", fr->callno, fr->ts);
  9820. #endif
  9821. }
  9822. /* Always run again */
  9823. ast_mutex_unlock(&iaxsl[fr->callno]);
  9824. return 1;
  9825. }
  9826. /* Function to clean up process thread if it is cancelled */
  9827. static void iax2_process_thread_cleanup(void *data)
  9828. {
  9829. struct iax2_thread *thread = data;
  9830. ast_mutex_destroy(&thread->lock);
  9831. ast_cond_destroy(&thread->cond);
  9832. ast_free(thread);
  9833. ast_atomic_dec_and_test(&iaxactivethreadcount);
  9834. }
  9835. static void *iax2_process_thread(void *data)
  9836. {
  9837. struct iax2_thread *thread = data;
  9838. struct timeval tv;
  9839. struct timespec ts;
  9840. int put_into_idle = 0;
  9841. ast_atomic_fetchadd_int(&iaxactivethreadcount,1);
  9842. pthread_cleanup_push(iax2_process_thread_cleanup, data);
  9843. for(;;) {
  9844. /* Wait for something to signal us to be awake */
  9845. ast_mutex_lock(&thread->lock);
  9846. /* Flag that we're ready to accept signals */
  9847. thread->ready_for_signal = 1;
  9848. /* Put into idle list if applicable */
  9849. if (put_into_idle)
  9850. insert_idle_thread(thread);
  9851. if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
  9852. struct iax2_thread *t = NULL;
  9853. /* Wait to be signalled or time out */
  9854. tv = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
  9855. ts.tv_sec = tv.tv_sec;
  9856. ts.tv_nsec = tv.tv_usec * 1000;
  9857. if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
  9858. /* This thread was never put back into the available dynamic
  9859. * thread list, so just go away. */
  9860. if (!put_into_idle) {
  9861. ast_mutex_unlock(&thread->lock);
  9862. break;
  9863. }
  9864. AST_LIST_LOCK(&dynamic_list);
  9865. /* Account for the case where this thread is acquired *right* after a timeout */
  9866. if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
  9867. ast_atomic_fetchadd_int(&iaxdynamicthreadcount, -1);
  9868. AST_LIST_UNLOCK(&dynamic_list);
  9869. if (t) {
  9870. /* This dynamic thread timed out waiting for a task and was
  9871. * not acquired immediately after the timeout,
  9872. * so it's time to go away. */
  9873. ast_mutex_unlock(&thread->lock);
  9874. break;
  9875. }
  9876. /* Someone grabbed our thread *right* after we timed out.
  9877. * Wait for them to set us up with something to do and signal
  9878. * us to continue. */
  9879. tv = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
  9880. ts.tv_sec = tv.tv_sec;
  9881. ts.tv_nsec = tv.tv_usec * 1000;
  9882. if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT)
  9883. {
  9884. ast_mutex_unlock(&thread->lock);
  9885. break;
  9886. }
  9887. }
  9888. } else {
  9889. ast_cond_wait(&thread->cond, &thread->lock);
  9890. }
  9891. /* Go back into our respective list */
  9892. put_into_idle = 1;
  9893. ast_mutex_unlock(&thread->lock);
  9894. if (thread->iostate == IAX_IOSTATE_IDLE)
  9895. continue;
  9896. /* Add ourselves to the active list now */
  9897. AST_LIST_LOCK(&active_list);
  9898. AST_LIST_INSERT_HEAD(&active_list, thread, list);
  9899. AST_LIST_UNLOCK(&active_list);
  9900. /* See what we need to do */
  9901. switch(thread->iostate) {
  9902. case IAX_IOSTATE_READY:
  9903. thread->actions++;
  9904. thread->iostate = IAX_IOSTATE_PROCESSING;
  9905. socket_process(thread);
  9906. handle_deferred_full_frames(thread);
  9907. break;
  9908. case IAX_IOSTATE_SCHEDREADY:
  9909. thread->actions++;
  9910. thread->iostate = IAX_IOSTATE_PROCESSING;
  9911. #ifdef SCHED_MULTITHREADED
  9912. thread->schedfunc(thread->scheddata);
  9913. #endif
  9914. default:
  9915. break;
  9916. }
  9917. time(&thread->checktime);
  9918. thread->iostate = IAX_IOSTATE_IDLE;
  9919. #ifdef DEBUG_SCHED_MULTITHREAD
  9920. thread->curfunc[0]='\0';
  9921. #endif
  9922. /* Now... remove ourselves from the active list, and return to the idle list */
  9923. AST_LIST_LOCK(&active_list);
  9924. AST_LIST_REMOVE(&active_list, thread, list);
  9925. AST_LIST_UNLOCK(&active_list);
  9926. /* Make sure another frame didn't sneak in there after we thought we were done. */
  9927. handle_deferred_full_frames(thread);
  9928. }
  9929. /*!\note For some reason, idle threads are exiting without being removed
  9930. * from an idle list, which is causing memory corruption. Forcibly remove
  9931. * it from the list, if it's there.
  9932. */
  9933. AST_LIST_LOCK(&idle_list);
  9934. AST_LIST_REMOVE(&idle_list, thread, list);
  9935. AST_LIST_UNLOCK(&idle_list);
  9936. AST_LIST_LOCK(&dynamic_list);
  9937. AST_LIST_REMOVE(&dynamic_list, thread, list);
  9938. AST_LIST_UNLOCK(&dynamic_list);
  9939. /* I am exiting here on my own volition, I need to clean up my own data structures
  9940. * Assume that I am no longer in any of the lists (idle, active, or dynamic)
  9941. */
  9942. pthread_cleanup_pop(1);
  9943. return NULL;
  9944. }
  9945. static int iax2_do_register(struct iax2_registry *reg)
  9946. {
  9947. struct iax_ie_data ied;
  9948. if (iaxdebug)
  9949. ast_debug(1, "Sending registration request for '%s'\n", reg->username);
  9950. if (reg->dnsmgr &&
  9951. ((reg->regstate == REG_STATE_TIMEOUT) || !reg->addr.sin_addr.s_addr)) {
  9952. /* Maybe the IP has changed, force DNS refresh */
  9953. ast_dnsmgr_refresh(reg->dnsmgr);
  9954. }
  9955. /*
  9956. * if IP has Changed, free allocated call to create a new one with new IP
  9957. * call has the pointer to IP and must be updated to the new one
  9958. */
  9959. if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
  9960. int callno = reg->callno;
  9961. ast_mutex_lock(&iaxsl[callno]);
  9962. iax2_destroy(callno);
  9963. ast_mutex_unlock(&iaxsl[callno]);
  9964. reg->callno = 0;
  9965. }
  9966. if (!reg->addr.sin_addr.s_addr) {
  9967. if (iaxdebug)
  9968. ast_debug(1, "Unable to send registration request for '%s' without IP address\n", reg->username);
  9969. /* Setup the next registration attempt */
  9970. reg->expire = iax2_sched_replace(reg->expire, sched,
  9971. (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
  9972. return -1;
  9973. }
  9974. if (!reg->callno) {
  9975. ast_debug(3, "Allocate call number\n");
  9976. reg->callno = find_callno_locked(0, 0, &reg->addr, NEW_FORCE, defaultsockfd, 0);
  9977. if (reg->callno < 1) {
  9978. ast_log(LOG_WARNING, "Unable to create call for registration\n");
  9979. return -1;
  9980. } else
  9981. ast_debug(3, "Registration created on call %d\n", reg->callno);
  9982. iaxs[reg->callno]->reg = reg;
  9983. ast_mutex_unlock(&iaxsl[reg->callno]);
  9984. }
  9985. /* Setup the next registration a little early */
  9986. reg->expire = iax2_sched_replace(reg->expire, sched,
  9987. (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
  9988. /* Send the request */
  9989. memset(&ied, 0, sizeof(ied));
  9990. iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
  9991. iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
  9992. add_empty_calltoken_ie(iaxs[reg->callno], &ied); /* this _MUST_ be the last ie added */
  9993. send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
  9994. reg->regstate = REG_STATE_REGSENT;
  9995. return 0;
  9996. }
  9997. static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force)
  9998. {
  9999. /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
  10000. is found for template */
  10001. struct iax_ie_data provdata;
  10002. struct iax_ie_data ied;
  10003. unsigned int sig;
  10004. struct sockaddr_in sin;
  10005. int callno;
  10006. struct create_addr_info cai;
  10007. memset(&cai, 0, sizeof(cai));
  10008. ast_debug(1, "Provisioning '%s' from template '%s'\n", dest, template);
  10009. if (iax_provision_build(&provdata, &sig, template, force)) {
  10010. ast_debug(1, "No provisioning found for template '%s'\n", template);
  10011. return 0;
  10012. }
  10013. if (end) {
  10014. memcpy(&sin, end, sizeof(sin));
  10015. cai.sockfd = sockfd;
  10016. } else if (create_addr(dest, NULL, &sin, &cai))
  10017. return -1;
  10018. /* Build the rest of the message */
  10019. memset(&ied, 0, sizeof(ied));
  10020. iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
  10021. callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
  10022. if (!callno)
  10023. return -1;
  10024. if (iaxs[callno]) {
  10025. /* Schedule autodestruct in case they don't ever give us anything back */
  10026. iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
  10027. sched, 15000, auto_hangup, (void *)(long)callno);
  10028. ast_set_flag(iaxs[callno], IAX_PROVISION);
  10029. /* Got a call number now, so go ahead and send the provisioning information */
  10030. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
  10031. }
  10032. ast_mutex_unlock(&iaxsl[callno]);
  10033. return 1;
  10034. }
  10035. static char *papp = "IAX2Provision";
  10036. static char *psyn = "Provision a calling IAXy with a given template";
  10037. static char *pdescrip =
  10038. " IAX2Provision([template]): Provisions the calling IAXy (assuming\n"
  10039. "the calling entity is in fact an IAXy) with the given template or\n"
  10040. "default if one is not specified. Returns -1 on error or 0 on success.\n";
  10041. /*! iax2provision
  10042. \ingroup applications
  10043. */
  10044. static int iax2_prov_app(struct ast_channel *chan, void *data)
  10045. {
  10046. int res;
  10047. char *sdata;
  10048. char *opts;
  10049. int force =0;
  10050. unsigned short callno = PTR_TO_CALLNO(chan->tech_pvt);
  10051. if (ast_strlen_zero(data))
  10052. data = "default";
  10053. sdata = ast_strdupa(data);
  10054. opts = strchr(sdata, '|');
  10055. if (opts)
  10056. *opts='\0';
  10057. if (chan->tech != &iax2_tech) {
  10058. ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
  10059. return -1;
  10060. }
  10061. if (!callno || !iaxs[callno] || !iaxs[callno]->addr.sin_addr.s_addr) {
  10062. ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
  10063. return -1;
  10064. }
  10065. res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
  10066. ast_verb(3, "Provisioned IAXY at '%s' with '%s'= %d\n",
  10067. ast_inet_ntoa(iaxs[callno]->addr.sin_addr),
  10068. sdata, res);
  10069. return res;
  10070. }
  10071. static char *handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  10072. {
  10073. int force = 0;
  10074. int res;
  10075. switch (cmd) {
  10076. case CLI_INIT:
  10077. e->command = "iax2 provision";
  10078. e->usage =
  10079. "Usage: iax2 provision <host> <template> [forced]\n"
  10080. " Provisions the given peer or IP address using a template\n"
  10081. " matching either 'template' or '*' if the template is not\n"
  10082. " found. If 'forced' is specified, even empty provisioning\n"
  10083. " fields will be provisioned as empty fields.\n";
  10084. return NULL;
  10085. case CLI_GENERATE:
  10086. if (a->pos == 3)
  10087. return iax_prov_complete_template(a->line, a->word, a->pos, a->n);
  10088. return NULL;
  10089. }
  10090. if (a->argc < 4)
  10091. return CLI_SHOWUSAGE;
  10092. if (a->argc > 4) {
  10093. if (!strcasecmp(a->argv[4], "forced"))
  10094. force = 1;
  10095. else
  10096. return CLI_SHOWUSAGE;
  10097. }
  10098. res = iax2_provision(NULL, -1, a->argv[2], a->argv[3], force);
  10099. if (res < 0)
  10100. ast_cli(a->fd, "Unable to find peer/address '%s'\n", a->argv[2]);
  10101. else if (res < 1)
  10102. ast_cli(a->fd, "No template (including wildcard) matching '%s'\n", a->argv[3]);
  10103. else
  10104. ast_cli(a->fd, "Provisioning '%s' with template '%s'%s\n", a->argv[2], a->argv[3], force ? ", forced" : "");
  10105. return CLI_SUCCESS;
  10106. }
  10107. static void __iax2_poke_noanswer(const void *data)
  10108. {
  10109. struct iax2_peer *peer = (struct iax2_peer *)data;
  10110. int callno;
  10111. if (peer->lastms > -1) {
  10112. ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
  10113. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, peer->lastms);
  10114. ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
  10115. }
  10116. if ((callno = peer->callno) > 0) {
  10117. ast_mutex_lock(&iaxsl[callno]);
  10118. iax2_destroy(callno);
  10119. ast_mutex_unlock(&iaxsl[callno]);
  10120. }
  10121. peer->callno = 0;
  10122. peer->lastms = -1;
  10123. /* Try again quickly */
  10124. peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
  10125. if (peer->pokeexpire == -1)
  10126. peer_unref(peer);
  10127. }
  10128. static int iax2_poke_noanswer(const void *data)
  10129. {
  10130. struct iax2_peer *peer = (struct iax2_peer *)data;
  10131. peer->pokeexpire = -1;
  10132. #ifdef SCHED_MULTITHREADED
  10133. if (schedule_action(__iax2_poke_noanswer, data))
  10134. #endif
  10135. __iax2_poke_noanswer(data);
  10136. peer_unref(peer);
  10137. return 0;
  10138. }
  10139. static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
  10140. {
  10141. struct iax2_peer *peer = obj;
  10142. iax2_poke_peer(peer, 0);
  10143. return 0;
  10144. }
  10145. static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
  10146. {
  10147. int callno;
  10148. if (!peer->maxms || (!peer->addr.sin_addr.s_addr && !peer->dnsmgr)) {
  10149. /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
  10150. immediately after clearing things out */
  10151. peer->lastms = 0;
  10152. peer->historicms = 0;
  10153. peer->pokeexpire = -1;
  10154. peer->callno = 0;
  10155. return 0;
  10156. }
  10157. /* The peer could change the callno inside iax2_destroy, since we do deadlock avoidance */
  10158. if ((callno = peer->callno) > 0) {
  10159. ast_log(LOG_NOTICE, "Still have a callno...\n");
  10160. ast_mutex_lock(&iaxsl[callno]);
  10161. iax2_destroy(callno);
  10162. ast_mutex_unlock(&iaxsl[callno]);
  10163. }
  10164. if (heldcall)
  10165. ast_mutex_unlock(&iaxsl[heldcall]);
  10166. callno = peer->callno = find_callno(0, 0, &peer->addr, NEW_FORCE, peer->sockfd, 0);
  10167. if (heldcall)
  10168. ast_mutex_lock(&iaxsl[heldcall]);
  10169. if (peer->callno < 1) {
  10170. ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
  10171. return -1;
  10172. }
  10173. /* Speed up retransmission times for this qualify call */
  10174. iaxs[peer->callno]->pingtime = peer->maxms / 4 + 1;
  10175. iaxs[peer->callno]->peerpoke = peer;
  10176. if (peer->pokeexpire > -1) {
  10177. if (!ast_sched_del(sched, peer->pokeexpire)) {
  10178. peer->pokeexpire = -1;
  10179. peer_unref(peer);
  10180. }
  10181. }
  10182. /* Queue up a new task to handle no reply */
  10183. /* If the host is already unreachable then use the unreachable interval instead */
  10184. if (peer->lastms < 0)
  10185. peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_noanswer, peer_ref(peer));
  10186. else
  10187. peer->pokeexpire = iax2_sched_add(sched, DEFAULT_MAXMS * 2, iax2_poke_noanswer, peer_ref(peer));
  10188. if (peer->pokeexpire == -1)
  10189. peer_unref(peer);
  10190. /* And send the poke */
  10191. ast_mutex_lock(&iaxsl[callno]);
  10192. if (iaxs[callno]) {
  10193. struct iax_ie_data ied = {
  10194. .buf = { 0 },
  10195. .pos = 0,
  10196. };
  10197. add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
  10198. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, ied.buf, ied.pos, -1);
  10199. }
  10200. ast_mutex_unlock(&iaxsl[callno]);
  10201. return 0;
  10202. }
  10203. static void free_context(struct iax2_context *con)
  10204. {
  10205. struct iax2_context *conl;
  10206. while(con) {
  10207. conl = con;
  10208. con = con->next;
  10209. ast_free(conl);
  10210. }
  10211. }
  10212. static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause)
  10213. {
  10214. int callno;
  10215. int res;
  10216. int fmt, native;
  10217. struct sockaddr_in sin;
  10218. struct ast_channel *c;
  10219. struct parsed_dial_string pds;
  10220. struct create_addr_info cai;
  10221. char *tmpstr;
  10222. memset(&pds, 0, sizeof(pds));
  10223. tmpstr = ast_strdupa(data);
  10224. parse_dial_string(tmpstr, &pds);
  10225. if (ast_strlen_zero(pds.peer)) {
  10226. ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
  10227. return NULL;
  10228. }
  10229. memset(&cai, 0, sizeof(cai));
  10230. cai.capability = iax2_capability;
  10231. ast_copy_flags(&cai, &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
  10232. /* Populate our address from the given */
  10233. if (create_addr(pds.peer, NULL, &sin, &cai)) {
  10234. *cause = AST_CAUSE_UNREGISTERED;
  10235. return NULL;
  10236. }
  10237. if (pds.port)
  10238. sin.sin_port = htons(atoi(pds.port));
  10239. callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
  10240. if (callno < 1) {
  10241. ast_log(LOG_WARNING, "Unable to create call\n");
  10242. *cause = AST_CAUSE_CONGESTION;
  10243. return NULL;
  10244. }
  10245. /* If this is a trunk, update it now */
  10246. ast_copy_flags(iaxs[callno], &cai, IAX_TRUNK | IAX_SENDANI | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
  10247. if (ast_test_flag(&cai, IAX_TRUNK)) {
  10248. int new_callno;
  10249. if ((new_callno = make_trunk(callno, 1)) != -1)
  10250. callno = new_callno;
  10251. }
  10252. iaxs[callno]->maxtime = cai.maxtime;
  10253. if (cai.found)
  10254. ast_string_field_set(iaxs[callno], host, pds.peer);
  10255. c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability);
  10256. ast_mutex_unlock(&iaxsl[callno]);
  10257. if (c) {
  10258. /* Choose a format we can live with */
  10259. if (c->nativeformats & format)
  10260. c->nativeformats &= format;
  10261. else {
  10262. native = c->nativeformats;
  10263. fmt = format;
  10264. res = ast_translator_best_choice(&fmt, &native);
  10265. if (res < 0) {
  10266. ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
  10267. ast_getformatname(c->nativeformats), ast_getformatname(fmt), c->name);
  10268. ast_hangup(c);
  10269. return NULL;
  10270. }
  10271. c->nativeformats = native;
  10272. }
  10273. c->readformat = ast_best_codec(c->nativeformats);
  10274. c->writeformat = c->readformat;
  10275. }
  10276. return c;
  10277. }
  10278. static void *sched_thread(void *ignore)
  10279. {
  10280. int count;
  10281. int res;
  10282. struct timeval tv;
  10283. struct timespec ts;
  10284. for (;;) {
  10285. res = ast_sched_wait(sched);
  10286. if ((res > 1000) || (res < 0))
  10287. res = 1000;
  10288. tv = ast_tvadd(ast_tvnow(), ast_samp2tv(res, 1000));
  10289. ts.tv_sec = tv.tv_sec;
  10290. ts.tv_nsec = tv.tv_usec * 1000;
  10291. pthread_testcancel();
  10292. ast_mutex_lock(&sched_lock);
  10293. ast_cond_timedwait(&sched_cond, &sched_lock, &ts);
  10294. ast_mutex_unlock(&sched_lock);
  10295. pthread_testcancel();
  10296. count = ast_sched_runq(sched);
  10297. if (count >= 20)
  10298. ast_debug(1, "chan_iax2: ast_sched_runq ran %d scheduled tasks all at once\n", count);
  10299. }
  10300. return NULL;
  10301. }
  10302. static void *network_thread(void *ignore)
  10303. {
  10304. /* Our job is simple: Send queued messages, retrying if necessary. Read frames
  10305. from the network, and queue them for delivery to the channels */
  10306. int res, count, wakeup;
  10307. struct iax_frame *f;
  10308. if (timingfd > -1)
  10309. ast_io_add(io, timingfd, timing_read, AST_IO_IN | AST_IO_PRI, NULL);
  10310. for(;;) {
  10311. pthread_testcancel();
  10312. /* Go through the queue, sending messages which have not yet been
  10313. sent, and scheduling retransmissions if appropriate */
  10314. AST_LIST_LOCK(&frame_queue);
  10315. count = 0;
  10316. wakeup = -1;
  10317. AST_LIST_TRAVERSE_SAFE_BEGIN(&frame_queue, f, list) {
  10318. if (f->sentyet)
  10319. continue;
  10320. /* Try to lock the pvt, if we can't... don't fret - defer it till later */
  10321. if (ast_mutex_trylock(&iaxsl[f->callno])) {
  10322. wakeup = 1;
  10323. continue;
  10324. }
  10325. f->sentyet = 1;
  10326. if (iaxs[f->callno]) {
  10327. send_packet(f);
  10328. count++;
  10329. }
  10330. ast_mutex_unlock(&iaxsl[f->callno]);
  10331. if (f->retries < 0) {
  10332. /* This is not supposed to be retransmitted */
  10333. AST_LIST_REMOVE_CURRENT(list);
  10334. /* Free the iax frame */
  10335. iax_frame_free(f);
  10336. } else {
  10337. /* We need reliable delivery. Schedule a retransmission */
  10338. f->retries++;
  10339. f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
  10340. }
  10341. }
  10342. AST_LIST_TRAVERSE_SAFE_END;
  10343. AST_LIST_UNLOCK(&frame_queue);
  10344. pthread_testcancel();
  10345. if (count >= 20)
  10346. ast_debug(1, "chan_iax2: Sent %d queued outbound frames all at once\n", count);
  10347. /* Now do the IO, and run scheduled tasks */
  10348. res = ast_io_wait(io, wakeup);
  10349. if (res >= 0) {
  10350. if (res >= 20)
  10351. ast_debug(1, "chan_iax2: ast_io_wait ran %d I/Os all at once\n", res);
  10352. }
  10353. }
  10354. return NULL;
  10355. }
  10356. static int start_network_thread(void)
  10357. {
  10358. struct iax2_thread *thread;
  10359. int threadcount = 0;
  10360. int x;
  10361. for (x = 0; x < iaxthreadcount; x++) {
  10362. thread = ast_calloc(1, sizeof(*thread));
  10363. if (thread) {
  10364. thread->type = IAX_THREAD_TYPE_POOL;
  10365. thread->threadnum = ++threadcount;
  10366. ast_mutex_init(&thread->lock);
  10367. ast_cond_init(&thread->cond, NULL);
  10368. if (ast_pthread_create_detached(&thread->threadid, NULL, iax2_process_thread, thread)) {
  10369. ast_log(LOG_WARNING, "Failed to create new thread!\n");
  10370. ast_free(thread);
  10371. thread = NULL;
  10372. }
  10373. AST_LIST_LOCK(&idle_list);
  10374. AST_LIST_INSERT_TAIL(&idle_list, thread, list);
  10375. AST_LIST_UNLOCK(&idle_list);
  10376. }
  10377. }
  10378. ast_pthread_create_background(&schedthreadid, NULL, sched_thread, NULL);
  10379. ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL);
  10380. ast_verb(2, "%d helper threads started\n", threadcount);
  10381. return 0;
  10382. }
  10383. static struct iax2_context *build_context(const char *context)
  10384. {
  10385. struct iax2_context *con;
  10386. if ((con = ast_calloc(1, sizeof(*con))))
  10387. ast_copy_string(con->context, context, sizeof(con->context));
  10388. return con;
  10389. }
  10390. static int get_auth_methods(const char *value)
  10391. {
  10392. int methods = 0;
  10393. if (strstr(value, "rsa"))
  10394. methods |= IAX_AUTH_RSA;
  10395. if (strstr(value, "md5"))
  10396. methods |= IAX_AUTH_MD5;
  10397. if (strstr(value, "plaintext"))
  10398. methods |= IAX_AUTH_PLAINTEXT;
  10399. return methods;
  10400. }
  10401. /*! \brief Check if address can be used as packet source.
  10402. \return 0 address available, 1 address unavailable, -1 error
  10403. */
  10404. static int check_srcaddr(struct sockaddr *sa, socklen_t salen)
  10405. {
  10406. int sd;
  10407. int res;
  10408. sd = socket(AF_INET, SOCK_DGRAM, 0);
  10409. if (sd < 0) {
  10410. ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
  10411. return -1;
  10412. }
  10413. res = bind(sd, sa, salen);
  10414. if (res < 0) {
  10415. ast_debug(1, "Can't bind: %s\n", strerror(errno));
  10416. close(sd);
  10417. return 1;
  10418. }
  10419. close(sd);
  10420. return 0;
  10421. }
  10422. /*! \brief Parse the "sourceaddress" value,
  10423. lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
  10424. not found. */
  10425. static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
  10426. {
  10427. struct sockaddr_in sin;
  10428. int nonlocal = 1;
  10429. int port = IAX_DEFAULT_PORTNO;
  10430. int sockfd = defaultsockfd;
  10431. char *tmp;
  10432. char *addr;
  10433. char *portstr;
  10434. if (!(tmp = ast_strdupa(srcaddr)))
  10435. return -1;
  10436. addr = strsep(&tmp, ":");
  10437. portstr = tmp;
  10438. if (portstr) {
  10439. port = atoi(portstr);
  10440. if (port < 1)
  10441. port = IAX_DEFAULT_PORTNO;
  10442. }
  10443. if (!ast_get_ip(&sin, addr)) {
  10444. struct ast_netsock *sock;
  10445. int res;
  10446. sin.sin_port = 0;
  10447. sin.sin_family = AF_INET;
  10448. res = check_srcaddr((struct sockaddr *) &sin, sizeof(sin));
  10449. if (res == 0) {
  10450. /* ip address valid. */
  10451. sin.sin_port = htons(port);
  10452. if (!(sock = ast_netsock_find(netsock, &sin)))
  10453. sock = ast_netsock_find(outsock, &sin);
  10454. if (sock) {
  10455. sockfd = ast_netsock_sockfd(sock);
  10456. nonlocal = 0;
  10457. } else {
  10458. unsigned int orig_saddr = sin.sin_addr.s_addr;
  10459. /* INADDR_ANY matches anyway! */
  10460. sin.sin_addr.s_addr = INADDR_ANY;
  10461. if (ast_netsock_find(netsock, &sin)) {
  10462. sin.sin_addr.s_addr = orig_saddr;
  10463. sock = ast_netsock_bind(outsock, io, srcaddr, port, tos, cos, socket_read, NULL);
  10464. if (sock) {
  10465. sockfd = ast_netsock_sockfd(sock);
  10466. ast_netsock_unref(sock);
  10467. nonlocal = 0;
  10468. } else {
  10469. nonlocal = 2;
  10470. }
  10471. }
  10472. }
  10473. }
  10474. }
  10475. peer->sockfd = sockfd;
  10476. if (nonlocal == 1) {
  10477. ast_log(LOG_WARNING, "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
  10478. srcaddr, peer->name);
  10479. return -1;
  10480. } else if (nonlocal == 2) {
  10481. ast_log(LOG_WARNING, "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
  10482. srcaddr, peer->name);
  10483. return -1;
  10484. } else {
  10485. ast_debug(1, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
  10486. return 0;
  10487. }
  10488. }
  10489. static void peer_destructor(void *obj)
  10490. {
  10491. struct iax2_peer *peer = obj;
  10492. int callno = peer->callno;
  10493. ast_free_ha(peer->ha);
  10494. if (callno > 0) {
  10495. ast_mutex_lock(&iaxsl[callno]);
  10496. iax2_destroy(callno);
  10497. ast_mutex_unlock(&iaxsl[callno]);
  10498. }
  10499. register_peer_exten(peer, 0);
  10500. if (peer->dnsmgr)
  10501. ast_dnsmgr_release(peer->dnsmgr);
  10502. if (peer->mwi_event_sub)
  10503. ast_event_unsubscribe(peer->mwi_event_sub);
  10504. ast_string_field_free_memory(peer);
  10505. }
  10506. /*! \brief Create peer structure based on configuration */
  10507. static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
  10508. {
  10509. struct iax2_peer *peer = NULL;
  10510. struct ast_ha *oldha = NULL;
  10511. int maskfound = 0;
  10512. int found = 0;
  10513. int firstpass = 1;
  10514. struct iax2_peer tmp_peer = {
  10515. .name = name,
  10516. };
  10517. if (!temponly) {
  10518. peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
  10519. if (peer && !ast_test_flag(peer, IAX_DELME))
  10520. firstpass = 0;
  10521. }
  10522. if (peer) {
  10523. found++;
  10524. if (firstpass) {
  10525. oldha = peer->ha;
  10526. peer->ha = NULL;
  10527. }
  10528. unlink_peer(peer);
  10529. } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
  10530. peer->expire = -1;
  10531. peer->pokeexpire = -1;
  10532. peer->sockfd = defaultsockfd;
  10533. if (ast_string_field_init(peer, 32))
  10534. peer = peer_unref(peer);
  10535. }
  10536. if (peer) {
  10537. if (firstpass) {
  10538. ast_copy_flags(peer, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
  10539. peer->encmethods = iax2_encryption;
  10540. peer->adsi = adsi;
  10541. ast_string_field_set(peer,secret,"");
  10542. if (!found) {
  10543. ast_string_field_set(peer, name, name);
  10544. peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
  10545. peer->expiry = min_reg_expire;
  10546. }
  10547. peer->prefs = prefs;
  10548. peer->capability = iax2_capability;
  10549. peer->smoothing = 0;
  10550. peer->pokefreqok = DEFAULT_FREQ_OK;
  10551. peer->pokefreqnotok = DEFAULT_FREQ_NOTOK;
  10552. peer->maxcallno = 0;
  10553. peercnt_modify(0, 0, &peer->addr);
  10554. peer->calltoken_required = CALLTOKEN_DEFAULT;
  10555. ast_string_field_set(peer,context,"");
  10556. ast_string_field_set(peer,peercontext,"");
  10557. ast_clear_flag(peer, IAX_HASCALLERID);
  10558. ast_string_field_set(peer, cid_name, "");
  10559. ast_string_field_set(peer, cid_num, "");
  10560. ast_string_field_set(peer, mohinterpret, mohinterpret);
  10561. ast_string_field_set(peer, mohsuggest, mohsuggest);
  10562. }
  10563. if (!v) {
  10564. v = alt;
  10565. alt = NULL;
  10566. }
  10567. while(v) {
  10568. if (!strcasecmp(v->name, "secret")) {
  10569. ast_string_field_set(peer, secret, v->value);
  10570. } else if (!strcasecmp(v->name, "mailbox")) {
  10571. ast_string_field_set(peer, mailbox, v->value);
  10572. } else if (!strcasecmp(v->name, "hasvoicemail")) {
  10573. if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
  10574. ast_string_field_set(peer, mailbox, name);
  10575. }
  10576. } else if (!strcasecmp(v->name, "mohinterpret")) {
  10577. ast_string_field_set(peer, mohinterpret, v->value);
  10578. } else if (!strcasecmp(v->name, "mohsuggest")) {
  10579. ast_string_field_set(peer, mohsuggest, v->value);
  10580. } else if (!strcasecmp(v->name, "dbsecret")) {
  10581. ast_string_field_set(peer, dbsecret, v->value);
  10582. } else if (!strcasecmp(v->name, "trunk")) {
  10583. ast_set2_flag(peer, ast_true(v->value), IAX_TRUNK);
  10584. if (ast_test_flag(peer, IAX_TRUNK) && (timingfd < 0)) {
  10585. ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without DAHDI timing\n", peer->name);
  10586. ast_clear_flag(peer, IAX_TRUNK);
  10587. }
  10588. } else if (!strcasecmp(v->name, "auth")) {
  10589. peer->authmethods = get_auth_methods(v->value);
  10590. } else if (!strcasecmp(v->name, "encryption")) {
  10591. peer->encmethods = get_encrypt_methods(v->value);
  10592. } else if (!strcasecmp(v->name, "transfer")) {
  10593. if (!strcasecmp(v->value, "mediaonly")) {
  10594. ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
  10595. } else if (ast_true(v->value)) {
  10596. ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
  10597. } else
  10598. ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
  10599. } else if (!strcasecmp(v->name, "jitterbuffer")) {
  10600. ast_set2_flag(peer, ast_true(v->value), IAX_USEJITTERBUF);
  10601. } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
  10602. ast_set2_flag(peer, ast_true(v->value), IAX_FORCEJITTERBUF);
  10603. } else if (!strcasecmp(v->name, "host")) {
  10604. if (!strcasecmp(v->value, "dynamic")) {
  10605. /* They'll register with us */
  10606. ast_set_flag(peer, IAX_DYNAMIC);
  10607. if (!found) {
  10608. /* Initialize stuff iff we're not found, otherwise
  10609. we keep going with what we had */
  10610. memset(&peer->addr.sin_addr, 0, 4);
  10611. if (peer->addr.sin_port) {
  10612. /* If we've already got a port, make it the default rather than absolute */
  10613. peer->defaddr.sin_port = peer->addr.sin_port;
  10614. peer->addr.sin_port = 0;
  10615. }
  10616. }
  10617. } else {
  10618. /* Non-dynamic. Make sure we become that way if we're not */
  10619. AST_SCHED_DEL(sched, peer->expire);
  10620. ast_clear_flag(peer, IAX_DYNAMIC);
  10621. if (ast_dnsmgr_lookup(v->value, &peer->addr.sin_addr, &peer->dnsmgr))
  10622. return peer_unref(peer);
  10623. if (!peer->addr.sin_port)
  10624. peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
  10625. }
  10626. if (!maskfound)
  10627. inet_aton("255.255.255.255", &peer->mask);
  10628. } else if (!strcasecmp(v->name, "defaultip")) {
  10629. if (ast_get_ip(&peer->defaddr, v->value))
  10630. return peer_unref(peer);
  10631. } else if (!strcasecmp(v->name, "sourceaddress")) {
  10632. peer_set_srcaddr(peer, v->value);
  10633. } else if (!strcasecmp(v->name, "permit") ||
  10634. !strcasecmp(v->name, "deny")) {
  10635. peer->ha = ast_append_ha(v->name, v->value, peer->ha, NULL);
  10636. } else if (!strcasecmp(v->name, "mask")) {
  10637. maskfound++;
  10638. inet_aton(v->value, &peer->mask);
  10639. } else if (!strcasecmp(v->name, "context")) {
  10640. ast_string_field_set(peer, context, v->value);
  10641. } else if (!strcasecmp(v->name, "regexten")) {
  10642. ast_string_field_set(peer, regexten, v->value);
  10643. } else if (!strcasecmp(v->name, "peercontext")) {
  10644. ast_string_field_set(peer, peercontext, v->value);
  10645. } else if (!strcasecmp(v->name, "port")) {
  10646. if (ast_test_flag(peer, IAX_DYNAMIC))
  10647. peer->defaddr.sin_port = htons(atoi(v->value));
  10648. else
  10649. peer->addr.sin_port = htons(atoi(v->value));
  10650. } else if (!strcasecmp(v->name, "username")) {
  10651. ast_string_field_set(peer, username, v->value);
  10652. } else if (!strcasecmp(v->name, "allow")) {
  10653. ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
  10654. } else if (!strcasecmp(v->name, "disallow")) {
  10655. ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
  10656. } else if (!strcasecmp(v->name, "callerid")) {
  10657. if (!ast_strlen_zero(v->value)) {
  10658. char name2[80];
  10659. char num2[80];
  10660. ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
  10661. ast_string_field_set(peer, cid_name, name2);
  10662. ast_string_field_set(peer, cid_num, num2);
  10663. } else {
  10664. ast_string_field_set(peer, cid_name, "");
  10665. ast_string_field_set(peer, cid_num, "");
  10666. }
  10667. ast_set_flag(peer, IAX_HASCALLERID);
  10668. } else if (!strcasecmp(v->name, "fullname")) {
  10669. ast_string_field_set(peer, cid_name, S_OR(v->value, ""));
  10670. ast_set_flag(peer, IAX_HASCALLERID);
  10671. } else if (!strcasecmp(v->name, "cid_number")) {
  10672. ast_string_field_set(peer, cid_num, S_OR(v->value, ""));
  10673. ast_set_flag(peer, IAX_HASCALLERID);
  10674. } else if (!strcasecmp(v->name, "sendani")) {
  10675. ast_set2_flag(peer, ast_true(v->value), IAX_SENDANI);
  10676. } else if (!strcasecmp(v->name, "inkeys")) {
  10677. ast_string_field_set(peer, inkeys, v->value);
  10678. } else if (!strcasecmp(v->name, "outkey")) {
  10679. ast_string_field_set(peer, outkey, v->value);
  10680. } else if (!strcasecmp(v->name, "qualify")) {
  10681. if (!strcasecmp(v->value, "no")) {
  10682. peer->maxms = 0;
  10683. } else if (!strcasecmp(v->value, "yes")) {
  10684. peer->maxms = DEFAULT_MAXMS;
  10685. } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
  10686. 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);
  10687. peer->maxms = 0;
  10688. }
  10689. } else if (!strcasecmp(v->name, "qualifysmoothing")) {
  10690. peer->smoothing = ast_true(v->value);
  10691. } else if (!strcasecmp(v->name, "qualifyfreqok")) {
  10692. if (sscanf(v->value, "%30d", &peer->pokefreqok) != 1) {
  10693. 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);
  10694. }
  10695. } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
  10696. if (sscanf(v->value, "%30d", &peer->pokefreqnotok) != 1) {
  10697. 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);
  10698. } else ast_log(LOG_WARNING, "Set peer->pokefreqnotok to %d\n", peer->pokefreqnotok);
  10699. } else if (!strcasecmp(v->name, "timezone")) {
  10700. ast_string_field_set(peer, zonetag, v->value);
  10701. } else if (!strcasecmp(v->name, "adsi")) {
  10702. peer->adsi = ast_true(v->value);
  10703. } else if (!strcasecmp(v->name, "maxcallnumbers")) {
  10704. if (sscanf(v->value, "%10hu", &peer->maxcallno) != 1) {
  10705. ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
  10706. } else {
  10707. peercnt_modify(1, peer->maxcallno, &peer->addr);
  10708. }
  10709. } else if (!strcasecmp(v->name, "requirecalltoken")) {
  10710. /* default is required unless in optional ip list */
  10711. if (ast_false(v->value)) {
  10712. peer->calltoken_required = CALLTOKEN_NO;
  10713. } else if (!strcasecmp(v->value, "auto")) {
  10714. peer->calltoken_required = CALLTOKEN_AUTO;
  10715. } else if (ast_true(v->value)) {
  10716. peer->calltoken_required = CALLTOKEN_YES;
  10717. } else {
  10718. ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
  10719. }
  10720. } /* else if (strcasecmp(v->name,"type")) */
  10721. /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
  10722. v = v->next;
  10723. if (!v) {
  10724. v = alt;
  10725. alt = NULL;
  10726. }
  10727. }
  10728. if (!peer->authmethods)
  10729. peer->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
  10730. ast_clear_flag(peer, IAX_DELME);
  10731. /* Make sure these are IPv4 addresses */
  10732. peer->addr.sin_family = AF_INET;
  10733. }
  10734. if (oldha)
  10735. ast_free_ha(oldha);
  10736. if (!ast_strlen_zero(peer->mailbox)) {
  10737. char *mailbox, *context;
  10738. context = mailbox = ast_strdupa(peer->mailbox);
  10739. strsep(&context, "@");
  10740. if (ast_strlen_zero(context))
  10741. context = "default";
  10742. peer->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, NULL,
  10743. AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
  10744. AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
  10745. AST_EVENT_IE_END);
  10746. }
  10747. return peer;
  10748. }
  10749. static void user_destructor(void *obj)
  10750. {
  10751. struct iax2_user *user = obj;
  10752. ast_free_ha(user->ha);
  10753. free_context(user->contexts);
  10754. if(user->vars) {
  10755. ast_variables_destroy(user->vars);
  10756. user->vars = NULL;
  10757. }
  10758. ast_string_field_free_memory(user);
  10759. }
  10760. /*! \brief Create in-memory user structure from configuration */
  10761. static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
  10762. {
  10763. struct iax2_user *user = NULL;
  10764. struct iax2_context *con, *conl = NULL;
  10765. struct ast_ha *oldha = NULL;
  10766. struct iax2_context *oldcon = NULL;
  10767. int format;
  10768. int firstpass=1;
  10769. int oldcurauthreq = 0;
  10770. char *varname = NULL, *varval = NULL;
  10771. struct ast_variable *tmpvar = NULL;
  10772. struct iax2_user tmp_user = {
  10773. .name = name,
  10774. };
  10775. if (!temponly) {
  10776. user = ao2_find(users, &tmp_user, OBJ_POINTER);
  10777. if (user && !ast_test_flag(user, IAX_DELME))
  10778. firstpass = 0;
  10779. }
  10780. if (user) {
  10781. if (firstpass) {
  10782. oldcurauthreq = user->curauthreq;
  10783. oldha = user->ha;
  10784. oldcon = user->contexts;
  10785. user->ha = NULL;
  10786. user->contexts = NULL;
  10787. }
  10788. /* Already in the list, remove it and it will be added back (or FREE'd) */
  10789. ao2_unlink(users, user);
  10790. } else {
  10791. user = ao2_alloc(sizeof(*user), user_destructor);
  10792. }
  10793. if (user) {
  10794. if (firstpass) {
  10795. ast_string_field_free_memory(user);
  10796. memset(user, 0, sizeof(struct iax2_user));
  10797. if (ast_string_field_init(user, 32)) {
  10798. user = user_unref(user);
  10799. goto cleanup;
  10800. }
  10801. user->maxauthreq = maxauthreq;
  10802. user->curauthreq = oldcurauthreq;
  10803. user->prefs = prefs;
  10804. user->capability = iax2_capability;
  10805. user->encmethods = iax2_encryption;
  10806. user->adsi = adsi;
  10807. user->calltoken_required = CALLTOKEN_DEFAULT;
  10808. ast_string_field_set(user, name, name);
  10809. ast_string_field_set(user, language, language);
  10810. ast_copy_flags(user, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_CODEC_USER_FIRST | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP);
  10811. ast_clear_flag(user, IAX_HASCALLERID);
  10812. ast_string_field_set(user, cid_name, "");
  10813. ast_string_field_set(user, cid_num, "");
  10814. ast_string_field_set(user, accountcode, accountcode);
  10815. ast_string_field_set(user, mohinterpret, mohinterpret);
  10816. ast_string_field_set(user, mohsuggest, mohsuggest);
  10817. }
  10818. if (!v) {
  10819. v = alt;
  10820. alt = NULL;
  10821. }
  10822. while(v) {
  10823. if (!strcasecmp(v->name, "context")) {
  10824. con = build_context(v->value);
  10825. if (con) {
  10826. if (conl)
  10827. conl->next = con;
  10828. else
  10829. user->contexts = con;
  10830. conl = con;
  10831. }
  10832. } else if (!strcasecmp(v->name, "permit") ||
  10833. !strcasecmp(v->name, "deny")) {
  10834. user->ha = ast_append_ha(v->name, v->value, user->ha, NULL);
  10835. } else if (!strcasecmp(v->name, "setvar")) {
  10836. varname = ast_strdupa(v->value);
  10837. if (varname && (varval = strchr(varname,'='))) {
  10838. *varval = '\0';
  10839. varval++;
  10840. if((tmpvar = ast_variable_new(varname, varval, ""))) {
  10841. tmpvar->next = user->vars;
  10842. user->vars = tmpvar;
  10843. }
  10844. }
  10845. } else if (!strcasecmp(v->name, "allow")) {
  10846. ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
  10847. } else if (!strcasecmp(v->name, "disallow")) {
  10848. ast_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
  10849. } else if (!strcasecmp(v->name, "trunk")) {
  10850. ast_set2_flag(user, ast_true(v->value), IAX_TRUNK);
  10851. if (ast_test_flag(user, IAX_TRUNK) && (timingfd < 0)) {
  10852. ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without DAHDI timing\n", user->name);
  10853. ast_clear_flag(user, IAX_TRUNK);
  10854. }
  10855. } else if (!strcasecmp(v->name, "auth")) {
  10856. user->authmethods = get_auth_methods(v->value);
  10857. } else if (!strcasecmp(v->name, "encryption")) {
  10858. user->encmethods = get_encrypt_methods(v->value);
  10859. } else if (!strcasecmp(v->name, "transfer")) {
  10860. if (!strcasecmp(v->value, "mediaonly")) {
  10861. ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
  10862. } else if (ast_true(v->value)) {
  10863. ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
  10864. } else
  10865. ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
  10866. } else if (!strcasecmp(v->name, "codecpriority")) {
  10867. if(!strcasecmp(v->value, "caller"))
  10868. ast_set_flag(user, IAX_CODEC_USER_FIRST);
  10869. else if(!strcasecmp(v->value, "disabled"))
  10870. ast_set_flag(user, IAX_CODEC_NOPREFS);
  10871. else if(!strcasecmp(v->value, "reqonly")) {
  10872. ast_set_flag(user, IAX_CODEC_NOCAP);
  10873. ast_set_flag(user, IAX_CODEC_NOPREFS);
  10874. }
  10875. } else if (!strcasecmp(v->name, "jitterbuffer")) {
  10876. ast_set2_flag(user, ast_true(v->value), IAX_USEJITTERBUF);
  10877. } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
  10878. ast_set2_flag(user, ast_true(v->value), IAX_FORCEJITTERBUF);
  10879. } else if (!strcasecmp(v->name, "dbsecret")) {
  10880. ast_string_field_set(user, dbsecret, v->value);
  10881. } else if (!strcasecmp(v->name, "secret")) {
  10882. if (!ast_strlen_zero(user->secret)) {
  10883. char *old = ast_strdupa(user->secret);
  10884. ast_string_field_build(user, secret, "%s;%s", old, v->value);
  10885. } else
  10886. ast_string_field_set(user, secret, v->value);
  10887. } else if (!strcasecmp(v->name, "callerid")) {
  10888. if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
  10889. char name2[80];
  10890. char num2[80];
  10891. ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
  10892. ast_string_field_set(user, cid_name, name2);
  10893. ast_string_field_set(user, cid_num, num2);
  10894. ast_set_flag(user, IAX_HASCALLERID);
  10895. } else {
  10896. ast_clear_flag(user, IAX_HASCALLERID);
  10897. ast_string_field_set(user, cid_name, "");
  10898. ast_string_field_set(user, cid_num, "");
  10899. }
  10900. } else if (!strcasecmp(v->name, "fullname")) {
  10901. if (!ast_strlen_zero(v->value)) {
  10902. ast_string_field_set(user, cid_name, v->value);
  10903. ast_set_flag(user, IAX_HASCALLERID);
  10904. } else {
  10905. ast_string_field_set(user, cid_name, "");
  10906. if (ast_strlen_zero(user->cid_num))
  10907. ast_clear_flag(user, IAX_HASCALLERID);
  10908. }
  10909. } else if (!strcasecmp(v->name, "cid_number")) {
  10910. if (!ast_strlen_zero(v->value)) {
  10911. ast_string_field_set(user, cid_num, v->value);
  10912. ast_set_flag(user, IAX_HASCALLERID);
  10913. } else {
  10914. ast_string_field_set(user, cid_num, "");
  10915. if (ast_strlen_zero(user->cid_name))
  10916. ast_clear_flag(user, IAX_HASCALLERID);
  10917. }
  10918. } else if (!strcasecmp(v->name, "accountcode")) {
  10919. ast_string_field_set(user, accountcode, v->value);
  10920. } else if (!strcasecmp(v->name, "mohinterpret")) {
  10921. ast_string_field_set(user, mohinterpret, v->value);
  10922. } else if (!strcasecmp(v->name, "mohsuggest")) {
  10923. ast_string_field_set(user, mohsuggest, v->value);
  10924. } else if (!strcasecmp(v->name, "language")) {
  10925. ast_string_field_set(user, language, v->value);
  10926. } else if (!strcasecmp(v->name, "amaflags")) {
  10927. format = ast_cdr_amaflags2int(v->value);
  10928. if (format < 0) {
  10929. ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
  10930. } else {
  10931. user->amaflags = format;
  10932. }
  10933. } else if (!strcasecmp(v->name, "inkeys")) {
  10934. ast_string_field_set(user, inkeys, v->value);
  10935. } else if (!strcasecmp(v->name, "maxauthreq")) {
  10936. user->maxauthreq = atoi(v->value);
  10937. if (user->maxauthreq < 0)
  10938. user->maxauthreq = 0;
  10939. } else if (!strcasecmp(v->name, "adsi")) {
  10940. user->adsi = ast_true(v->value);
  10941. } else if (!strcasecmp(v->name, "requirecalltoken")) {
  10942. /* default is required unless in optional ip list */
  10943. if (ast_false(v->value)) {
  10944. user->calltoken_required = CALLTOKEN_NO;
  10945. } else if (!strcasecmp(v->value, "auto")) {
  10946. user->calltoken_required = CALLTOKEN_AUTO;
  10947. } else if (ast_true(v->value)) {
  10948. user->calltoken_required = CALLTOKEN_YES;
  10949. } else {
  10950. ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
  10951. }
  10952. } /* else if (strcasecmp(v->name,"type")) */
  10953. /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
  10954. v = v->next;
  10955. if (!v) {
  10956. v = alt;
  10957. alt = NULL;
  10958. }
  10959. }
  10960. if (!user->authmethods) {
  10961. if (!ast_strlen_zero(user->secret)) {
  10962. user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
  10963. if (!ast_strlen_zero(user->inkeys))
  10964. user->authmethods |= IAX_AUTH_RSA;
  10965. } else if (!ast_strlen_zero(user->inkeys)) {
  10966. user->authmethods = IAX_AUTH_RSA;
  10967. } else {
  10968. user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
  10969. }
  10970. }
  10971. ast_clear_flag(user, IAX_DELME);
  10972. }
  10973. cleanup:
  10974. if (oldha)
  10975. ast_free_ha(oldha);
  10976. if (oldcon)
  10977. free_context(oldcon);
  10978. return user;
  10979. }
  10980. static int peer_delme_cb(void *obj, void *arg, int flags)
  10981. {
  10982. struct iax2_peer *peer = obj;
  10983. ast_set_flag(peer, IAX_DELME);
  10984. return 0;
  10985. }
  10986. static int user_delme_cb(void *obj, void *arg, int flags)
  10987. {
  10988. struct iax2_user *user = obj;
  10989. ast_set_flag(user, IAX_DELME);
  10990. return 0;
  10991. }
  10992. static void delete_users(void)
  10993. {
  10994. struct iax2_registry *reg;
  10995. ao2_callback(users, 0, user_delme_cb, NULL);
  10996. AST_LIST_LOCK(&registrations);
  10997. while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
  10998. AST_SCHED_DEL(sched, reg->expire);
  10999. if (reg->callno) {
  11000. int callno = reg->callno;
  11001. ast_mutex_lock(&iaxsl[callno]);
  11002. if (iaxs[callno]) {
  11003. iaxs[callno]->reg = NULL;
  11004. iax2_destroy(callno);
  11005. }
  11006. ast_mutex_unlock(&iaxsl[callno]);
  11007. }
  11008. if (reg->dnsmgr)
  11009. ast_dnsmgr_release(reg->dnsmgr);
  11010. ast_free(reg);
  11011. }
  11012. AST_LIST_UNLOCK(&registrations);
  11013. ao2_callback(peers, 0, peer_delme_cb, NULL);
  11014. }
  11015. static void prune_users(void)
  11016. {
  11017. struct iax2_user *user;
  11018. struct ao2_iterator i;
  11019. i = ao2_iterator_init(users, 0);
  11020. while ((user = ao2_iterator_next(&i))) {
  11021. if (ast_test_flag(user, IAX_DELME) || ast_test_flag(user, IAX_RTCACHEFRIENDS)) {
  11022. ao2_unlink(users, user);
  11023. }
  11024. user_unref(user);
  11025. }
  11026. ao2_iterator_destroy(&i);
  11027. }
  11028. /* Prune peers who still are supposed to be deleted */
  11029. static void prune_peers(void)
  11030. {
  11031. struct iax2_peer *peer;
  11032. struct ao2_iterator i;
  11033. i = ao2_iterator_init(peers, 0);
  11034. while ((peer = ao2_iterator_next(&i))) {
  11035. if (ast_test_flag(peer, IAX_DELME) || ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
  11036. unlink_peer(peer);
  11037. }
  11038. peer_unref(peer);
  11039. }
  11040. ao2_iterator_destroy(&i);
  11041. }
  11042. static void set_timing(void)
  11043. {
  11044. #ifdef HAVE_DAHDI
  11045. int bs = trunkfreq * 8;
  11046. if (timingfd > -1) {
  11047. if (
  11048. #ifdef DAHDI_TIMERACK
  11049. ioctl(timingfd, DAHDI_TIMERCONFIG, &bs) &&
  11050. #endif
  11051. ioctl(timingfd, DAHDI_SET_BLOCKSIZE, &bs))
  11052. ast_log(LOG_WARNING, "Unable to set blocksize on timing source\n");
  11053. }
  11054. #endif
  11055. }
  11056. static void set_config_destroy(void)
  11057. {
  11058. strcpy(accountcode, "");
  11059. strcpy(language, "");
  11060. strcpy(mohinterpret, "default");
  11061. strcpy(mohsuggest, "");
  11062. trunkmaxsize = MAX_TRUNKDATA;
  11063. amaflags = 0;
  11064. delayreject = 0;
  11065. ast_clear_flag((&globalflags), IAX_NOTRANSFER);
  11066. ast_clear_flag((&globalflags), IAX_TRANSFERMEDIA);
  11067. ast_clear_flag((&globalflags), IAX_USEJITTERBUF);
  11068. ast_clear_flag((&globalflags), IAX_FORCEJITTERBUF);
  11069. delete_users();
  11070. ao2_callback(callno_limits, OBJ_NODATA, addr_range_delme_cb, NULL);
  11071. ao2_callback(calltoken_ignores, OBJ_NODATA, addr_range_delme_cb, NULL);
  11072. }
  11073. /*! \brief Load configuration */
  11074. static int set_config(const char *config_file, int reload)
  11075. {
  11076. struct ast_config *cfg, *ucfg;
  11077. int capability=iax2_capability;
  11078. struct ast_variable *v;
  11079. char *cat;
  11080. const char *utype;
  11081. const char *tosval;
  11082. int format;
  11083. int portno = IAX_DEFAULT_PORTNO;
  11084. int x;
  11085. int mtuv;
  11086. struct iax2_user *user;
  11087. struct iax2_peer *peer;
  11088. struct ast_netsock *ns;
  11089. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  11090. #if 0
  11091. static unsigned short int last_port=0;
  11092. #endif
  11093. cfg = ast_config_load(config_file, config_flags);
  11094. if (!cfg) {
  11095. ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
  11096. return -1;
  11097. } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  11098. ucfg = ast_config_load("users.conf", config_flags);
  11099. if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
  11100. return 0;
  11101. /* Otherwise we need to reread both files */
  11102. ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
  11103. cfg = ast_config_load(config_file, config_flags);
  11104. } else { /* iax.conf changed, gotta reread users.conf, too */
  11105. ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
  11106. ucfg = ast_config_load("users.conf", config_flags);
  11107. }
  11108. if (reload) {
  11109. set_config_destroy();
  11110. }
  11111. /* Reset global codec prefs */
  11112. memset(&prefs, 0 , sizeof(struct ast_codec_pref));
  11113. /* Reset Global Flags */
  11114. memset(&globalflags, 0, sizeof(globalflags));
  11115. ast_set_flag(&globalflags, IAX_RTUPDATE);
  11116. ast_set_flag(&globalflags, IAX_SHRINKCALLERID);
  11117. #ifdef SO_NO_CHECK
  11118. nochecksums = 0;
  11119. #endif
  11120. min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
  11121. max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
  11122. global_max_trunk_mtu = MAX_TRUNK_MTU;
  11123. global_maxcallno = DEFAULT_MAXCALLNO_LIMIT;
  11124. global_maxcallno_nonval = DEFAULT_MAXCALLNO_LIMIT_NONVAL;
  11125. maxauthreq = 3;
  11126. srvlookup = 0;
  11127. v = ast_variable_browse(cfg, "general");
  11128. /* Seed initial tos value */
  11129. tosval = ast_variable_retrieve(cfg, "general", "tos");
  11130. if (tosval) {
  11131. if (ast_str2tos(tosval, &tos))
  11132. ast_log(LOG_WARNING, "Invalid tos value, refer to QoS documentation\n");
  11133. }
  11134. /* Seed initial cos value */
  11135. tosval = ast_variable_retrieve(cfg, "general", "cos");
  11136. if (tosval) {
  11137. if (ast_str2cos(tosval, &cos))
  11138. ast_log(LOG_WARNING, "Invalid cos value, refer to QoS documentation\n");
  11139. }
  11140. while(v) {
  11141. if (!strcasecmp(v->name, "bindport")){
  11142. if (reload)
  11143. ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
  11144. else
  11145. portno = atoi(v->value);
  11146. } else if (!strcasecmp(v->name, "pingtime"))
  11147. ping_time = atoi(v->value);
  11148. else if (!strcasecmp(v->name, "iaxthreadcount")) {
  11149. if (reload) {
  11150. if (atoi(v->value) != iaxthreadcount)
  11151. ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
  11152. } else {
  11153. iaxthreadcount = atoi(v->value);
  11154. if (iaxthreadcount < 1) {
  11155. ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
  11156. iaxthreadcount = 1;
  11157. } else if (iaxthreadcount > 256) {
  11158. ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
  11159. iaxthreadcount = 256;
  11160. }
  11161. }
  11162. } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
  11163. if (reload) {
  11164. AST_LIST_LOCK(&dynamic_list);
  11165. iaxmaxthreadcount = atoi(v->value);
  11166. AST_LIST_UNLOCK(&dynamic_list);
  11167. } else {
  11168. iaxmaxthreadcount = atoi(v->value);
  11169. if (iaxmaxthreadcount < 0) {
  11170. ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
  11171. iaxmaxthreadcount = 0;
  11172. } else if (iaxmaxthreadcount > 256) {
  11173. ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
  11174. iaxmaxthreadcount = 256;
  11175. }
  11176. }
  11177. } else if (!strcasecmp(v->name, "nochecksums")) {
  11178. #ifdef SO_NO_CHECK
  11179. if (ast_true(v->value))
  11180. nochecksums = 1;
  11181. else
  11182. nochecksums = 0;
  11183. #else
  11184. if (ast_true(v->value))
  11185. ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
  11186. #endif
  11187. }
  11188. else if (!strcasecmp(v->name, "maxjitterbuffer"))
  11189. maxjitterbuffer = atoi(v->value);
  11190. else if (!strcasecmp(v->name, "resyncthreshold"))
  11191. resyncthreshold = atoi(v->value);
  11192. else if (!strcasecmp(v->name, "maxjitterinterps"))
  11193. maxjitterinterps = atoi(v->value);
  11194. else if (!strcasecmp(v->name, "jittertargetextra"))
  11195. jittertargetextra = atoi(v->value);
  11196. else if (!strcasecmp(v->name, "lagrqtime"))
  11197. lagrq_time = atoi(v->value);
  11198. else if (!strcasecmp(v->name, "maxregexpire"))
  11199. max_reg_expire = atoi(v->value);
  11200. else if (!strcasecmp(v->name, "minregexpire"))
  11201. min_reg_expire = atoi(v->value);
  11202. else if (!strcasecmp(v->name, "bindaddr")) {
  11203. if (reload) {
  11204. ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
  11205. } else {
  11206. if (!(ns = ast_netsock_bind(netsock, io, v->value, portno, tos, cos, socket_read, NULL))) {
  11207. ast_log(LOG_WARNING, "Unable apply binding to '%s' at line %d\n", v->value, v->lineno);
  11208. } else {
  11209. if (strchr(v->value, ':'))
  11210. ast_verb(2, "Binding IAX2 to '%s'\n", v->value);
  11211. else
  11212. ast_verb(2, "Binding IAX2 to '%s:%d'\n", v->value, portno);
  11213. if (defaultsockfd < 0)
  11214. defaultsockfd = ast_netsock_sockfd(ns);
  11215. ast_netsock_unref(ns);
  11216. }
  11217. }
  11218. } else if (!strcasecmp(v->name, "authdebug"))
  11219. authdebug = ast_true(v->value);
  11220. else if (!strcasecmp(v->name, "encryption"))
  11221. iax2_encryption = get_encrypt_methods(v->value);
  11222. else if (!strcasecmp(v->name, "transfer")) {
  11223. if (!strcasecmp(v->value, "mediaonly")) {
  11224. ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
  11225. } else if (ast_true(v->value)) {
  11226. ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
  11227. } else
  11228. ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
  11229. } else if (!strcasecmp(v->name, "codecpriority")) {
  11230. if(!strcasecmp(v->value, "caller"))
  11231. ast_set_flag((&globalflags), IAX_CODEC_USER_FIRST);
  11232. else if(!strcasecmp(v->value, "disabled"))
  11233. ast_set_flag((&globalflags), IAX_CODEC_NOPREFS);
  11234. else if(!strcasecmp(v->value, "reqonly")) {
  11235. ast_set_flag((&globalflags), IAX_CODEC_NOCAP);
  11236. ast_set_flag((&globalflags), IAX_CODEC_NOPREFS);
  11237. }
  11238. } else if (!strcasecmp(v->name, "jitterbuffer"))
  11239. ast_set2_flag((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
  11240. else if (!strcasecmp(v->name, "forcejitterbuffer"))
  11241. ast_set2_flag((&globalflags), ast_true(v->value), IAX_FORCEJITTERBUF);
  11242. else if (!strcasecmp(v->name, "delayreject"))
  11243. delayreject = ast_true(v->value);
  11244. else if (!strcasecmp(v->name, "allowfwdownload"))
  11245. ast_set2_flag((&globalflags), ast_true(v->value), IAX_ALLOWFWDOWNLOAD);
  11246. else if (!strcasecmp(v->name, "rtcachefriends"))
  11247. ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
  11248. else if (!strcasecmp(v->name, "rtignoreregexpire"))
  11249. ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
  11250. else if (!strcasecmp(v->name, "rtupdate"))
  11251. ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTUPDATE);
  11252. else if (!strcasecmp(v->name, "trunktimestamps"))
  11253. ast_set2_flag(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
  11254. else if (!strcasecmp(v->name, "rtautoclear")) {
  11255. int i = atoi(v->value);
  11256. if(i > 0)
  11257. global_rtautoclear = i;
  11258. else
  11259. i = 0;
  11260. ast_set2_flag((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
  11261. } else if (!strcasecmp(v->name, "trunkfreq")) {
  11262. trunkfreq = atoi(v->value);
  11263. if (trunkfreq < 10)
  11264. trunkfreq = 10;
  11265. } else if (!strcasecmp(v->name, "trunkmtu")) {
  11266. mtuv = atoi(v->value);
  11267. if (mtuv == 0 )
  11268. global_max_trunk_mtu = 0;
  11269. else if (mtuv >= 172 && mtuv < 4000)
  11270. global_max_trunk_mtu = mtuv;
  11271. else
  11272. ast_log(LOG_NOTICE, "trunkmtu value out of bounds (%d) at line %d\n",
  11273. mtuv, v->lineno);
  11274. } else if (!strcasecmp(v->name, "trunkmaxsize")) {
  11275. trunkmaxsize = atoi(v->value);
  11276. if (trunkmaxsize == 0)
  11277. trunkmaxsize = MAX_TRUNKDATA;
  11278. } else if (!strcasecmp(v->name, "autokill")) {
  11279. if (sscanf(v->value, "%30d", &x) == 1) {
  11280. if (x >= 0)
  11281. autokill = x;
  11282. else
  11283. ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
  11284. } else if (ast_true(v->value)) {
  11285. autokill = DEFAULT_MAXMS;
  11286. } else {
  11287. autokill = 0;
  11288. }
  11289. } else if (!strcasecmp(v->name, "bandwidth")) {
  11290. if (!strcasecmp(v->value, "low")) {
  11291. capability = IAX_CAPABILITY_LOWBANDWIDTH;
  11292. } else if (!strcasecmp(v->value, "medium")) {
  11293. capability = IAX_CAPABILITY_MEDBANDWIDTH;
  11294. } else if (!strcasecmp(v->value, "high")) {
  11295. capability = IAX_CAPABILITY_FULLBANDWIDTH;
  11296. } else
  11297. ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
  11298. } else if (!strcasecmp(v->name, "allow")) {
  11299. ast_parse_allow_disallow(&prefs, &capability, v->value, 1);
  11300. } else if (!strcasecmp(v->name, "disallow")) {
  11301. ast_parse_allow_disallow(&prefs, &capability, v->value, 0);
  11302. } else if (!strcasecmp(v->name, "register")) {
  11303. iax2_register(v->value, v->lineno);
  11304. } else if (!strcasecmp(v->name, "iaxcompat")) {
  11305. iaxcompat = ast_true(v->value);
  11306. } else if (!strcasecmp(v->name, "regcontext")) {
  11307. ast_copy_string(regcontext, v->value, sizeof(regcontext));
  11308. /* Create context if it doesn't exist already */
  11309. ast_context_find_or_create(NULL, NULL, regcontext, "IAX2");
  11310. } else if (!strcasecmp(v->name, "tos")) {
  11311. if (ast_str2tos(v->value, &tos))
  11312. ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
  11313. } else if (!strcasecmp(v->name, "cos")) {
  11314. if (ast_str2cos(v->value, &cos))
  11315. ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
  11316. } else if (!strcasecmp(v->name, "accountcode")) {
  11317. ast_copy_string(accountcode, v->value, sizeof(accountcode));
  11318. } else if (!strcasecmp(v->name, "mohinterpret")) {
  11319. ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
  11320. } else if (!strcasecmp(v->name, "mohsuggest")) {
  11321. ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
  11322. } else if (!strcasecmp(v->name, "amaflags")) {
  11323. format = ast_cdr_amaflags2int(v->value);
  11324. if (format < 0) {
  11325. ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
  11326. } else {
  11327. amaflags = format;
  11328. }
  11329. } else if (!strcasecmp(v->name, "language")) {
  11330. ast_copy_string(language, v->value, sizeof(language));
  11331. } else if (!strcasecmp(v->name, "maxauthreq")) {
  11332. maxauthreq = atoi(v->value);
  11333. if (maxauthreq < 0)
  11334. maxauthreq = 0;
  11335. } else if (!strcasecmp(v->name, "adsi")) {
  11336. adsi = ast_true(v->value);
  11337. } else if (!strcasecmp(v->name, "srvlookup")) {
  11338. srvlookup = ast_true(v->value);
  11339. } else if (!strcasecmp(v->name, "maxcallnumbers")) {
  11340. if (sscanf(v->value, "%10hu", &global_maxcallno) != 1) {
  11341. ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d\n", v->value, v->lineno);
  11342. }
  11343. } else if (!strcasecmp(v->name, "maxcallnumbers_nonvalidated")) {
  11344. if (sscanf(v->value, "%10hu", &global_maxcallno_nonval) != 1) {
  11345. 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);
  11346. }
  11347. } else if (!strcasecmp(v->name, "calltokenoptional")) {
  11348. if (add_calltoken_ignore(v->value)) {
  11349. ast_log(LOG_WARNING, "Invalid calltokenoptional address range - '%s' line %d\n", v->value, v->lineno);
  11350. }
  11351. } else if (!strcasecmp(v->name, "shrinkcallerid")) {
  11352. if (ast_true(v->value)) {
  11353. ast_set_flag((&globalflags), IAX_SHRINKCALLERID);
  11354. } else if (ast_false(v->value)) {
  11355. ast_clear_flag((&globalflags), IAX_SHRINKCALLERID);
  11356. } else {
  11357. ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
  11358. }
  11359. }/*else if (strcasecmp(v->name,"type")) */
  11360. /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
  11361. v = v->next;
  11362. }
  11363. if (defaultsockfd < 0) {
  11364. if (!(ns = ast_netsock_bind(netsock, io, "0.0.0.0", portno, tos, cos, socket_read, NULL))) {
  11365. ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
  11366. } else {
  11367. ast_verb(2, "Binding IAX2 to default address 0.0.0.0:%d\n", portno);
  11368. defaultsockfd = ast_netsock_sockfd(ns);
  11369. ast_netsock_unref(ns);
  11370. }
  11371. }
  11372. if (reload) {
  11373. ast_netsock_release(outsock);
  11374. outsock = ast_netsock_list_alloc();
  11375. if (!outsock) {
  11376. ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
  11377. return -1;
  11378. }
  11379. ast_netsock_init(outsock);
  11380. }
  11381. if (min_reg_expire > max_reg_expire) {
  11382. ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
  11383. min_reg_expire, max_reg_expire, max_reg_expire);
  11384. min_reg_expire = max_reg_expire;
  11385. }
  11386. iax2_capability = capability;
  11387. if (ucfg) {
  11388. struct ast_variable *gen;
  11389. int genhasiax;
  11390. int genregisteriax;
  11391. const char *hasiax, *registeriax;
  11392. genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
  11393. genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
  11394. gen = ast_variable_browse(ucfg, "general");
  11395. cat = ast_category_browse(ucfg, NULL);
  11396. while (cat) {
  11397. if (strcasecmp(cat, "general")) {
  11398. hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
  11399. registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
  11400. if (ast_true(hasiax) || (!hasiax && genhasiax)) {
  11401. /* Start with general parameters, then specific parameters, user and peer */
  11402. user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
  11403. if (user) {
  11404. ao2_link(users, user);
  11405. user = user_unref(user);
  11406. }
  11407. peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
  11408. if (peer) {
  11409. if (ast_test_flag(peer, IAX_DYNAMIC))
  11410. reg_source_db(peer);
  11411. ao2_link(peers, peer);
  11412. peer = peer_unref(peer);
  11413. }
  11414. }
  11415. if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
  11416. char tmp[256];
  11417. const char *host = ast_variable_retrieve(ucfg, cat, "host");
  11418. const char *username = ast_variable_retrieve(ucfg, cat, "username");
  11419. const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
  11420. if (!host)
  11421. host = ast_variable_retrieve(ucfg, "general", "host");
  11422. if (!username)
  11423. username = ast_variable_retrieve(ucfg, "general", "username");
  11424. if (!secret)
  11425. secret = ast_variable_retrieve(ucfg, "general", "secret");
  11426. if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
  11427. if (!ast_strlen_zero(secret))
  11428. snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
  11429. else
  11430. snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
  11431. iax2_register(tmp, 0);
  11432. }
  11433. }
  11434. }
  11435. cat = ast_category_browse(ucfg, cat);
  11436. }
  11437. ast_config_destroy(ucfg);
  11438. }
  11439. cat = ast_category_browse(cfg, NULL);
  11440. while(cat) {
  11441. if (strcasecmp(cat, "general")) {
  11442. utype = ast_variable_retrieve(cfg, cat, "type");
  11443. if (!strcasecmp(cat, "callnumberlimits")) {
  11444. build_callno_limits(ast_variable_browse(cfg, cat));
  11445. } else if (utype) {
  11446. if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
  11447. user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
  11448. if (user) {
  11449. ao2_link(users, user);
  11450. user = user_unref(user);
  11451. }
  11452. }
  11453. if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
  11454. peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
  11455. if (peer) {
  11456. if (ast_test_flag(peer, IAX_DYNAMIC))
  11457. reg_source_db(peer);
  11458. ao2_link(peers, peer);
  11459. peer = peer_unref(peer);
  11460. }
  11461. } else if (strcasecmp(utype, "user")) {
  11462. ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
  11463. }
  11464. } else
  11465. ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
  11466. }
  11467. cat = ast_category_browse(cfg, cat);
  11468. }
  11469. ast_config_destroy(cfg);
  11470. set_timing();
  11471. return 1;
  11472. }
  11473. static void poke_all_peers(void)
  11474. {
  11475. struct ao2_iterator i;
  11476. struct iax2_peer *peer;
  11477. i = ao2_iterator_init(peers, 0);
  11478. while ((peer = ao2_iterator_next(&i))) {
  11479. iax2_poke_peer(peer, 0);
  11480. peer_unref(peer);
  11481. }
  11482. ao2_iterator_destroy(&i);
  11483. }
  11484. static int reload_config(void)
  11485. {
  11486. static const char config[] = "iax.conf";
  11487. struct iax2_registry *reg;
  11488. if (set_config(config, 1) > 0) {
  11489. prune_peers();
  11490. prune_users();
  11491. ao2_callback(callno_limits, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
  11492. ao2_callback(calltoken_ignores, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
  11493. ao2_callback(peercnts, OBJ_NODATA, set_peercnt_limit_all_cb, NULL);
  11494. trunk_timed = trunk_untimed = 0;
  11495. trunk_nmaxmtu = trunk_maxmtu = 0;
  11496. AST_LIST_LOCK(&registrations);
  11497. AST_LIST_TRAVERSE(&registrations, reg, entry)
  11498. iax2_do_register(reg);
  11499. AST_LIST_UNLOCK(&registrations);
  11500. /* Qualify hosts, too */
  11501. poke_all_peers();
  11502. }
  11503. reload_firmware(0);
  11504. iax_provision_reload(1);
  11505. return 0;
  11506. }
  11507. static char *handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  11508. {
  11509. switch (cmd) {
  11510. case CLI_INIT:
  11511. e->command = "iax2 reload";
  11512. e->usage =
  11513. "Usage: iax2 reload\n"
  11514. " Reloads IAX configuration from iax.conf\n";
  11515. return NULL;
  11516. case CLI_GENERATE:
  11517. return NULL;
  11518. }
  11519. reload_config();
  11520. return CLI_SUCCESS;
  11521. }
  11522. static int reload(void)
  11523. {
  11524. return reload_config();
  11525. }
  11526. static int cache_get_callno_locked(const char *data)
  11527. {
  11528. struct sockaddr_in sin;
  11529. int x;
  11530. int callno;
  11531. struct iax_ie_data ied;
  11532. struct create_addr_info cai;
  11533. struct parsed_dial_string pds;
  11534. char *tmpstr;
  11535. for (x = 0; x < ARRAY_LEN(iaxs); x++) {
  11536. /* Look for an *exact match* call. Once a call is negotiated, it can only
  11537. look up entries for a single context */
  11538. if (!ast_mutex_trylock(&iaxsl[x])) {
  11539. if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
  11540. return x;
  11541. ast_mutex_unlock(&iaxsl[x]);
  11542. }
  11543. }
  11544. /* No match found, we need to create a new one */
  11545. memset(&cai, 0, sizeof(cai));
  11546. memset(&ied, 0, sizeof(ied));
  11547. memset(&pds, 0, sizeof(pds));
  11548. tmpstr = ast_strdupa(data);
  11549. parse_dial_string(tmpstr, &pds);
  11550. if (ast_strlen_zero(pds.peer)) {
  11551. ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
  11552. return -1;
  11553. }
  11554. /* Populate our address from the given */
  11555. if (create_addr(pds.peer, NULL, &sin, &cai))
  11556. return -1;
  11557. ast_debug(1, "peer: %s, username: %s, password: %s, context: %s\n",
  11558. pds.peer, pds.username, pds.password, pds.context);
  11559. callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
  11560. if (callno < 1) {
  11561. ast_log(LOG_WARNING, "Unable to create call\n");
  11562. return -1;
  11563. }
  11564. ast_string_field_set(iaxs[callno], dproot, data);
  11565. iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
  11566. iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
  11567. iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, "TBD");
  11568. /* the string format is slightly different from a standard dial string,
  11569. because the context appears in the 'exten' position
  11570. */
  11571. if (pds.exten)
  11572. iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.exten);
  11573. if (pds.username)
  11574. iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
  11575. iax_ie_append_int(&ied, IAX_IE_FORMAT, IAX_CAPABILITY_FULLBANDWIDTH);
  11576. iax_ie_append_int(&ied, IAX_IE_CAPABILITY, IAX_CAPABILITY_FULLBANDWIDTH);
  11577. /* Keep password handy */
  11578. if (pds.password)
  11579. ast_string_field_set(iaxs[callno], secret, pds.password);
  11580. if (pds.key)
  11581. ast_string_field_set(iaxs[callno], outkey, pds.key);
  11582. /* Start the call going */
  11583. add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
  11584. send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
  11585. return callno;
  11586. }
  11587. static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
  11588. {
  11589. struct iax2_dpcache *dp = NULL;
  11590. struct timeval tv = ast_tvnow();
  11591. int x, com[2], timeout, old = 0, outfd, abort, callno;
  11592. struct ast_channel *c = NULL;
  11593. struct ast_frame *f = NULL;
  11594. AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, cache_list) {
  11595. if (ast_tvcmp(tv, dp->expiry) > 0) {
  11596. AST_LIST_REMOVE_CURRENT(cache_list);
  11597. if ((dp->flags & CACHE_FLAG_PENDING) || dp->callno)
  11598. ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp->flags, dp->callno);
  11599. else
  11600. ast_free(dp);
  11601. continue;
  11602. }
  11603. if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
  11604. break;
  11605. }
  11606. AST_LIST_TRAVERSE_SAFE_END;
  11607. if (!dp) {
  11608. /* No matching entry. Create a new one. */
  11609. /* First, can we make a callno? */
  11610. if ((callno = cache_get_callno_locked(data)) < 0) {
  11611. ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
  11612. return NULL;
  11613. }
  11614. if (!(dp = ast_calloc(1, sizeof(*dp)))) {
  11615. ast_mutex_unlock(&iaxsl[callno]);
  11616. return NULL;
  11617. }
  11618. ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
  11619. ast_copy_string(dp->exten, exten, sizeof(dp->exten));
  11620. dp->expiry = ast_tvnow();
  11621. dp->orig = dp->expiry;
  11622. /* Expires in 30 mins by default */
  11623. dp->expiry.tv_sec += iaxdefaultdpcache;
  11624. dp->flags = CACHE_FLAG_PENDING;
  11625. for (x = 0; x < ARRAY_LEN(dp->waiters); x++)
  11626. dp->waiters[x] = -1;
  11627. /* Insert into the lists */
  11628. AST_LIST_INSERT_TAIL(&dpcache, dp, cache_list);
  11629. AST_LIST_INSERT_TAIL(&iaxs[callno]->dpentries, dp, peer_list);
  11630. /* Send the request if we're already up */
  11631. if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
  11632. iax2_dprequest(dp, callno);
  11633. ast_mutex_unlock(&iaxsl[callno]);
  11634. }
  11635. /* By here we must have a dp */
  11636. if (dp->flags & CACHE_FLAG_PENDING) {
  11637. /* Okay, here it starts to get nasty. We need a pipe now to wait
  11638. for a reply to come back so long as it's pending */
  11639. for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
  11640. /* Find an empty slot */
  11641. if (dp->waiters[x] < 0)
  11642. break;
  11643. }
  11644. if (x >= ARRAY_LEN(dp->waiters)) {
  11645. ast_log(LOG_WARNING, "No more waiter positions available\n");
  11646. return NULL;
  11647. }
  11648. if (pipe(com)) {
  11649. ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
  11650. return NULL;
  11651. }
  11652. dp->waiters[x] = com[1];
  11653. /* Okay, now we wait */
  11654. timeout = iaxdefaulttimeout * 1000;
  11655. /* Temporarily unlock */
  11656. AST_LIST_UNLOCK(&dpcache);
  11657. /* Defer any dtmf */
  11658. if (chan)
  11659. old = ast_channel_defer_dtmf(chan);
  11660. abort = 0;
  11661. while(timeout) {
  11662. c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &timeout);
  11663. if (outfd > -1)
  11664. break;
  11665. if (!c)
  11666. continue;
  11667. if (!(f = ast_read(c))) {
  11668. abort = 1;
  11669. break;
  11670. }
  11671. ast_frfree(f);
  11672. }
  11673. if (!timeout) {
  11674. ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
  11675. }
  11676. AST_LIST_LOCK(&dpcache);
  11677. dp->waiters[x] = -1;
  11678. close(com[1]);
  11679. close(com[0]);
  11680. if (abort) {
  11681. /* Don't interpret anything, just abort. Not sure what th epoint
  11682. of undeferring dtmf on a hung up channel is but hey whatever */
  11683. if (!old && chan)
  11684. ast_channel_undefer_dtmf(chan);
  11685. return NULL;
  11686. }
  11687. if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
  11688. /* Now to do non-independent analysis the results of our wait */
  11689. if (dp->flags & CACHE_FLAG_PENDING) {
  11690. /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
  11691. pending. Don't let it take as long to timeout. */
  11692. dp->flags &= ~CACHE_FLAG_PENDING;
  11693. dp->flags |= CACHE_FLAG_TIMEOUT;
  11694. /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
  11695. systems without leaving it unavailable once the server comes back online */
  11696. dp->expiry.tv_sec = dp->orig.tv_sec + 60;
  11697. for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
  11698. if (dp->waiters[x] > -1) {
  11699. if (write(dp->waiters[x], "asdf", 4) < 0) {
  11700. ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
  11701. }
  11702. }
  11703. }
  11704. }
  11705. }
  11706. /* Our caller will obtain the rest */
  11707. if (!old && chan)
  11708. ast_channel_undefer_dtmf(chan);
  11709. }
  11710. return dp;
  11711. }
  11712. /*! \brief Part of the IAX2 switch interface */
  11713. static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
  11714. {
  11715. int res = 0;
  11716. struct iax2_dpcache *dp = NULL;
  11717. #if 0
  11718. ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
  11719. #endif
  11720. if ((priority != 1) && (priority != 2))
  11721. return 0;
  11722. AST_LIST_LOCK(&dpcache);
  11723. if ((dp = find_cache(chan, data, context, exten, priority))) {
  11724. if (dp->flags & CACHE_FLAG_EXISTS)
  11725. res = 1;
  11726. } else {
  11727. ast_log(LOG_WARNING, "Unable to make DP cache\n");
  11728. }
  11729. AST_LIST_UNLOCK(&dpcache);
  11730. return res;
  11731. }
  11732. /*! \brief part of the IAX2 dial plan switch interface */
  11733. static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
  11734. {
  11735. int res = 0;
  11736. struct iax2_dpcache *dp = NULL;
  11737. #if 0
  11738. ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
  11739. #endif
  11740. if ((priority != 1) && (priority != 2))
  11741. return 0;
  11742. AST_LIST_LOCK(&dpcache);
  11743. if ((dp = find_cache(chan, data, context, exten, priority))) {
  11744. if (dp->flags & CACHE_FLAG_CANEXIST)
  11745. res = 1;
  11746. } else {
  11747. ast_log(LOG_WARNING, "Unable to make DP cache\n");
  11748. }
  11749. AST_LIST_UNLOCK(&dpcache);
  11750. return res;
  11751. }
  11752. /*! \brief Part of the IAX2 Switch interface */
  11753. static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
  11754. {
  11755. int res = 0;
  11756. struct iax2_dpcache *dp = NULL;
  11757. #if 0
  11758. ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
  11759. #endif
  11760. if ((priority != 1) && (priority != 2))
  11761. return 0;
  11762. AST_LIST_LOCK(&dpcache);
  11763. if ((dp = find_cache(chan, data, context, exten, priority))) {
  11764. if (dp->flags & CACHE_FLAG_MATCHMORE)
  11765. res = 1;
  11766. } else {
  11767. ast_log(LOG_WARNING, "Unable to make DP cache\n");
  11768. }
  11769. AST_LIST_UNLOCK(&dpcache);
  11770. return res;
  11771. }
  11772. /*! \brief Execute IAX2 dialplan switch */
  11773. static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
  11774. {
  11775. char odata[256];
  11776. char req[256];
  11777. char *ncontext;
  11778. struct iax2_dpcache *dp = NULL;
  11779. struct ast_app *dial = NULL;
  11780. #if 0
  11781. 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);
  11782. #endif
  11783. if (priority == 2) {
  11784. /* Indicate status, can be overridden in dialplan */
  11785. const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
  11786. if (dialstatus) {
  11787. dial = pbx_findapp(dialstatus);
  11788. if (dial)
  11789. pbx_exec(chan, dial, "");
  11790. }
  11791. return -1;
  11792. } else if (priority != 1)
  11793. return -1;
  11794. AST_LIST_LOCK(&dpcache);
  11795. if ((dp = find_cache(chan, data, context, exten, priority))) {
  11796. if (dp->flags & CACHE_FLAG_EXISTS) {
  11797. ast_copy_string(odata, data, sizeof(odata));
  11798. ncontext = strchr(odata, '/');
  11799. if (ncontext) {
  11800. *ncontext = '\0';
  11801. ncontext++;
  11802. snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
  11803. } else {
  11804. snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
  11805. }
  11806. ast_verb(3, "Executing Dial('%s')\n", req);
  11807. } else {
  11808. AST_LIST_UNLOCK(&dpcache);
  11809. ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
  11810. return -1;
  11811. }
  11812. }
  11813. AST_LIST_UNLOCK(&dpcache);
  11814. if ((dial = pbx_findapp("Dial")))
  11815. return pbx_exec(chan, dial, req);
  11816. else
  11817. ast_log(LOG_WARNING, "No dial application registered\n");
  11818. return -1;
  11819. }
  11820. static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  11821. {
  11822. struct iax2_peer *peer;
  11823. char *peername, *colname;
  11824. peername = ast_strdupa(data);
  11825. /* if our channel, return the IP address of the endpoint of current channel */
  11826. if (!strcmp(peername,"CURRENTCHANNEL")) {
  11827. unsigned short callno;
  11828. if (chan->tech != &iax2_tech)
  11829. return -1;
  11830. callno = PTR_TO_CALLNO(chan->tech_pvt);
  11831. ast_copy_string(buf, iaxs[callno]->addr.sin_addr.s_addr ? ast_inet_ntoa(iaxs[callno]->addr.sin_addr) : "", len);
  11832. return 0;
  11833. }
  11834. if ((colname = strchr(peername, ',')))
  11835. *colname++ = '\0';
  11836. else
  11837. colname = "ip";
  11838. if (!(peer = find_peer(peername, 1)))
  11839. return -1;
  11840. if (!strcasecmp(colname, "ip")) {
  11841. ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
  11842. } else if (!strcasecmp(colname, "status")) {
  11843. peer_status(peer, buf, len);
  11844. } else if (!strcasecmp(colname, "mailbox")) {
  11845. ast_copy_string(buf, peer->mailbox, len);
  11846. } else if (!strcasecmp(colname, "context")) {
  11847. ast_copy_string(buf, peer->context, len);
  11848. } else if (!strcasecmp(colname, "expire")) {
  11849. snprintf(buf, len, "%d", peer->expire);
  11850. } else if (!strcasecmp(colname, "dynamic")) {
  11851. ast_copy_string(buf, (ast_test_flag(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
  11852. } else if (!strcasecmp(colname, "callerid_name")) {
  11853. ast_copy_string(buf, peer->cid_name, len);
  11854. } else if (!strcasecmp(colname, "callerid_num")) {
  11855. ast_copy_string(buf, peer->cid_num, len);
  11856. } else if (!strcasecmp(colname, "codecs")) {
  11857. ast_getformatname_multiple(buf, len -1, peer->capability);
  11858. } else if (!strncasecmp(colname, "codec[", 6)) {
  11859. char *codecnum, *ptr;
  11860. int index = 0, codec = 0;
  11861. codecnum = strchr(colname, '[');
  11862. *codecnum = '\0';
  11863. codecnum++;
  11864. if ((ptr = strchr(codecnum, ']'))) {
  11865. *ptr = '\0';
  11866. }
  11867. index = atoi(codecnum);
  11868. if((codec = ast_codec_pref_index(&peer->prefs, index))) {
  11869. ast_copy_string(buf, ast_getformatname(codec), len);
  11870. }
  11871. }
  11872. peer_unref(peer);
  11873. return 0;
  11874. }
  11875. struct ast_custom_function iaxpeer_function = {
  11876. .name = "IAXPEER",
  11877. .synopsis = "Gets IAX peer information",
  11878. .syntax = "IAXPEER(<peername|CURRENTCHANNEL>[,item])",
  11879. .read = function_iaxpeer,
  11880. .desc = "If peername specified, valid items are:\n"
  11881. "- ip (default) The IP address.\n"
  11882. "- status The peer's status (if qualify=yes)\n"
  11883. "- mailbox The configured mailbox.\n"
  11884. "- context The configured context.\n"
  11885. "- expire The epoch time of the next expire.\n"
  11886. "- dynamic Is it dynamic? (yes/no).\n"
  11887. "- callerid_name The configured Caller ID name.\n"
  11888. "- callerid_num The configured Caller ID number.\n"
  11889. "- codecs The configured codecs.\n"
  11890. "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
  11891. "\n"
  11892. "If CURRENTCHANNEL specified, returns IP address of current channel\n"
  11893. "\n"
  11894. };
  11895. static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *args, char *buf, size_t buflen)
  11896. {
  11897. struct chan_iax2_pvt *pvt;
  11898. unsigned int callno;
  11899. int res = 0;
  11900. if (!chan || chan->tech != &iax2_tech) {
  11901. ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
  11902. return -1;
  11903. }
  11904. callno = PTR_TO_CALLNO(chan->tech_pvt);
  11905. ast_mutex_lock(&iaxsl[callno]);
  11906. if (!(pvt = iaxs[callno])) {
  11907. ast_mutex_unlock(&iaxsl[callno]);
  11908. return -1;
  11909. }
  11910. if (!strcasecmp(args, "osptoken"))
  11911. ast_copy_string(buf, pvt->osptoken, buflen);
  11912. else
  11913. res = -1;
  11914. ast_mutex_unlock(&iaxsl[callno]);
  11915. return res;
  11916. }
  11917. /*! \brief Part of the device state notification system ---*/
  11918. static int iax2_devicestate(void *data)
  11919. {
  11920. struct parsed_dial_string pds;
  11921. char *tmp = ast_strdupa(data);
  11922. struct iax2_peer *p;
  11923. int res = AST_DEVICE_INVALID;
  11924. memset(&pds, 0, sizeof(pds));
  11925. parse_dial_string(tmp, &pds);
  11926. if (ast_strlen_zero(pds.peer)) {
  11927. ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
  11928. return res;
  11929. }
  11930. ast_debug(3, "Checking device state for device %s\n", pds.peer);
  11931. /* SLD: FIXME: second call to find_peer during registration */
  11932. if (!(p = find_peer(pds.peer, 1)))
  11933. return res;
  11934. res = AST_DEVICE_UNAVAILABLE;
  11935. ast_debug(3, "iax2_devicestate: Found peer. What's device state of %s? addr=%d, defaddr=%d maxms=%d, lastms=%d\n",
  11936. pds.peer, p->addr.sin_addr.s_addr, p->defaddr.sin_addr.s_addr, p->maxms, p->lastms);
  11937. if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
  11938. (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
  11939. /* Peer is registered, or have default IP address
  11940. and a valid registration */
  11941. if (p->historicms == 0 || p->historicms <= p->maxms)
  11942. /* let the core figure out whether it is in use or not */
  11943. res = AST_DEVICE_UNKNOWN;
  11944. }
  11945. peer_unref(p);
  11946. return res;
  11947. }
  11948. static struct ast_switch iax2_switch =
  11949. {
  11950. name: "IAX2",
  11951. description: "IAX Remote Dialplan Switch",
  11952. exists: iax2_exists,
  11953. canmatch: iax2_canmatch,
  11954. exec: iax2_exec,
  11955. matchmore: iax2_matchmore,
  11956. };
  11957. /*
  11958. { { "iax2", "show", "cache", NULL },
  11959. iax2_show_cache, "Display IAX cached dialplan",
  11960. show_cache_usage },
  11961. { { "iax2", "show", "channels", NULL },
  11962. iax2_show_channels, "List active IAX channels",
  11963. show_channels_usage },
  11964. { { "iax2", "show", "firmware", NULL },
  11965. iax2_show_firmware, "List available IAX firmwares",
  11966. show_firmware_usage },
  11967. { { "iax2", "show", "netstats", NULL },
  11968. iax2_show_netstats, "List active IAX channel netstats",
  11969. show_netstats_usage },
  11970. { { "iax2", "show", "peers", NULL },
  11971. iax2_show_peers, "List defined IAX peers",
  11972. show_peers_usage },
  11973. { { "iax2", "show", "registry", NULL },
  11974. iax2_show_registry, "Display IAX registration status",
  11975. show_reg_usage },
  11976. { { "iax2", "show", "stats", NULL },
  11977. iax2_show_stats, "Display IAX statistics",
  11978. show_stats_usage },
  11979. { { "iax2", "show", "threads", NULL },
  11980. iax2_show_threads, "Display IAX helper thread info",
  11981. show_threads_usage },
  11982. { { "iax2", "unregister", NULL },
  11983. iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry",
  11984. unregister_usage, complete_iax2_unregister },
  11985. { { "iax2", "set", "mtu", NULL },
  11986. iax2_set_mtu, "Set the IAX systemwide trunking MTU",
  11987. set_mtu_usage, NULL, NULL },
  11988. { { "iax2", "show", "users", NULL },
  11989. iax2_show_users, "List defined IAX users",
  11990. show_users_usage },
  11991. { { "iax2", "prune", "realtime", NULL },
  11992. iax2_prune_realtime, "Prune a cached realtime lookup",
  11993. prune_realtime_usage, complete_iax2_show_peer },
  11994. { { "iax2", "reload", NULL },
  11995. iax2_reload, "Reload IAX configuration",
  11996. iax2_reload_usage },
  11997. { { "iax2", "show", "peer", NULL },
  11998. iax2_show_peer, "Show details on specific IAX peer",
  11999. show_peer_usage, complete_iax2_show_peer },
  12000. { { "iax2", "set", "debug", NULL },
  12001. iax2_do_debug, "Enable IAX debugging",
  12002. debug_usage },
  12003. { { "iax2", "set", "debug", "trunk", NULL },
  12004. iax2_do_trunk_debug, "Enable IAX trunk debugging",
  12005. debug_trunk_usage },
  12006. { { "iax2", "set", "debug", "jb", NULL },
  12007. iax2_do_jb_debug, "Enable IAX jitterbuffer debugging",
  12008. debug_jb_usage },
  12009. { { "iax2", "set", "debug", "off", NULL },
  12010. iax2_no_debug, "Disable IAX debugging",
  12011. no_debug_usage },
  12012. { { "iax2", "set", "debug", "trunk", "off", NULL },
  12013. iax2_no_trunk_debug, "Disable IAX trunk debugging",
  12014. no_debug_trunk_usage },
  12015. { { "iax2", "set", "debug", "jb", "off", NULL },
  12016. iax2_no_jb_debug, "Disable IAX jitterbuffer debugging",
  12017. no_debug_jb_usage },
  12018. { { "iax2", "test", "losspct", NULL },
  12019. iax2_test_losspct, "Set IAX2 incoming frame loss percentage",
  12020. iax2_test_losspct_usage },
  12021. { { "iax2", "provision", NULL },
  12022. iax2_prov_cmd, "Provision an IAX device",
  12023. show_prov_usage, iax2_prov_complete_template_3rd },
  12024. #ifdef IAXTESTS
  12025. { { "iax2", "test", "late", NULL },
  12026. iax2_test_late, "Test the receipt of a late frame",
  12027. iax2_test_late_usage },
  12028. { { "iax2", "test", "resync", NULL },
  12029. iax2_test_resync, "Test a resync in received timestamps",
  12030. iax2_test_resync_usage },
  12031. { { "iax2", "test", "jitter", NULL },
  12032. iax2_test_jitter, "Simulates jitter for testing",
  12033. iax2_test_jitter_usage },
  12034. #endif
  12035. */
  12036. static struct ast_cli_entry cli_iax2_set_debug_deprecated = AST_CLI_DEFINE(handle_cli_iax2_set_debug_deprecated, "Enable/Disable IAX debugging");
  12037. static struct ast_cli_entry cli_iax2_set_debug_trunk_deprecated = AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk_deprecated, "Enable/Disable IAX debugging");
  12038. static struct ast_cli_entry cli_iax2_set_debug_jb_deprecated = AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb_deprecated, "Enable/Disable IAX debugging");
  12039. static struct ast_cli_entry cli_iax2[] = {
  12040. AST_CLI_DEFINE(handle_cli_iax2_provision, "Provision an IAX device"),
  12041. AST_CLI_DEFINE(handle_cli_iax2_prune_realtime, "Prune a cached realtime lookup"),
  12042. AST_CLI_DEFINE(handle_cli_iax2_reload, "Reload IAX configuration"),
  12043. AST_CLI_DEFINE(handle_cli_iax2_set_mtu, "Set the IAX systemwide trunking MTU"),
  12044. AST_CLI_DEFINE(handle_cli_iax2_set_debug, "Enable/Disable IAX debugging", .deprecate_cmd = &cli_iax2_set_debug_deprecated),
  12045. AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk, "Enable/Disable IAX trunk debugging", .deprecate_cmd = &cli_iax2_set_debug_trunk_deprecated),
  12046. AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb, "Enable/Disable IAX jitterbuffer debugging", .deprecate_cmd = &cli_iax2_set_debug_jb_deprecated),
  12047. AST_CLI_DEFINE(handle_cli_iax2_show_cache, "Display IAX cached dialplan"),
  12048. AST_CLI_DEFINE(handle_cli_iax2_show_channels, "List active IAX channels"),
  12049. AST_CLI_DEFINE(handle_cli_iax2_show_firmware, "List available IAX firmware"),
  12050. AST_CLI_DEFINE(handle_cli_iax2_show_netstats, "List active IAX channel netstats"),
  12051. AST_CLI_DEFINE(handle_cli_iax2_show_peer, "Show details on specific IAX peer"),
  12052. AST_CLI_DEFINE(handle_cli_iax2_show_peers, "List defined IAX peers"),
  12053. AST_CLI_DEFINE(handle_cli_iax2_show_registry, "Display IAX registration status"),
  12054. AST_CLI_DEFINE(handle_cli_iax2_show_stats, "Display IAX statistics"),
  12055. AST_CLI_DEFINE(handle_cli_iax2_show_threads, "Display IAX helper thread info"),
  12056. AST_CLI_DEFINE(handle_cli_iax2_show_users, "List defined IAX users"),
  12057. AST_CLI_DEFINE(handle_cli_iax2_test_losspct, "Set IAX2 incoming frame loss percentage"),
  12058. AST_CLI_DEFINE(handle_cli_iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry"),
  12059. AST_CLI_DEFINE(handle_cli_iax2_show_callno_limits, "Show current entries in IP call number limit table"),
  12060. #ifdef IAXTESTS
  12061. AST_CLI_DEFINE(handle_cli_iax2_test_jitter, "Simulates jitter for testing"),
  12062. AST_CLI_DEFINE(handle_cli_iax2_test_late, "Test the receipt of a late frame"),
  12063. AST_CLI_DEFINE(handle_cli_iax2_test_resync, "Test a resync in received timestamps"),
  12064. #endif /* IAXTESTS */
  12065. };
  12066. static int __unload_module(void)
  12067. {
  12068. struct iax2_thread *thread = NULL;
  12069. struct ast_context *con;
  12070. int x;
  12071. /* Make sure threads do not hold shared resources when they are canceled */
  12072. /* Grab the sched lock resource to keep it away from threads about to die */
  12073. /* Cancel the network thread, close the net socket */
  12074. if (netthreadid != AST_PTHREADT_NULL) {
  12075. AST_LIST_LOCK(&frame_queue);
  12076. ast_mutex_lock(&sched_lock);
  12077. pthread_cancel(netthreadid);
  12078. ast_cond_signal(&sched_cond);
  12079. ast_mutex_unlock(&sched_lock); /* Release the schedule lock resource */
  12080. AST_LIST_UNLOCK(&frame_queue);
  12081. pthread_join(netthreadid, NULL);
  12082. }
  12083. if (schedthreadid != AST_PTHREADT_NULL) {
  12084. ast_mutex_lock(&sched_lock);
  12085. pthread_cancel(schedthreadid);
  12086. ast_cond_signal(&sched_cond);
  12087. ast_mutex_unlock(&sched_lock);
  12088. pthread_join(schedthreadid, NULL);
  12089. }
  12090. /* Call for all threads to halt */
  12091. AST_LIST_LOCK(&idle_list);
  12092. while ((thread = AST_LIST_REMOVE_HEAD(&idle_list, list)))
  12093. pthread_cancel(thread->threadid);
  12094. AST_LIST_UNLOCK(&idle_list);
  12095. AST_LIST_LOCK(&active_list);
  12096. while ((thread = AST_LIST_REMOVE_HEAD(&active_list, list)))
  12097. pthread_cancel(thread->threadid);
  12098. AST_LIST_UNLOCK(&active_list);
  12099. AST_LIST_LOCK(&dynamic_list);
  12100. while ((thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list)))
  12101. pthread_cancel(thread->threadid);
  12102. AST_LIST_UNLOCK(&dynamic_list);
  12103. /* Wait for threads to exit */
  12104. while(0 < iaxactivethreadcount)
  12105. usleep(10000);
  12106. ast_netsock_release(netsock);
  12107. ast_netsock_release(outsock);
  12108. for (x = 0; x < ARRAY_LEN(iaxs); x++) {
  12109. if (iaxs[x]) {
  12110. iax2_destroy(x);
  12111. }
  12112. }
  12113. ast_manager_unregister( "IAXpeers" );
  12114. ast_manager_unregister( "IAXpeerlist" );
  12115. ast_manager_unregister( "IAXnetstats" );
  12116. ast_unregister_application(papp);
  12117. ast_cli_unregister_multiple(cli_iax2, sizeof(cli_iax2) / sizeof(struct ast_cli_entry));
  12118. ast_unregister_switch(&iax2_switch);
  12119. ast_channel_unregister(&iax2_tech);
  12120. delete_users();
  12121. iax_provision_unload();
  12122. sched_context_destroy(sched);
  12123. reload_firmware(1);
  12124. for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
  12125. ast_mutex_destroy(&iaxsl[x]);
  12126. }
  12127. ao2_ref(peers, -1);
  12128. ao2_ref(users, -1);
  12129. ao2_ref(iax_peercallno_pvts, -1);
  12130. ao2_ref(iax_transfercallno_pvts, -1);
  12131. ao2_ref(peercnts, -1);
  12132. ao2_ref(callno_limits, -1);
  12133. ao2_ref(calltoken_ignores, -1);
  12134. ao2_ref(callno_pool, -1);
  12135. ao2_ref(callno_pool_trunk, -1);
  12136. con = ast_context_find(regcontext);
  12137. if (con)
  12138. ast_context_destroy(con, "IAX2");
  12139. return 0;
  12140. }
  12141. static int unload_module(void)
  12142. {
  12143. ast_custom_function_unregister(&iaxpeer_function);
  12144. ast_custom_function_unregister(&iaxvar_function);
  12145. return __unload_module();
  12146. }
  12147. static int peer_set_sock_cb(void *obj, void *arg, int flags)
  12148. {
  12149. struct iax2_peer *peer = obj;
  12150. if (peer->sockfd < 0)
  12151. peer->sockfd = defaultsockfd;
  12152. return 0;
  12153. }
  12154. static int pvt_hash_cb(const void *obj, const int flags)
  12155. {
  12156. const struct chan_iax2_pvt *pvt = obj;
  12157. return pvt->peercallno;
  12158. }
  12159. static int pvt_cmp_cb(void *obj, void *arg, int flags)
  12160. {
  12161. struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
  12162. /* The frames_received field is used to hold whether we're matching
  12163. * against a full frame or not ... */
  12164. return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt,
  12165. pvt2->frames_received) ? CMP_MATCH : 0;
  12166. }
  12167. static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
  12168. {
  12169. const struct chan_iax2_pvt *pvt = obj;
  12170. return pvt->transfercallno;
  12171. }
  12172. static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
  12173. {
  12174. struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
  12175. /* The frames_received field is used to hold whether we're matching
  12176. * against a full frame or not ... */
  12177. return match(&pvt2->transfer, pvt2->transfercallno, pvt2->callno, pvt,
  12178. pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
  12179. }
  12180. static int load_objects(void)
  12181. {
  12182. peers = users = iax_peercallno_pvts = iax_transfercallno_pvts = NULL;
  12183. peercnts = callno_limits = calltoken_ignores = callno_pool = callno_pool_trunk = NULL;
  12184. if (!(peers = ao2_container_alloc(MAX_PEER_BUCKETS, peer_hash_cb, peer_cmp_cb))) {
  12185. goto container_fail;
  12186. } else if (!(users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_cb, user_cmp_cb))) {
  12187. goto container_fail;
  12188. } else if (!(iax_peercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, pvt_hash_cb, pvt_cmp_cb))) {
  12189. goto container_fail;
  12190. } else if (!(iax_transfercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, transfercallno_pvt_hash_cb, transfercallno_pvt_cmp_cb))) {
  12191. goto container_fail;
  12192. } else if (!(peercnts = ao2_container_alloc(MAX_PEER_BUCKETS, peercnt_hash_cb, peercnt_cmp_cb))) {
  12193. goto container_fail;
  12194. } else if (!(callno_limits = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
  12195. goto container_fail;
  12196. } else if (!(calltoken_ignores = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
  12197. goto container_fail;
  12198. } else if (create_callno_pools()) {
  12199. goto container_fail;
  12200. }
  12201. return 0;
  12202. container_fail:
  12203. if (peers) {
  12204. ao2_ref(peers, -1);
  12205. }
  12206. if (users) {
  12207. ao2_ref(users, -1);
  12208. }
  12209. if (iax_peercallno_pvts) {
  12210. ao2_ref(iax_peercallno_pvts, -1);
  12211. }
  12212. if (iax_transfercallno_pvts) {
  12213. ao2_ref(iax_transfercallno_pvts, -1);
  12214. }
  12215. if (peercnts) {
  12216. ao2_ref(peercnts, -1);
  12217. }
  12218. if (callno_limits) {
  12219. ao2_ref(callno_limits, -1);
  12220. }
  12221. if (calltoken_ignores) {
  12222. ao2_ref(calltoken_ignores, -1);
  12223. }
  12224. if (callno_pool) {
  12225. ao2_ref(callno_pool, -1);
  12226. }
  12227. if (callno_pool_trunk) {
  12228. ao2_ref(callno_pool_trunk, -1);
  12229. }
  12230. return AST_MODULE_LOAD_FAILURE;
  12231. }
  12232. /*! \brief Load IAX2 module, load configuraiton ---*/
  12233. static int load_module(void)
  12234. {
  12235. static const char config[] = "iax.conf";
  12236. int x = 0;
  12237. struct iax2_registry *reg = NULL;
  12238. if (load_objects()) {
  12239. return AST_MODULE_LOAD_FAILURE;
  12240. }
  12241. randomcalltokendata = ast_random();
  12242. ast_custom_function_register(&iaxpeer_function);
  12243. ast_custom_function_register(&iaxvar_function);
  12244. iax_set_output(iax_debug_output);
  12245. iax_set_error(iax_error_output);
  12246. jb_setoutput(jb_error_output, jb_warning_output, NULL);
  12247. #ifdef HAVE_DAHDI
  12248. #ifdef DAHDI_TIMERACK
  12249. timingfd = open("/dev/dahdi/timer", O_RDWR);
  12250. if (timingfd < 0)
  12251. #endif
  12252. timingfd = open("/dev/dahdi/pseudo", O_RDWR);
  12253. if (timingfd < 0)
  12254. ast_log(LOG_WARNING, "Unable to open IAX timing interface: %s\n", strerror(errno));
  12255. #endif
  12256. memset(iaxs, 0, sizeof(iaxs));
  12257. for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
  12258. ast_mutex_init(&iaxsl[x]);
  12259. }
  12260. ast_cond_init(&sched_cond, NULL);
  12261. if (!(sched = sched_context_create())) {
  12262. ast_log(LOG_ERROR, "Failed to create scheduler context\n");
  12263. return AST_MODULE_LOAD_FAILURE;
  12264. }
  12265. if (!(io = io_context_create())) {
  12266. ast_log(LOG_ERROR, "Failed to create I/O context\n");
  12267. sched_context_destroy(sched);
  12268. return AST_MODULE_LOAD_FAILURE;
  12269. }
  12270. if (!(netsock = ast_netsock_list_alloc())) {
  12271. ast_log(LOG_ERROR, "Failed to create netsock list\n");
  12272. io_context_destroy(io);
  12273. sched_context_destroy(sched);
  12274. return AST_MODULE_LOAD_FAILURE;
  12275. }
  12276. ast_netsock_init(netsock);
  12277. outsock = ast_netsock_list_alloc();
  12278. if (!outsock) {
  12279. ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
  12280. io_context_destroy(io);
  12281. sched_context_destroy(sched);
  12282. return AST_MODULE_LOAD_FAILURE;
  12283. }
  12284. ast_netsock_init(outsock);
  12285. ast_cli_register_multiple(cli_iax2, sizeof(cli_iax2) / sizeof(struct ast_cli_entry));
  12286. ast_register_application(papp, iax2_prov_app, psyn, pdescrip);
  12287. ast_manager_register( "IAXpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peers, "List IAX Peers" );
  12288. ast_manager_register( "IAXpeerlist", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peer_list, "List IAX Peers" );
  12289. ast_manager_register( "IAXnetstats", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_netstats, "Show IAX Netstats" );
  12290. if(set_config(config, 0) == -1)
  12291. return AST_MODULE_LOAD_DECLINE;
  12292. if (ast_channel_register(&iax2_tech)) {
  12293. ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
  12294. __unload_module();
  12295. return AST_MODULE_LOAD_FAILURE;
  12296. }
  12297. if (ast_register_switch(&iax2_switch))
  12298. ast_log(LOG_ERROR, "Unable to register IAX switch\n");
  12299. if (start_network_thread()) {
  12300. ast_log(LOG_ERROR, "Unable to start network thread\n");
  12301. __unload_module();
  12302. return AST_MODULE_LOAD_FAILURE;
  12303. } else
  12304. ast_verb(2, "IAX Ready and Listening\n");
  12305. AST_LIST_LOCK(&registrations);
  12306. AST_LIST_TRAVERSE(&registrations, reg, entry)
  12307. iax2_do_register(reg);
  12308. AST_LIST_UNLOCK(&registrations);
  12309. ao2_callback(peers, 0, peer_set_sock_cb, NULL);
  12310. ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
  12311. reload_firmware(0);
  12312. iax_provision_reload(0);
  12313. return AST_MODULE_LOAD_SUCCESS;
  12314. }
  12315. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Inter Asterisk eXchange (Ver 2)",
  12316. .load = load_module,
  12317. .unload = unload_module,
  12318. .reload = reload,
  12319. );